首页 > 解决方案 > 在 logger.warning 调用中使单元测试失败

问题描述

unittest如果我看到写入记录器的任何警告,我希望我的 Python测试失败。如何捕获记录器消息并使其测试失败?

标签: python-3.xpython-unittest

解决方案


unittest具有assertLogs用于捕获日志记录的上下文管理器(自 Python 3.4 起添加,旧版本使用unittest2backport lib)。使用示例:

spam.py(待测试代码)

import logging
logging.getLogger(__name__).addHandler(logging.NullHandler())


def eggs():
    logging.warning('hello world')

测试:

import unittest
import spam

class SpamTests(unittest.TestCase):

    def test_eggs(self):
        with self.assertLogs() as ctx:
            spam.eggs()
        # we expect one record to be captured
        self.assertEqual(len(ctx.records), 1)
        record = ctx.records[0]
        # we expect the captured record to have the message 'hello world'
        self.assertEqual(record.message, 'hello world')

如果您想对任何具有警告级别的记录进行测试失败,您可以例如检查捕获的记录,按级别过滤:

self.assertFalse([r for r in ctx.records if r.levelno == logging.WARNING])

推荐阅读