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
相关推荐
测试老哥1 天前
Pytest自动化测试框架tep环境变量、fixtures、用例三者之间的关系
自动化测试·软件测试·python·测试工具·测试用例·pytest·职场发展
小小测试开发1 天前
Agent 安全测试:pytest 原生红队框架 RAMPART 实战解析
人工智能·pytest
不拘一格的叶三少5 天前
Pytest + Playwright 自动化测试工程设计要点 & 目录结构
测试工具·pytest
努力搬砖的咸鱼6 天前
意图理解:让Agent从需求描述自动生成Pytest测试策略
人工智能·python·ai·单元测试·pytest·agent
St_rive9 天前
Pytest skip&&skipif跳过⽤例
运维·服务器·pytest
努力搬砖的咸鱼12 天前
AI Agent测试全景图:它到底改变了什么
人工智能·python·ai·集成测试·pytest·agent·ai编程
X1A0RAN13 天前
自动化流水线提效·微观篇:pytest 执行顺序优化
自动化·pytest
久久学姐21 天前
Python+Playwright+Pytest+BDD,用FSM打造高效测试框架
python·pytest·bdd·playwright·fsm
小白上线*^_^*21 天前
Pytest 自动化测试框架速通指南(二)
软件测试·pytest·python测试框架·ai测试基础