How to Use pytest-html for Test Reports in Pytest
To use
pytest-html for generating test reports, first install it with pip install pytest-html. Then run your tests with pytest --html=report.html to create an HTML report file showing test results.Syntax
The basic syntax to generate an HTML report with pytest-html is:
pytest --html=report.html: Runs tests and saves the report asreport.html.--self-contained-html(optional): Embeds CSS and JavaScript inside the report for easy sharing.
You can also specify the report path and customize the report name.
bash
pytest --html=report.html --self-contained-html
Example
This example shows a simple test file and how to run pytest with pytest-html to generate a report.
python
import pytest def test_addition(): assert 1 + 1 == 2 def test_subtraction(): assert 5 - 3 == 2 # Run this command in terminal: # pytest test_sample.py --html=report.html --self-contained-html
Output
============================= test session starts =============================
collected 2 items
test_sample.py .. [100%]
============================== 2 passed in 0.01s ==============================
HTML report generated: report.html
Common Pitfalls
Common mistakes when using pytest-html include:
- Not installing the plugin before running tests (
pip install pytest-htmlis required). - Forgetting to add
--html=filename.htmloption, so no report is generated. - Using relative paths incorrectly for the report file location.
- Not using
--self-contained-htmlwhen sharing the report, causing missing styles.
Always verify the report file is created after test run.
bash
## Wrong way (no report generated): # pytest test_sample.py ## Right way: # pytest test_sample.py --html=report.html --self-contained-html
Quick Reference
| Option | Description |
|---|---|
| --html=FILE | Generate HTML report saved to FILE |
| --self-contained-html | Embed CSS/JS inside report for portability |
| --clean-alluredir | Clean previous allure results (if using allure) |
| --maxfail=NUM | Stop after NUM failures |
| -v | Verbose output during test run |
Key Takeaways
Install pytest-html plugin with pip before use.
Run tests with --html=report.html to generate the report.
Use --self-contained-html to create a portable report file.
Check that the report file is created after tests finish.
Avoid running pytest without the --html option if you want reports.