首页 > 解决方案 > 如何在同步测试类中使用 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

我假设我遗漏了一些简单的东西,所以这一切都可以分解为一个简单的问题:我到底该如何测试这个?

谢谢!

标签: python-3.xunit-testingpython-asynciopython-aiofilespyfakefs

解决方案


您可以创建一个类来完全修补“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())

推荐阅读