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

2022-01-08 00:00:00 python mocking unit-testing nose

问题描述

我正在尝试编写一个简单的单元测试,以验证在特定条件下,我的应用程序中的类将通过标准日志记录 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': [],
        }

相关文章