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

结果查看:

相关推荐
开源优测5 天前
使用Pytest Fixtures来提升TestCase的可读性、高效性
pytest
撸码到无法自拔5 天前
python接口测试:2.8 Pytest之pytest-html报告生成
开发语言·python·pytest
唐古乌梁海6 天前
【Pytest】生成html报告中,中文乱码问题解决方案
pytest
开源优测6 天前
深入理解Pytest中的Setup和Teardown
pytest
莲动渔舟6 天前
pytest自动化测试 - pytest夹具的基本概念
pytest
测试19987 天前
Pytest+Allure+Excel接口自动化测试框架实战
自动化测试·软件测试·python·测试工具·职场和发展·excel·pytest
可遇_不可求8 天前
Pytest插件介绍:pytest-django
django·sqlite·pytest
城下秋草11 天前
pytest+playwright落地实战大纲
自动化测试·pytest·测试·playwright
卜及中12 天前
【Pytest】基础到高级功能的理解使用
开发语言·python·学习·pytest·python3.11