How should I verify a log message when testing Python code under nose?(在鼻子下测试 Python 代码时,我应该如何验证日志消息?)
问题描述
我正在尝试编写一个简单的单元测试,以验证在特定条件下,我的应用程序中的类将通过标准日志记录 API 记录错误.我不知道测试这种情况的最干净的方法是什么.
I'm trying to write a simple unit test that will verify that, under a certain condition, a class in my application will log an error via the standard logging API. I can't work out what the cleanest way to test this situation is.
我知道鼻子已经通过它的日志插件捕获日志输出,但这似乎是为了作为失败测试的报告和调试帮助.
I know that nose already captures logging output through it's logging plugin, but this seems to be intended as a reporting and debugging aid for failed tests.
我可以看到的两种方法是:
The two ways to do this I can see are:
- 以零碎的方式 (mymodule.logging = mockloggingmodule) 或使用适当的模拟库来模拟日志模块.
- 编写或使用现有的鼻子插件来捕获输出并进行验证.
如果我采用前一种方法,我想知道将全局状态重置为模拟日志模块之前的状态的最简洁方法.
If I go for the former approach, I'd like to know what the cleanest way to reset the global state to what it was before I mocked out the logging module.
期待您对此的提示和技巧...
Looking forward to your hints and tips on this one...
推荐答案
我曾经模拟记录器,但是在这种情况下我发现最好使用记录处理程序,所以我基于 jkp 建议的文件(现在已经死了,但缓存在 互联网档案)
I used to mock loggers, but in this situation I found best to use logging handlers, so I wrote this one based on the document suggested by jkp(now dead, but cached on Internet Archive)
class MockLoggingHandler(logging.Handler):
"""Mock logging handler to check for expected logs."""
def __init__(self, *args, **kwargs):
self.reset()
logging.Handler.__init__(self, *args, **kwargs)
def emit(self, record):
self.messages[record.levelname.lower()].append(record.getMessage())
def reset(self):
self.messages = {
'debug': [],
'info': [],
'warning': [],
'error': [],
'critical': [],
}
这篇关于在鼻子下测试 Python 代码时,我应该如何验证日志消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在鼻子下测试 Python 代码时,我应该如何验证日志


基础教程推荐
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 包装空间模型 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01