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
相关推荐
测试老哥4 小时前
pytest+requests+allure自动化测试接入Jenkins学习
自动化测试·软件测试·学习·测试工具·职场和发展·jenkins·pytest
丿罗小黑6 小时前
Pytest项目_day20(log日志)
pytest
xt19892887 小时前
pytest+yaml+allure接口自动化测试框架
自动化测试·pytest·接口自动化·框架封装
灰阳阳7 小时前
接口自动化测试大全(python+pytest+allure)
python·pytest·接口自动化·allure
5:003 天前
pytest框架-详解
pytest
丿罗小黑5 天前
Pytest项目_day15(yaml)
pytest
丿罗小黑5 天前
Pytest项目_day16(yaml和parametrize结合)
pytest
代码小念6 天前
Pytest+selenium UI自动化测试实战实例(超详细)
selenium·ui·pytest
丿罗小黑6 天前
Pytest项目_day11(fixture、conftest)
pytest