我正在更新我的一个Python软件包,因此它是异步的(使用aiohttp
而不是requests
)。我也在更新我的单元测试,以便它们可以与新的异步版本一起使用,但是在此方面遇到了一些麻烦。
这是我包裹中的摘录:
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
类中以关闭会话,然后从测试中调用此函数,但这仍然行不通,并且仍然说有一个未关闭的函数客户会话。
是否可以这样做,我只是做错了什么,还是最好使用asynctest
或pytest-aiohttp
之类的东西?
编辑:我还检查了aiohttp
的文档,发现example展示了如何使用标准库的单元测试来测试应用程序。不幸的是,我无法使用它,因为loop
中提供的AioHTTPTestCase
从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'
答案 0 :(得分:3)
将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。