Ray*_*emi 4 python logging python-unittest
我想在我的单元测试中测试记录器消息而不将它们打印到屏幕上。鉴于此代码:
import logging
logging.basicConfig(level=logging.ERROR)
logger = logging.getLogger('test')
logger.warning('this is a warning')
# How do I see that there was a warning?
Run Code Online (Sandbox Code Playgroud)
如何查看记录器中的日志记录以查看是否有警告?我在 Logger 中找不到可以完成这项工作的迭代器。
在这种情况下,您可能需要使用TestCase.assertLogs()上下文管理器。文档提供了一个很好的例子,说明可以用它做什么:
with self.assertLogs('foo', level='INFO') as cm:
logging.getLogger('foo').info('first message')
logging.getLogger('foo.bar').error('second message')
self.assertEqual(cm.output, ['INFO:foo:first message',
'ERROR:foo.bar:second message'])
Run Code Online (Sandbox Code Playgroud)
在上下文管理器中,您可以访问实例cm.records列表LogRecord或cm.output格式化消息列表