如何在pytest中捕获logging.warning与logging.debug日志?
在pytest中捕获logging.warning或logging.debug日志的方法
你的测试失败核心原因是:capsys仅负责捕获标准输出(stdout)和标准错误(stderr),而logging.warning的输出默认不会被capsys.out捕获,且pytest内置了专门的日志捕获机制,需通过caplog fixture来获取日志内容。
方法一:使用caplog fixture(推荐)
caplog是pytest专门为日志捕获设计的fixture,能直接获取所有日志信息,无需额外配置。修改后的测试代码如下:
import logging def test_myoutput(capsys, caplog): print("hello") logging.warning("world") # 验证print的标准输出 captured = capsys.readouterr() assert captured.out == "hello\n" # 验证logging.warning的内容 assert "world" in caplog.text # 更精确的断言:匹配日志的logger名称、级别和消息 assert caplog.record_tuples == [("root", logging.WARNING, "world")] print("next") captured = capsys.readouterr() assert captured.out == "next\n"
caplog常用属性:
caplog.text:所有捕获的日志文本拼接内容caplog.record_tuples:每个日志的元组列表,格式为(logger名称, 日志级别, 日志消息)caplog.records:完整的日志记录对象列表,可访问日志的模块、行号等细节属性
如果要捕获logging.debug,只需调整日志级别:
def test_debug_log(caplog): # 设置捕获的最低日志级别为DEBUG caplog.set_level(logging.DEBUG) logging.debug("debug message") assert "debug message" in caplog.text
方法二:配置logging输出到标准流后用capsys捕获
若坚持使用capsys,可手动配置logging将日志输出到stdout或stderr,再通过capsys的err或out属性获取:
import logging import sys def test_myoutput(capsys): # 配置logging输出到stderr(默认输出目标,此处显式声明确保生效) logging.basicConfig(stream=sys.stderr, level=logging.WARNING) print("hello") logging.warning("world") captured = capsys.readouterr() assert captured.out == "hello\n" # 日志内容会出现在stderr中 assert "WARNING:root:world\n" in captured.err print("next") captured = capsys.readouterr() assert captured.out == "next\n"
注意:这种方法需要手动管理logging配置,可能影响其他测试的日志输出,因此优先推荐caplog方案。
内容的提问来源于stack exchange,提问作者PaleNeutron
相关产品推荐
相关产品推荐

