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 小时前
FastAPI单元测试实战:别等上线被喷才后悔,TestClient用对了真香!
python·单元测试·pytest·api·fastapi·web·httpx·testclient·依赖项覆盖
小罗和阿泽7 小时前
接口测试系列 接口自动化测试 pytest框架(四)
pytest
python开发笔记8 小时前
pytest(16) mark用法
pytest
忘忧记9 小时前
pytest 基础用法教程
pytest
我的xiaodoujiao1 天前
3、API 接口自动化测试详细图文教程学习系列3--相关Python基础知识2
python·学习·测试工具·pytest
小陈的进阶之路1 天前
Pytest 框架与 Fixture 总结
笔记·pytest
我的xiaodoujiao1 天前
4、API 接口自动化测试详细图文教程学习系列4--相关Python基础知识3
python·学习·测试工具·pytest
小罗和阿泽1 天前
接口测试系列 接口自动化测试 pytest框架(三)
开发语言·python·pytest
独断万古他化2 天前
Python+Pytest 接口自动化测试实战 —— 抽奖系统接口测试框架设计与实现
python·pytest·接口自动化·测试·allure·yaml·json schema