在鼻子下面测试Python代码时,应如何验证日志消息? [英] How should I verify a log message when testing Python code under nose?

查看:132
本文介绍了在鼻子下面测试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 =模拟日志模块)或使用适当的模拟库来模拟日志记录模块.
  • 编写或使用现有的鼻子插件捕获输出并进行验证.

如果我采用前一种方法,那么我想知道在嘲笑日志记录模块之前将全局状态重置为最干净的方法是什么.

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...

推荐答案

我过去常常模拟记录器,但是在这种情况下,我发现最好使用记录处理程序,因此我基于

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代码时,应如何验证日志消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆