...

Pytest解决报告日志等相对路径问题

我们在使用pytest搭建测试框架时,有时候为了方便会将生成报告/日志等参数直接作为默认参数配置在pytest.ini中,如

pytest.ini

[pytest]
addopts = -v --html=reports/report.html --alluredir=reports/allure_results

log_file = logs/test.log

需要 pip install pytest pytest-html allure-pytest

如果在项目根目录命令行下执行 pytest . 测试的话,报告和日志可以生成到项目下的reports及logs目录中。
但是在PyCharm中如果直接运行用例,则报告会生成在用例所在目录的reports及logs目录中,如下图。

image

有没有办法在调试时,报告和日志也自动生成在项目下而非运行路径下呢?

我们可以在conftest.py中使用Hooks函数pytest_configure来修改config.option中对应的参数来强制将文件路径改到项目路径(rootdir)下。

conftest.py

def pytest_configure(config):
    rootdir = config.rootdir  # 项目根目录
    # 日志文件路径
    log_file = config.getoption('--log-file') or config.getini('log_file')
    if log_file:
        config.option.log_file = rootdir / log_file
    # pytest-ini报告路径
    htmlpath = config.getoption('--html')
    if htmlpath:
        config.option.htmlpath = rootdir / htmlpath
    # allure-pytest报告数据路径
    allure_report_dir = config.getoption('--alluredir')
    if allure_report_dir:
        config.option.allure_report_dir = rootdir / allure_report_dir

再次运行用例,报告/日志等就会固定生成在项目路径下,如图:

image

作者:韩志超

出处:https://www.cnblogs.com/superhin/p/18396443/pytest_relative_report_log_path

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

如有问题,请微信联系 superz-han,并发送原文链接。

posted @   韩志超  阅读(45)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
历史上的今天:
2019-09-04 Pytest权威教程09-捕获标准输出及标准错误输出
2019-09-04 Pytest权威教程08-使用tmp目录和文件
2019-09-04 Pytest权威教程07-Monkeypatching,对模块和环境进行Mock
点击右上角即可分享
微信分享提示
more_horiz
keyboard_arrow_up dark_mode palette
选择主题