0
0
PyTesttesting~8 mins

pytest-html for HTML reports - Framework Patterns

Choose your learning style9 modes available
Framework Mode - pytest-html for HTML reports
Folder Structure
project-root/
├── tests/
│   ├── test_login.py
│   ├── test_checkout.py
│   └── conftest.py
├── reports/
│   └── latest_report.html
├── pytest.ini
└── requirements.txt
    

This structure keeps tests in tests/, reports in reports/, and config files at root.

Test Framework Layers
  • Tests: Test functions inside tests/ folder using pytest.
  • Fixtures: Setup and teardown logic in conftest.py for reusable test resources.
  • Configuration: pytest.ini to configure pytest and pytest-html plugin options.
  • Reports: HTML reports generated by pytest-html saved in reports/.
  • Dependencies: Managed in requirements.txt including pytest and pytest-html.
Configuration Patterns

Use pytest.ini to configure pytest-html options and test runs:

[pytest]
addopts = --html=reports/latest_report.html --self-contained-html
    

This sets the report output path and embeds CSS for a single file report.

Use conftest.py for fixtures like browser setup or environment variables.

import pytest

@pytest.fixture(scope='session')
def base_url():
    return "https://example.com"
    

For sensitive data like credentials, use environment variables or separate config files not committed to version control.

Test Reporting and CI/CD Integration

pytest-html generates a detailed HTML report with test results, screenshots (if added), and logs.

In CI/CD pipelines (like GitHub Actions, Jenkins), run tests with:

pytest --html=reports/latest_report.html --self-contained-html
    

Then archive or publish the reports/latest_report.html as a build artifact or web page for easy access.

This helps teams quickly see test outcomes and failures in a readable format.

Best Practices
  • Keep reports in a dedicated reports/ folder to avoid clutter.
  • Use --self-contained-html to create portable reports without external dependencies.
  • Integrate report generation into CI/CD to automate feedback on test runs.
  • Use fixtures in conftest.py to manage test setup cleanly.
  • Secure sensitive data by using environment variables, not hardcoded in tests or configs.
Self Check

Question: Where in this framework structure would you add a new fixture to provide a database connection for tests?

Key Result
Use pytest-html plugin with pytest.ini config and conftest.py fixtures to generate and manage HTML test reports.