assertLog未捕获日志记录

2024-09-27 22:15:38 发布

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

我在Python 3.8.3中运行了这个测试程序

import unittest
import logging
class logging_TestCase (unittest.TestCase):

    def test_logging(self):
        with self.assertLogs() as cm:
            logging.Logger('test').error("A test error message")

然后我运行这个:

% python -m unittest dummy.py

拿着这个。请注意,我的测试消息正在编写中,但格式错误。也许这就是上下文管理器缺少它的原因?这都是我的代码,所以我不知道我在哪里更改格式

A test error message
F
======================================================================
FAIL: test_logging (dummy.logging_TestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/raysalemi/PycharmProjects/pyuvm/tests/dummy.py", line 7, in test_logging
    logging.Logger('test').error("A test error message")
AssertionError: no logs of level INFO or higher triggered on root

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (failures=1)
(base) raysalemi@WriteNow tests % cat dummy.py
import unittest
import logging
class logging_TestCase (unittest.TestCase):

    def test_logging(self):
        with self.assertLogs() as cm:
            logging.Logger('test').error("A test error message")%

我是做错了什么,还是这在3.8.3中被打破了? 我习惯于用3.6来写作


Tags: pytestimportselfmessageloggingdefwith
1条回答
网友
1楼 · 发布于 2024-09-27 22:15:38

正如您在消息中所看到的,在根日志记录器上检查日志记录-如果您不提供日志记录器,这是默认设置。由于不使用根记录器,断言将失败。您必须通过正在测试的记录器:

class LoggingTestCase (unittest.TestCase):

    def test_logging(self):
        logger = logging.Logger('test')
        with self.assertLogs(logger) as cm:
            logger.error("A test error message")

至于格式:这取决于记录器的配置方式

相关问题 更多 >

    热门问题