考虑模块中的函数。
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方法中生成的假文件。
我假设我遗漏了一些简单的东西,所以实际上这一切都可以分解为一个简单的问题:我该如何测试它?
谢谢!
发布于 2019-01-22 22:22:13
你可以创建一个类来修补'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())https://stackoverflow.com/questions/54145118
复制相似问题