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

结果查看:

相关推荐
FINE!(正在努力!)1 天前
PyTest框架学习
学习·pytest
程序员杰哥2 天前
接口自动化测试之pytest 运行方式及前置后置封装
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
测试老哥2 天前
Pytest+Selenium UI自动化测试实战实例
自动化测试·软件测试·python·selenium·测试工具·ui·pytest
水银嘻嘻2 天前
07 APP 自动化- appium+pytest+allure框架封装
python·appium·自动化·pytest
天才测试猿3 天前
接口自动化测试之pytest接口关联框架封装
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
not coder4 天前
Pytest Fixture 详解
数据库·pytest
not coder4 天前
pytest 常见问题解答 (FAQ)
开发语言·python·pytest
程序员的世界你不懂4 天前
(1)pytest简介和环境准备
pytest
not coder4 天前
Pytest Fixture 是什么?
数据库·oracle·pytest
Tester_孙大壮4 天前
pytest中的元类思想与实战应用
pytest