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

标签 python unit-testing python-3.x mocking

我有这段代码要测试:

log = logging.getLogger(__name__)


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

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

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

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

提前感谢您的任何帮助!

最佳答案

您可以在实际的日志记录对象上使用 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 docs on logging

关于python - 如何修补/模拟 logging.getlogger(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18901360/

相关文章:

python - 如何在 matplotlib 中的条形图/堆积条形图上获取标签?

python - Python 的 "is"运算符在 Go 中的等价物是什么?

python - 将字典转换为 Pandas 数据框

java - 用于测试中调试语句的 Logger 或 System.out.print

c# - Visual Studio 2010 单元测试

Python 从 url 写入 Json 文件,python 3 添加\n 和 b'

python - isinstance() 方法在 Python 3 中返回错误答案

python - 如果 Mongo 中两个日期之间存在任何数据,则返回 true 或 false

Python(17874,0x111e92dc0)malloc : can't allocate region

java - 如何对 StepVerifier 中的所有剩余元素执行断言?