python-3.x - 如何在同步测试类中使用 pyfakefs 测试 aiofile
问题描述
考虑模块中的功能。
async def _get_user_mapping():
async with aiofiles.open('/etc/subuid') as f:
async for line in f:
print(line)
还有一个测试班
from atestfile import _get_user_mapping
class TestFS(fake_filesystem_unittest.TestCase):
def setUp(self):
self.a_required_class_parameter = True
self.setUpPyfakefs()
for file_path in ['/etc/subuid']:
self.fs.create_file(file_path, contents = """testuser:100000:65536
testuser2:165536:65536""")
def test(self):
if self.a_required_class_parameter:
asyncio.get_event_loop().run_until_complete(_get_user_mapping())
在此示例中,测试函数应设置 pyfakefs 以提供假文件。不幸的是,aiofiles 无权访问该文件,打印输出是系统上的真实文件。
有谁知道我如何修补 aiofiles 事件循环以使用 pyfakefs 作为假文件系统?在测试中,我使用名为pytest-aiofiles
(听起来像我需要的,对吗?)的库找到了以下代码片段,但它们显示的示例:
@pytest.mark.asyncio
async def test_stuff(self):
filename = 'test'
etc.....
如果我将mark.asyncio
装饰器添加到test
类方法中,则导入的函数无法访问方法中生成的假文件setUp
。
我假设我遗漏了一些简单的东西,所以这一切都可以分解为一个简单的问题:我到底该如何测试这个?
谢谢!
解决方案
您可以创建一个类来完全修补“aiofiles”吗?
class FakeAiofiles
def open():
# return the open fake file you created in the test
然后在您的测试中,使用:
def test(self):
with mock.patch('atestfile.aiofiles', return_value=FakeAiofiles)
if self.a_required_class_parameter:
asyncio.get_event_loop().run_until_complete(_get_user_mapping())
推荐阅读
- actions-on-google - 我可以从 Google ID 令牌中获取街道地址、电话、性别吗?
- xcode - Unable to Install Erlang using asdf on OSX 10.15.4
- javascript - 如何获取一天的开始和结束的 UNIX 时间戳?
- android - ScrollView not scrolling properly?
- python - 在 Plotly 中在图的底部显示所有子图的迹线值
- vue.js - Vuetify 输入字段图形故障(名称被删除)
- javascript - Javascript null value
- movesense - WbCmd Movesense:放置对象的麻烦
- ruby - centos 7上的乘客安装失败,请建议如何解决这个问题?
- r - dplyr::select() 对可能不存在的列重新排序