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
相关推荐
兴趣使然黄小黄10 小时前
【Pytest】使用Allure生成企业级测试报告
python·pytest
少云清1 天前
【接口测试】4_代码实现 _pytest框架
pytest·接口测试
屋顶那猫1 天前
使用pyinstaller打包pytest项目
python·pytest
zyx没烦恼2 天前
pytest框架
pytest
兴趣使然黄小黄4 天前
【Pytest】Pytest常用的第三方插件
python·pytest
我的xiaodoujiao4 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 34--基础知识 9--文件上传功能
前端·python·测试工具·ui·pytest
我一定会有钱4 天前
pytest测试框架基础
python·单元测试·自动化·pytest
我的xiaodoujiao4 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 35--二次封装MySQL数据库连接操作
python·学习·测试工具·pytest
给你一页白纸5 天前
Pytest 测试用例自动生成:接口自动化进阶实践
python·pytest·接口自动化
工会主席-阿冰5 天前
使用pytest-selenium插件,ui自动化示例
selenium·pytest