0
0
PytestHow-ToBeginner ยท 3 min read

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 as report.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-html is required).
  • Forgetting to add --html=filename.html option, so no report is generated.
  • Using relative paths incorrectly for the report file location.
  • Not using --self-contained-html when 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

OptionDescription
--html=FILEGenerate HTML report saved to FILE
--self-contained-htmlEmbed CSS/JS inside report for portability
--clean-alluredirClean previous allure results (if using allure)
--maxfail=NUMStop after NUM failures
-vVerbose 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.