When running tests with pytest, it generates a detailed test report with essential information such as test outcomes, durations, and failures. Although the default report format is informative, it might lack customization and styling options. In this blog post, we will explore how to style the pytest test report to make it more visually appealing and easier to read.
Using pytest-html
One way to style the pytest test report is by using the pytest-html
plugin. This plugin generates an HTML report that can be customized with CSS styles. To get started, you need to install the pytest-html
package:
pip install pytest-html
After installing the package, you can generate an HTML report by running pytest with the --html
option:
pytest --html=report.html
This command will run your tests and generate an HTML report named report.html
. You can open this file in a browser to view the styled test report.
Customizing the report style
To customize the style of the pytest test report, you can override the default CSS styles provided by pytest-html
. You can do this by creating a custom CSS file and linking it to the HTML report.
Here’s an example of a custom CSS file that changes the font, background color, and header style:
body {
font-family: Arial, sans-serif;
background-color: #f5f5f5;
}
h1 {
color: #333;
font-size: 24px;
font-weight: bold;
margin-bottom: 20px;
}
Save this CSS code in a file named custom.css
.
To link this custom CSS file to the report, modify the pytest command as follows:
pytest --html=report.html --self-contained-html --css=custom.css
The --self-contained-html
option ensures that the CSS styles are embedded in the HTML file, making it a standalone report. The --css
option specifies the path to the custom CSS file (custom.css
).
Conclusion
By using pytest-html
and custom CSS styles, you can enhance the visual appearance of the pytest test report. Styling the report makes it more readable and visually appealing, making it easier to analyze the test results. Experiment with different CSS styles to create a test report that best suits your needs.
Remember to continually check the pytest documentation and pytest-html
documentation for updates and additional features.
Happy testing!