如何在pytest自动fixture中用caplog检测loguru日志错误?
解决Loguru日志在Pytest自动Fixture中无法捕获的问题
问题根源
你的代码中caplog.text为空,是因为Loguru默认独立于Python标准logging模块运行,而Pytest的caplog fixture仅能捕获标准logging产生的日志,自然抓不到Loguru的输出。
两种可行解决方案
方案1:直接用Loguru的Sink捕获日志(推荐)
不需要依赖caplog,直接通过Loguru的sink机制捕获测试过程中的日志,在测试结束后检查是否存在ERROR级别日志:
from io import StringIO from loguru import logger import pytest @pytest.fixture(autouse=True) def assert_no_loguru_errors(): # 创建内存缓冲区用于捕获日志 log_buffer = StringIO() # 给Loguru添加输出到缓冲区的handler handler_id = logger.add( log_buffer, format="{level}: {message}", # 保留级别信息便于检查 level="DEBUG" # 确保能捕获ERROR及以上级别日志 ) yield # 执行测试用例 # 测试结束后清理handler并检查日志 logger.remove(handler_id) log_content = log_buffer.getvalue() assert "ERROR" not in log_content, f"检测到ERROR日志:\n{log_content}"
方案2:将Loguru日志重定向到标准logging
通过配置Loguru将日志转发到标准logging模块,让caplog能够捕获到:
import logging from loguru import logger import pytest @pytest.fixture(autouse=True) def redirect_loguru_to_caplog(caplog): # 配置Loguru将日志发送到caplog对应的logging logger handler_id = logger.add( logging.getLogger("caplog"), format="{message}", level=logging.DEBUG, enqueue=False ) # 设置caplog捕获级别为ERROR,过滤无关日志 caplog.set_level(logging.ERROR) yield # 清理Loguru的handler logger.remove(handler_id) # 检查caplog中的日志 assert "ERROR" not in caplog.text, f"检测到ERROR日志:\n{caplog.text}"
关于你参考的Loguru文档示例
文档中的示例是替换caplog fixture本身,如果你想沿用那个思路,需要确保替换后的caplog fixture能被自动生效的fixture调用,但直接使用上面两种方案会更直接,无需修改原有caplog的使用逻辑。
内容的提问来源于stack exchange,提问作者lefli
相关产品推荐
相关产品推荐

