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如下:

- a.py

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

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

- 验证:

pytest test_a.py

相关推荐

  1. Python单元测试框架:unittest与pytest的深度对比

    2024-04-10 09:24:03       7 阅读
  2. Python自动化测试之使用pytest-mock模拟用户输入

    2024-04-10 09:24:03       20 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-10 09:24:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-10 09:24:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-10 09:24:03       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-10 09:24:03       20 阅读

热门阅读

  1. 群集服务器与主机托管区别

    2024-04-10 09:24:03       12 阅读
  2. 阀门位置反馈器F5-MEC-420

    2024-04-10 09:24:03       13 阅读
  3. helm原理

    2024-04-10 09:24:03       13 阅读
  4. easyui 使用记录

    2024-04-10 09:24:03       13 阅读
  5. 第四十七章 为 Web 应用程序实现 HTTP 身份验证

    2024-04-10 09:24:03       12 阅读
  6. hbase的基础搭建

    2024-04-10 09:24:03       12 阅读
  7. mysql create procedure

    2024-04-10 09:24:03       12 阅读
  8. HBase详解(3)

    2024-04-10 09:24:03       9 阅读
  9. 封装Element-Plus表单组件

    2024-04-10 09:24:03       15 阅读
  10. textcnn做多分类

    2024-04-10 09:24:03       10 阅读