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
相关推荐
思则变2 天前
[Pytest][Part 1]Pytest 自动化测试框架
pytest
思则变4 天前
[Pytest] [Part 2]增加 log功能
开发语言·python·pytest
思则变5 天前
[Pytest][Part 3]检测python package状态
pytest
cooldream200918 天前
pytest 框架详解与实战指南
pytest·测试
慕城南风18 天前
【pytest进阶】Pytest之conftest详解
pytest
编程小白gogogo19 天前
AI自动化测试速成(Pytest框架)
pytest
慕城南风19 天前
【pytest进阶】pytest详解及进阶使用
linux·服务器·pytest
Tom Boom1 个月前
Pytest断言全解析:掌握测试验证的核心艺术
自动化测试·python·测试开发·pytest
不要一直敲门1 个月前
初学 pytest 记录
pytest