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
相关推荐
给你一页白纸3 小时前
将分散的Pytest测试脚本统一接入测试平台:FastAPI改造方案详解
python·pytest·接口自动化·测试平台
问道飞鱼8 小时前
【自动化测试】 pytest 结合 Playwright 实现页面元素在两个区域间拖拽
pytest·拖拽·playweight
先鱼鲨生8 小时前
自动化框架pytest
运维·自动化·pytest
程序员杰哥1 天前
Pytest自动化测试框架实战
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
Yorlen_Zhang2 天前
Python pytest assert 断言
python·servlet·pytest
纯纯沙口4 天前
pytest - 基础使用教程
pytest
问道飞鱼4 天前
【自动化测试】pytest 语法与核心概念
自动化测试·pytest·playwright
zUlKyyRC4 天前
基于一阶RC模型,FFRLS+EKF算法的电池SOC在线联合估计Matlab程序
pytest
我的xiaodoujiao6 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 40--完善优化 Allure 测试报告显示内容
python·学习·测试工具·pytest