assertLog 未捕获日志记录

Ray*_*emi 3 python python-3.x python-unittest

我有这个测试程序在 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")
Run Code Online (Sandbox Code Playgroud)

然后我运行这个:

% python -m unittest dummy.py
Run Code Online (Sandbox Code Playgroud)

并得到这个。请注意,我的测试消息正在写出,但格式错误。也许这就是上下文管理器丢失的原因?这是我的全部代码,所以我看不到在哪里更改格式。

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")%
Run Code Online (Sandbox Code Playgroud)

我做错了什么或者这在 3.8.3 中被破坏了?我习惯用3.6来写。

MrB*_*men 6

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

class LoggingTestCase (unittest.TestCase):

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

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