Search code examples
pythonpytestpytest-html

How to change the filename of pytest-html's generated HTML report?


I know how to change the report name, the following does that for me just fine:

conftest.py

def pytest_html_report_title(report):
   report.title = 'My API Testing'

But that doesn't change the name of the actual file itself. It is still showing up as report.html and just overwriting itself every run.

Is there a way to change the filename? I want to name it something dynamic with a timestamp so it doesn't keep overwriting the same file.


Solution

  • The pytest-html plugin adds an --html CLI option to pytest to customize the path and filename of the generated HTML file:

    $ ls | grep -c "html"
    0
     
    $ pytest --html=mycustomreportfilename.html tests/*
    ...
    - Generated html report: file:/path/to/mycustomreportfilename.html -
    
    $ ls | grep -c "html"
    1
    
    $ ls | grep "html"
    mycustomreportfilename.html
    

    If you want "something dynamic with a timestamp" and you are using a shell or an environment that has date/time commands or utilities (such as the date command on Bash), you can then pass the output of those commands or utilities to the --html option (see this related post on generating various formats using date):

    $ ls | grep -c "html"
    0
    
    $ pytest --html="$(date +%Y%m%d_%H%M%SZ)_report.html" tests/*
    $ pytest --html="$(date +%Y%m%d_%H%M%SZ)_report.html" tests/*
    $ pytest --html="$(date +%Y%m%d_%H%M%SZ)_report.html" tests/*
    
    $ ls | grep -c "html"
    3
    
    $ ls | grep "html"
    20240106_171151Z_report.html
    20240106_171202Z_report.html
    20240106_171206Z_report.html
    

    But in doing that, it generates the same assets folder for all the generated HTML reports. Not sure if that will be a problem, but to guarantee that each report is independent, I suggest also passing the --self-contained-html option to create a self-contained HTML report:

    $ pytest --html="$(date +%Y%m%d_%H%M%SZ)_report.html" --self-contained-html tests/*
    

    The --html option isn't documented in the pytest-html docs (as of pytest-html 4.1.1), but it is there in the source code (again as of pytest-html 4.1.1 https://github.com/pytest-dev/pytest-html/blob/4.1.1/src/pytest_html/plugin.py#L27-L33):

    group.addoption(
        "--html",
        action="store",
        dest="htmlpath",
        metavar="path",
        default=None,
        help="create html report file at given path.",
    )