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

How should I verify a log message when testing Python code under nose?(在鼻子下测试 Python 代码时,我应该如何验证日志消息?)
本文介绍了在鼻子下测试 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 代码时,我应该如何验证日志消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

patching a class yields quot;AttributeError: Mock object has no attributequot; when accessing instance attributes(修补类会产生“AttributeError:Mock object has no attribute;访问实例属性时)
How to mock lt;ModelClassgt;.query.filter_by() in Flask-SqlAlchemy(如何在 Flask-SqlAlchemy 中模拟 lt;ModelClassgt;.query.filter_by())
FTPLIB error socket.gaierror: [Errno 8] nodename nor servname provided, or not known(FTPLIB 错误 socket.gaierror: [Errno 8] nodename nor servname provided, or not known)
Weird numpy.sum behavior when adding zeros(添加零时奇怪的 numpy.sum 行为)
Why does the #39;int#39; object is not callable error occur when using the sum() function?(为什么在使用 sum() 函数时会出现 int object is not callable 错误?)
How to sum in pandas by unique index in several columns?(如何通过几列中的唯一索引对 pandas 求和?)