使用pytestfixture和asynctes

2024-09-27 22:28:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用asynctest,我想利用pytestfixture。我对caplog fixture感兴趣(但不仅如此)。你知道吗

在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 :(

Tags: testimportselflogasynciotaskasynclogging
1条回答
网友
1楼 · 发布于 2024-09-27 22:28:19

实际上,asynctest构建在unittest之上,与pytest测试框架没有任何共同之处。你知道吗

所以我自己的回答是:对于pytest fixture,使用pytest而不是asynctest。

对于日志问题,可以通过获取和模拟日志函数来解决。你知道吗

    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(":(")

相关问题 更多 >

    热门问题