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

结果查看:

相关推荐
开源优测1 天前
Pytest中5种不同的方法解析JSON数据
log4j·json·pytest
不求大富大贵只求富可敌国1 天前
Gtest, Junit,以及pytest对比理解
junit·pytest
xing25162 天前
pytest下放pytest.ini文件就导致报错:ERROR: file or directory not found: #
pytest
xing25164 天前
pytest-html
前端·html·pytest
唐古乌梁海5 天前
【pytest】编写自动化测试用例命名规范README
自动化·pytest
xing25165 天前
pytest下allure
开发语言·python·pytest
IT求学人6 天前
pytest运行用例的常见方式及参数
pytest
开源优测7 天前
什么是pytest.ini及如何在Pytest中应用以提升配置效率
pytest
摸鱼仙人~7 天前
ImportError: cannot import name ‘FixtureDef‘ from ‘pytest‘
conda·pytest·fastapi