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')

结果查看:

相关推荐
我的xiaodoujiao12 小时前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 44--将自动化测试结果自动推送至钉钉工作群聊
前端·python·测试工具·ui·pytest
我的xiaodoujiao15 小时前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 45--生成项目需要的requirements.txt依赖文件
python·学习·测试工具·pytest
月明长歌16 小时前
全栈测试修炼指南:从接口策略到 Python+Pytest+Allure 企业级架构
python·架构·pytest
一晌小贪欢1 天前
Python 测试利器:使用 pytest 高效编写和管理单元测试
python·单元测试·pytest·python3·python测试
我送炭你添花2 天前
Pelco KBD300A 模拟器:20.搭建pytest集成测试基础框架 + 模拟器闭环测试
python·集成测试·pytest
我送炭你添花3 天前
Pelco KBD300A 模拟器:18. 按依赖顺序 + 复杂度由低到高逐步推进pytest单元测试
python·单元测试·log4j·pytest
生活很暖很治愈3 天前
Pytest-order插件
python·测试工具·测试用例·pytest
测试人社区—66795 天前
2025区块链分层防御指南:AI驱动的安全测试实战策略
开发语言·驱动开发·python·appium·pytest
我送炭你添花6 天前
pytest 入门指南:从零开始掌握 Python 测试框架的核心概念与使用方法
chrome·python·pytest
though the night6 天前
Python UI 自动化测试框架搭建demo(Selenium+Pytest 版)
自动化测试·selenium·测试工具·pytest