python-3.x - 在 logger.warning 调用中使单元测试失败
问题描述
unittest
如果我看到写入记录器的任何警告,我希望我的 Python测试失败。如何捕获记录器消息并使其测试失败?
解决方案
unittest
具有assertLogs
用于捕获日志记录的上下文管理器(自 Python 3.4 起添加,旧版本使用unittest2
backport 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])
推荐阅读
- html - 无法通过 div 获取隐藏菜单
- c++ - 如何将 libtorch 库添加到 CLION?
- spring-boot - 无法测试我的@RestController:嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:
- javascript - 如何演示 document.documentElement.clientWidth 和 innerWidth 之间的区别?
- r - 按名称读入 csv 列的子集
- google-sheets - 使用查询过滤数据的下拉列表
- python - 如何使用来自多个自变量的多个 Z 分数开发 0-100 综合分数或指数分数?
- r - 空间投影问题 - 未知数据 GRS1980
- r - 将布尔输出添加到 R 中的函数
- jboss - 如何在 Wildfly jboss 中登录到不同的文件?