python-3.x assertLog未捕获日志记录

qv7cva1a  于 2023-04-22  发布在  Python
关注(0)|答案(2)|浏览(145)

我在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中写作。

14ifxucb

14ifxucb1#

正如您在消息中看到的,日志记录在根日志记录器上检查-这是默认值,如果您没有提供日志记录器。由于您没有使用根日志记录器,Assert失败。您必须通过您正在测试的日志记录器:

class LoggingTestCase (unittest.TestCase):

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

至于格式:这取决于如何配置记录器。

khbbv19g

khbbv19g2#

如果使用logger = logging.Logger('test'),错误仍然存在:

AssertionError: no logs of level INFO or higher triggered on test

尝试将其从Logger更改为getLogger

class LoggingTestCase (unittest.TestCase):

    def test_logging(self):
        logger = logging.getLogger('test') # <---- the change is here
        with self.assertLogs(logger) as cm:
            logger.error("A test error message")

相关问题