Python模拟日志记录,同时保留日志输出

2024-05-14 11:13:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一系列使用pythonlogging module的单元/集成测试。我想测试是否在适当的时候记录了正确的东西,我可以使用mock模块实现这一点,如下所示:

@mock.patch('logging.Logger.info')

但是,当我这样做的时候,实际的日志记录就会停止(原因很明显!)这对我调试我的测试工作的原因很有用

我的问题如下:有没有一种方法可以模拟日志调用,这样我就可以断言它们是用预期参数调用的,但仍然保留日志功能?在

我当前的方法是创建一个包含MagicMock和一个未模拟的记录器的包装器类:

^{pr2}$

但这不管用。在

干杯, 杰克


Tags: 模块方法功能info参数logging记录原因
2条回答

我在2010年发布了this关于单元测试和日志记录的文章,它应该仍然是相关的。内容太大,无法在这里的答案中总结,因此提供了一个链接。在

您应该看到^{}

wraps: Item for the mock object to wrap. If wraps is not None then calling the Mock will pass the call through to the wrapped object (returning the real result). Attribute access on the mock will return a Mock object that wraps the corresponding attribute of the wrapped object (so attempting to access an attribute that doesn’t exist will raise an AttributeError).

If the mock has an explicit return_value set then calls are not passed to the wrapped object and the return_value is returned instead.

相关问题 更多 >

    热门问题