Pytest日志收集器配置

前言

pytest框架中,日志记录(logging)是一个强大的功能,它允许我们在测试期间记录信息、警告、错误等,从而帮助调试和监控测试进度。

pytestPython标准库中的logging模块完美集成,因此你可以很容易地在pytest测试中使用日志记录。

配置日志收集

通过修改pytest.ini配置文件来配置日志记录。

创建一个名为pytest.ini的文件在项目的根目录,并添加以下内

python 复制代码
[pytest]
;打印详细日志,相当于命令行加 -vs
addopts = --capture=no --tb=long


;日志开关 true/false
log_cli = true


;输出到终端
;日志级别
log_cli_level = info
;日志格式
log_cli_format = %(asctime)s --> %(filename)-10s [line:%(lineno)-3d] --> %(levelname)-5s --> %(message)s
;日志时间格式
log_cli_date_format = %Y-%m-%d %H:%M:%S


; 输出到文件
;日志文件位置
log_file = logs/test-log.txt
;日志文件等级
log_file_level = info
;日志文件格式
log_file_format = %(asctime)s --> %(filename)-10s [line:%(lineno)-3d] --> %(levelname)-5s --> %(message)s
;日志文件日期格式
log_file_date_format = %Y-%m-%d %H:%M:%S

容来配置日志记录:

验证日志收集

代码实例

python 复制代码
import logging
import pytest

logger = logging.getLogger(__name__)


@pytest.mark.parametrize(argnames=["v1", "v2"], argvalues=[[1, 2], [2, 3], [3, 4]])
def test_case_01(v1, v2):
    logger.info(f"断言:{v1} < {v2}")
    assert v1 < v2, "断言失败"

执行结果

测试用例添加日志

测试用例导入loggin模块,即可在想要的地方添加日志。

python 复制代码
import logging

logging.info(f"请求方法:{method},请求路径:{url},请求参数:{data}")
logging.info(f"响应结果:{res}")
拓展-收集断言错误信息

利用钩子函数在测试用例执行结束阶段收集执行信息。

在目标目录创建conftest.py配置文件

python 复制代码
import json
import logging


def pytest_runtest_makereport(item, call):
    if call.excinfo is not None:
        msg = {
            "module": item.location[0],
            "function": item.name,
            "line": item.location[1],
            "message": str(call.excinfo.value).replace("\n", ":")
        }
        logging.error(json.dumps(msg, indent=4, ensure_ascii=False))

结果查看:

拓展-动态生成日志文件

conftest.py文件添加如下代码

python 复制代码
# 动态生成log文件的名称,哪怕配置文件中配置了log_file选项也不会生效
def pytest_configure(config):
    time_now = datetime.now().strftime('%Y_%m_%d_%H_%M_%S')
    config.option.log_file = os.path.join(config.rootdir, 'log', f'{time_now}.log')

结果查看:

相关推荐
别在内卷了2 天前
测试学习之——Pytest Day2
服务器·学习·pytest
chao_7892 天前
pytest 实战演练【pytest】
自动化测试·单元测试·自动化·pytest
qq_513728043 天前
为什么选择 pytest 而不是 unittest
pytest
思则变3 天前
[Pytest][Part 5]单条测试和用例集测试
pytest
杨梅树5 天前
pytest中mark的使用
pytest
测试开发技术7 天前
如何在 Pytest 中调用其他用例返回的接口参数?
面试·自动化·pytest·接口·接口测试·api测试
思则变8 天前
[Pytest][Part 4]多种测试运行方式
pytest
程序员三藏8 天前
如何使用Pytest进行测试?
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
一个处女座的测试10 天前
Python语言+pytest框架+allure报告+log日志+yaml文件+mysql断言实现接口自动化框架
python·mysql·pytest
思则变13 天前
[Pytest][Part 1]Pytest 自动化测试框架
pytest