【问题标题】:Writing unit tests when using aiohttp and asyncio使用 aiohttp 和 asyncio 时编写单元测试
【发布时间】:2019-06-14 04:35:25
【问题描述】:

我正在更新我的一个 Python 包,因此它是异步的(使用 aiohttp 而不是 requests)。我也在更新我的单元测试,以便它们与新的异步版本一起工作,但我遇到了一些麻烦。

这是我包裹中的一个 sn-p:

async def fetch(session, url):
    while True:
        try:
            async with session.get(url) as response:
                assert response.status == 200
                return await response.json()
        except Exception as error:
            pass


class FPL():
    def __init__(self, session):
        self.session = session

    async def get_user(self, user_id, return_json=False):
        url = API_URLS["user"].format(user_id)
        user = await fetch(self.session, url)

        if return_json:
            return user
        return User(user, session=self.session)

使用时似乎一切正常:

async def main():
    async with aiohttp.ClientSession() as session:
         fpl = FPL(session)
         user = await fpl.get_user(3808385)
         print(user)

loop = asynio.get_event_loop()
loop.run_until_complete(main())

>>> User 3808385

很遗憾,我的单元测试遇到了一些问题。我以为我可以简单地做类似的事情

def _run(coroutine):
    return asyncio.get_event_loop().run_until_complete(coroutine)


class FPLTest(unittest.TestCase):
    def setUp(self):
        session = aiohttp.ClientSession()
        self.fpl = FPL(session)

    def test_user(self):
        user = _run(self.fpl.get_user("3523615"))
        self.assertIsInstance(user, User)

        user = _run(self.fpl.get_user("3523615", True))
        self.assertIsInstance(user, dict)

if __name__ == '__main__':
    unittest.main()

它给出了诸如

之类的错误
DeprecationWarning: The object should be created from async function loop=loop)

ResourceWarning: Unclosed client session <aiohttp.client.ClientSession object at 0x7fbe647fd208>

我尝试将_close() 函数添加到关闭会话的FPL 类,然后从测试中调用它,但这也不起作用,仍然说有一个未关闭的客户端会话。

是否有可能做到这一点,我只是做错了什么,还是我最好改用asynctestpytest-aiohttp之类的东西?

编辑:我还检查了aiohttp 的文档,发现example 展示了如何使用标准库的 unittest 测试应用程序。不幸的是,我无法让它工作,因为 AioHTTPTestCase 中提供的 loop 自 3.5 以来已被弃用并引发错误:

class FPLTest(AioHTTPTestCase):
    def setUp(self):
        session = aiohttp.ClientSession()
        self.fpl = FPL(session)

    @unittest_run_loop
    async def test_user(self):
        user = await self.fpl.get_user("3523615")
        self.assertIsInstance(user, User)

        user = await self.fpl.get_user("3523615", True)
        self.assertIsInstance(user, dict)

给予

tests/test_fpl.py:20: DeprecationWarning: The object should be created from async function
  session = aiohttp.ClientSession()
  ...
======================================================================
ERROR: test_user (__main__.FPLTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/amos/Documents/fpl/venv/lib/python3.7/site-packages/aiohttp/test_utils.py", line 477, in new_func
    return self.loop.run_until_complete(
AttributeError: 'FPLTest' object has no attribute 'loop'

======================================================================
ERROR: test_user (__main__.FPLTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/amos/Documents/fpl/venv/lib/python3.7/site-packages/aiohttp/test_utils.py", line 451, in tearDown
    self.loop.run_until_complete(self.tearDownAsync())
AttributeError: 'FPLTest' object has no attribute 'loop'

【问题讨论】:

    标签: python python-asyncio aiohttp


    【解决方案1】:

    将 pytest 与 aiohttp-pytest 一起使用:

    async def test_test_user(loop):
        async with aiohttp.ClientSession() as session:
             fpl = FPL(session)
             user = await fpl.get_user(3808385)
        assert isinstance(user, User)
    

    现代python开发者的谚语:人生苦短,不要用pytest。

    您可能还想设置一个模拟服务器以在测试期间接收您的 http 请求,我没有一个简单的示例,但可以看到一个完整的工作示例 here

    【讨论】:

    • 我很快就用这个例子来看看它是否可以工作,它确实有效 - 谢谢!我希望我不必转换所有测试并可以继续使用 unittest,但我想我会尝试 pytest(以前从未使用过)。
    • 您不必转换所有测试,只需转换需要异步行为的测试即可。 pytest 运行标准的单元测试样式测试非常好。
    • 另外,从 unittest 切换到 py.test 很像从 urllib2 切换到 requests - 这样的改进让人永不回头,只会后悔没有早点切换!
    • 我同意,到目前为止真的很棒。最后,我创建了一些允许我访问的装置,例如我的测试中的 fpl 对象。转换所有内容甚至不需要那么长时间,并且看起来比以前干净得多。
    猜你喜欢
    • 1970-01-01
    • 2021-11-05
    • 2014-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多