python - 将 pytest 夹具与 asynctest 一起使用
问题描述
我正在使用asynctest,我想利用 pytest 夹具。我对(但不仅是)caplog夹具感兴趣。
在 asynctest 测试类中,我可以使用with self.assertLogs():
,但是当我的日志不在块内生成时,这还不够。
import asyncio
import logging
import asynctest
async def worker():
logging.error(":(")
class TestClass(asynctest.TestCase):
"""Testing class. """
async def setUp(self):
self.worker_task = asyncio.ensure_future(worker())
async def tearDown(self):
try:
self.worker_task.cancel()
except asyncio.CancelledError:
pass
async def test_get_error_log(self):
""" Simple test that assert logs emitted. """
with self.assertLogs(level="ERROR") as cm:
await asyncio.sleep(1)
上面的测试如果失败但如果我有:
---------- Captured log call -----------
ERROR root:tmp.py:7 :(
解决方案
In fact asynctest is build on top of unittest and has nothing in common with the pytest testing framework.
So my own response is: for pytest fixtures, then use pytest instead of asynctest.
For the logging issue, it can be solved by getting and mocking the logging function.
async def test_get_error_log(self):
""" Simple test that assert logs emitted. """
logging.error = asynctest.Mock()
await asyncio.sleep(1)
logging.error.assert_called_once_with(":(")