Skip to content

#54: Create a Report for Your Test Results With Pytest

The test summary of pytest is good when you develop your application. But when you want to share these results with others, the lack of details is a problem. Let us look how we can create a more detailed report that we can share.

Create a report with pytest-html

Pytest cannot offer everything, but thanks to the plugin system it does not have to. There is a plugin called pytest-html that we can install into our virtual environment:

$ pip install pytest-html

To create a slightly interactive report, we can run pytest with the **--html=report.html** option:

$ pytest --html=report.html

This creates a file report.html (and an assets folder) that you can open in your browser:

The pytest HTML report

The checkboxes allow you to filter your tests and only show the ones you care about.

Customizing the CSS

I like the content of the report, but I find the grey text hard to read. Luckily that is easy to fix with a custom CSS file like this one:

1
2
3
4
5
6
7
td {
    color: black;
}

body {
    color: black;
}

We can specify one or more CSS files with the **--css** option:

$ pytest --html=report.html --css=myreport.css

If we now open the report in the browser we can read the text a lot better:

The report no longer uses grey for its text colour

Pytest-html takes our CSS file(s) and appends them to assets/style.css. Therefore, you will not see any change when you edit myreport.css and refresh the report in the browser. You first need to run pytest again to see a change.

The assets/style.css file is a good starting point to change the layout. Just remember not to modify that file, then pytest will overwrite it on the next run.

Sharing the report on the web

You can take the report.html file and the assets folder and put it on a web server. The Content Security Policy (CSP) settings may prevent the CSS from being loaded into the browser. Is this the case, you can use the **--self-contained-html** option to inline the CSS:

$ pytest --html=report.html --css=myreport.css --self-contained-html

Your report looks as before, but instead of the link to the style.css file you now have all the CSS definitions in the header section of the HTML page:

  <head>
    <meta charset="utf-8"/>
    <title>Test Report</title>
    <style>
    ...
    /******************************
     * CUSTOM CSS
     * myreport.css
     ******************************/

    td {
        color: black;
    }

    body {
        color: black;
    }</style>
  </head>

Next

Our list of plugins and packages grows - and most of them we only need for developing our application and not to run it in production. Next week we look at an interesting approach with the requirements.txt file to address this point.