我正在尝试使用 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/