ger*_*rit 13 python testing logging unit-testing pytest
我正在尝试使用 pytest 来测试我的函数是否记录了预期的文本,例如解决了这个问题(pyunit 等效项是assertLogs)。按照pytest logging documentation,我将caplog夹具传递给测试人员。该文件指出:
最后,在测试运行期间发送到记录器的所有日志都以 logging.LogRecord 实例和最终日志文本的形式在夹具上可用。
我正在测试的模块是:
import logging
logger = logging.getLogger(__name__)
def foo():
logger.info("Quinoa")
Run Code Online (Sandbox Code Playgroud)
测试人员是:
def test_foo(caplog):
from mwe16 import foo
foo()
assert "Quinoa" in caplog.text
Run Code Online (Sandbox Code Playgroud)
我希望这个测试能够通过。但是,运行测试 withpytest 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 ===============================
Run Code Online (Sandbox Code Playgroud)
caplog.text尽管foo()向记录器发送文本,但为什么还是空的?我如何使用pytest,从而caplog.text不会捕捉记录的文字,或以其他方式验证该文本被记录?
ger*_*rit 10
这里的文档不清楚。经过反复试验,尽管有“测试运行期间发送到记录器的所有日志都可用”文本,但它仍然只捕获具有某些日志级别的日志。要真正捕获所有日志,需要使用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
Run Code Online (Sandbox Code Playgroud)
现在,测试通过:
============================= 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 ===============================
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4055 次 |
| 最近记录: |