Python单元测试pytest捕获日志输出

使用pytest进行单元测试时,遇到了需要测试日志输出的情况,查看了文档

https://docs.pytest.org/en/latest/how-to/capture-stdout-stderr.html

https://docs.pytest.org/en/latest/how-to/logging.html

然后试了一下,捕捉logger.info可以用caplog,获取print输出可用capsys,Demo如下:

python 复制代码
import logging

logger = logging.getLogger(__name__)
LOG_INFO = "I'm a teapot"
PRINT_MSG = "No thing to do."


def function_with_logger(msg=None):
    if msg is None:
        msg = LOG_INFO
    logger.info(msg)


def function_include_print():
    print(PRINT_MSG)
  • test_a.py
python 复制代码
import logging

from a import LOG_INFO, PRINT_MSG, function_include_print, function_with_logger


def test_logger(caplog):
    caplog.set_level(logging.INFO)
    function_with_logger()
    log_messages = [record.message for record in caplog.records]
    assert LOG_INFO in log_messages
    caplog.clear()
    function_with_logger("foo")
    assert "foo" in caplog.text


def test_print(capsys):
    function_include_print()
    captured = capsys.readouterr()
    assert PRINT_MSG in captured.out
  • 验证:
bash 复制代码
pytest test_a.py
相关推荐
nbwenren6 天前
2026实测:Gemini 3.1 Pro 从需求文档到 pytest 测试用例一条龙教程
测试用例·pytest
我的xiaodoujiao7 天前
API 接口自动化测试详细图文教程学习系列16--项目实战演练3
python·学习·测试工具·pytest
我的xiaodoujiao7 天前
API 接口自动化测试详细图文教程学习系列15--项目实战演练2
python·学习·测试工具·pytest
技术钱8 天前
PyTest配置与API测试用例
servlet·测试用例·pytest
weixin_4196583110 天前
pytest 零基础入门实战指南
python·pycharm·pytest
姚青&13 天前
软件测试基础概念
单元测试·pytest
爆更小哇16 天前
pytest集成Allure报告教程
python·测试工具·pytest·接口测试·allure
gCode Teacher 格码致知16 天前
Python提高:pytest的简单案例-由Deepseek产生
python·pytest
gCode Teacher 格码致知16 天前
Python提高: unittest和 pytest的使用方法-由Deepseek产生
开发语言·python·pytest