我如何修补/模拟 logging.getlogger()

新手上路,请多包涵

我有这段代码要测试:

 log = logging.getLogger(__name__)

class A(object):
    def __init__(self):
        log.debug('Init')

但我不知道如何断言 log.debug 是用“Init”调用的

我尝试修补记录器但检查它我只发现了一个 getLogger 模拟。

我敢肯定它很简单,但我就是想不通!

在此先感谢您提供的所有帮助!

原文由 Philip Ridout 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 486
2 个回答

您可以在实际的日志记录对象上使用 patch.object() 。这让您可以验证您是否也在使用正确的记录器:

 logger = logging.getLogger('path.to.module.under.test')
with mock.patch.object(logger, 'debug') as mock_debug:
    run_code_under_test()
    mock_debug.assert_called_once_with('Init')

或者,如果您使用的是 Pytest,那么它已经有一个可以为您捕获日志的装置:

 def test_bar(caplog):
    with caplog.at_level(logging.DEBUG):
        run_code_under_test()
    assert "Init" in caplog.text
    # or, if you really need to check the log-level
    assert caplog.records[-1].message == "Init"
    assert caplog.records[-1].levelname == "DEBUG"

pytest 文档中有关日志记录 的更多信息

原文由 hwjp 发布,翻译遵循 CC BY-SA 4.0 许可协议

Assuming log is a global variable in a module mymod , you want to mock the actual instance that getLogger returned, which is what debug 。然后,您可以检查 log.debug 是否使用正确的参数调用。

 with mock.patch('mymod.log') as log_mock:
    # test code
    log_mock.debug.assert_called_with('Init')

原文由 chepner 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题