在鼻子下测试 Python 代码时,我应该如何验证日志

时间:2022-11-19
本文介绍了在鼻子下测试 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 代码时,我应该如何验证日志消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:修补函数的 __call__ 下一篇:没有了

相关文章

最新文章