Python Friday #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.

This post is part of my journey to learn Python. You can find the other parts of this series here.

 

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:

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

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:

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

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:

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:

 

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.

1 thought on “Python Friday #54: Create a Report for Your Test Results With Pytest”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.