我们在使用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目录中,如下图。

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

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

我们可以在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

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

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