python - 为什么 caplog.text 是空的,即使我正在测试的函数正在记录?

标签 python unit-testing testing logging pytest

我正在尝试使用 pytest 来测试我的函数是否正在记录预期的文本,例如寻址 this question ( pyunit 等效项为 assertLogs )。继pytest logging documentation ,我将 caplog fixture 传递给测试仪。文档指出:

Lastly all the logs sent to the logger during the test run are made available on the fixture in the form of both the logging.LogRecord instances and the final log text.

我正在测试的模块是:

import logging
logger = logging.getLogger(__name__)

def foo():
    logger.info("Quinoa")

测试者是:

def test_foo(caplog):
    from mwe16 import foo
    foo()
    assert "Quinoa" in caplog.text

我希望这个测试能够通过。但是,使用 pytest test_mwe16.py 运行测试会显示由于 caplog.text 为空而导致测试失败:

============================= test session starts ==============================
platform linux -- Python 3.7.3, pytest-5.3.0, py-1.8.0, pluggy-0.13.0
rootdir: /tmp
plugins: mock-1.12.1, cov-2.8.1
collected 1 item

test_mwe16.py F                                                          [100%]

=================================== FAILURES ===================================
___________________________________ test_foo ___________________________________

caplog = <_pytest.logging.LogCaptureFixture object at 0x7fa86853e8d0>

    def test_foo(caplog):
        from mwe16 import foo
        foo()
>       assert "Quinoa" in caplog.text
E       AssertionError: assert 'Quinoa' in ''
E        +  where '' = <_pytest.logging.LogCaptureFixture object at 0x7fa86853e8d0>.text

test_mwe16.py:4: AssertionError
============================== 1 failed in 0.06s ===============================

尽管 foo() 向记录器发送文本,但为什么 caplog.text 为空?如何使用 pytest 以便 caplog.text 捕获记录的文本,或者以其他方式验证文本是否正在记录?

最佳答案

这里的文档不清楚。经过反复试验,尽管有“测试运行期间发送到记录器的所有日志均可用”文本,但它仍然只捕获具有特定日志级别的日志。要实际上捕获所有日志,需要使用 caplog.set_level 设置捕获的日志消息的日志级别。或caplog.at_level上下文管理器,使测试模块变成:

import logging
def test_foo(caplog):
    from mwe16 import foo
    with caplog.at_level(logging.DEBUG):
        foo()
    assert "Quinoa" in caplog.text

现在,测试通过了:

============================= test session starts ==============================
platform linux -- Python 3.7.3, pytest-5.3.0, py-1.8.0, pluggy-0.13.0
rootdir: /tmp
plugins: mock-1.12.1, cov-2.8.1
collected 1 item

test_mwe16.py .                                                          [100%]

============================== 1 passed in 0.04s ===============================

关于python - 为什么 caplog.text 是空的,即使我正在测试的函数正在记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59875983/

相关文章:

python - 如何根据pandas数据框中的非连续索引列表替换值?

python - 从Python中的df列中删除字符串

python从两个列表中创建一个新列表,第二个列表表示重复第一个列表中的元素多少次

Angular 7 单元测试依赖注入(inject)在 ngOnInit 中不起作用

android - Android monkeyrunner 的 help.py 在哪里

php - 使用 phpspec 进行测试 - 来自当前类的模拟方法

Python pandas - 按不同年份的每周数据分组 - 重新采样

python - 有哪些策略可确保在所有区域设置中正确处理所有区域设置感知操作?

Django Rest 框架单元测试

javascript - Selenium 扩展 : "blocking" commands