如何使用 caplog 检查额外的记录器内容?

How can I check the extra logger content with caplog?

我在日志上用 mocker 进行了单元测试:

代码:

def my_func():
    extra = my_http_call(): # returns {"foo": "bar"}
    logger.warning(
       "My warning",
       extra=extra
    )

为了测试这个,我使用了 mocker:

def test_my_func(mocker):
    import logging
    mocker.patch("logging.Logger.warning")
    my_func()
    logging.Logger.warning.assert_called_once_with(
        "My warning",
        extra={"foo": "bar"}
    )

但为了与我想使用的其他测试协调一致 caplog。所以我的测试变成了:

def test_my_func(caplog):
    my_func()
    assert caplog.messages == ["My warning"]

我搜索了一种方法来测试 extra 数据的内容,但我一无所获。

Key-value extra 中给出的对是“... used to populate the __dict__ of the LogRecord created for the logging event with user-defined attributes." 然后您可以通过访问 caplog:

捕获的记录来断言这些属性
def test_my_func(caplog)
    my_func()
    assert caplog.records[0].foo == "bar"