Python 3.8.0,pytest 5.3.2,日志记录 0.5.1.2。
我的代码有一个输入循环,为了防止程序完全崩溃,我捕获任何抛出的异常,将它们记录为关键,重置程序状态,然后继续运行。这意味着导致这种异常的测试不会完全失败,只要输出仍然是预期的。如果错误是测试代码的副作用但不影响主要测试逻辑,则可能会发生这种情况。但是,我仍然想知道该测试暴露了一个导致错误的错误。
我所做的大部分谷歌搜索都显示了如何在 pytest 中显示日志的结果,我正在这样做,但我不知道是否有办法在测试中公开日志,这样我就可以在任何测试中失败错误或严重级别的日志。
编辑:这是失败尝试的最小示例:
test.py:
import subject
import logging
import pytest
@pytest.fixture(autouse=True)
def no_log_errors(caplog):
yield # Run in teardown
print(caplog.records)
# caplog.set_level(logging.INFO)
errors = [record for record in caplog.records if record.levelno >= logging.ERROR]
assert not errors
def test_main():
subject.main()
# assert False
Run Code Online (Sandbox Code Playgroud)
subject.py:
import logging
logger = logging.Logger('s')
def main():
logger.critical("log critical")
Run Code Online (Sandbox Code Playgroud)
运行python3 -m pytest test.py通过没有错误。取消对 assert 语句的注释使测试失败且没有错误,并打印[]到 stdout 和log criticalstderr。
编辑2:
我找到了为什么会失败。从关于 caplog 的文档: …