Bird
Raised Fist0
PyTesttesting~15 mins

Coverage report formats (terminal, HTML, XML) in PyTest - Build an Automation Script

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Generate coverage reports in terminal, HTML, and XML formats using pytest
Preconditions (3)
Step 1: Open a terminal in the project root directory
Step 2: Run pytest with coverage enabled and generate a terminal report using: pytest --cov=your_package
Step 3: Verify the coverage summary is displayed in the terminal
Step 4: Run pytest with coverage enabled and generate an HTML report using: pytest --cov=your_package --cov-report=html
Step 5: Verify an 'htmlcov' directory is created with the HTML report files
Step 6: Open 'htmlcov/index.html' in a browser and verify coverage details are shown
Step 7: Run pytest with coverage enabled and generate an XML report using: pytest --cov=your_package --cov-report=xml
Step 8: Verify a 'coverage.xml' file is created in the project root
Step 9: Open 'coverage.xml' in a text editor and verify it contains XML coverage data
✅ Expected Result: Coverage reports are generated and visible in terminal, HTML, and XML formats as specified
Automation Requirements - pytest with pytest-cov
Assertions Needed:
Verify terminal output contains coverage summary
Verify 'htmlcov/index.html' file exists and contains valid HTML
Verify 'coverage.xml' file exists and contains valid XML coverage data
Best Practices:
Use subprocess module to run pytest commands
Use explicit file existence checks for report files
Parse HTML and XML files to confirm report content validity
Clean up generated report files after test run
Automated Solution
PyTest
import subprocess
import os
import xml.etree.ElementTree as ET
from pathlib import Path


def test_coverage_reports():
    package_name = "your_package"  # Replace with your actual package name

    # Run pytest with coverage and terminal report
    result = subprocess.run(
        ["pytest", f"--cov={package_name}"],
        capture_output=True,
        text=True
    )
    assert result.returncode == 0, "Pytest run failed"
    assert "coverage" in result.stdout.lower(), "Coverage summary not found in terminal output"

    # Run pytest with coverage and HTML report
    result_html = subprocess.run(
        ["pytest", f"--cov={package_name}", "--cov-report=html"],
        capture_output=True,
        text=True
    )
    assert result_html.returncode == 0, "Pytest HTML report run failed"

    html_report_path = Path("htmlcov/index.html")
    assert html_report_path.exists(), "HTML coverage report file does not exist"

    # Simple check that HTML file contains expected tags
    with open(html_report_path, "r", encoding="utf-8") as f:
        html_content = f.read()
    assert "<html" in html_content.lower() and "coverage" in html_content.lower(), "HTML report content invalid"

    # Run pytest with coverage and XML report
    result_xml = subprocess.run(
        ["pytest", f"--cov={package_name}", "--cov-report=xml"],
        capture_output=True,
        text=True
    )
    assert result_xml.returncode == 0, "Pytest XML report run failed"

    xml_report_path = Path("coverage.xml")
    assert xml_report_path.exists(), "XML coverage report file does not exist"

    # Parse XML to verify it is well-formed and contains coverage data
    tree = ET.parse(xml_report_path)
    root = tree.getroot()
    assert root.tag == "coverage", "Root tag of XML report is not 'coverage'"

    # Cleanup generated reports
    if html_report_path.exists():
        for file in html_report_path.parent.glob("**/*"):
            if file.is_file():
                file.unlink()
        html_report_path.parent.rmdir()
    if xml_report_path.exists():
        xml_report_path.unlink()

This test automates the manual steps to generate coverage reports in three formats using pytest and pytest-cov.

First, it runs pytest with coverage enabled and checks the terminal output for coverage summary text.

Next, it runs pytest again to generate an HTML report, then verifies the 'htmlcov/index.html' file exists and contains expected HTML content.

Then, it runs pytest to generate an XML report and parses the 'coverage.xml' file to confirm it is valid XML with the root tag 'coverage'.

Finally, it cleans up the generated report files to keep the project directory clean.

This approach uses subprocess to run commands, file checks for report existence, and content parsing for validation, following best practices for test automation.

Common Mistakes - 4 Pitfalls
Not checking the return code of the pytest subprocess call
Hardcoding package name without clear instruction to replace
Not verifying the content of the HTML or XML reports
Not cleaning up generated report files after test
Bonus Challenge

Now add data-driven testing to generate coverage reports for three different package names

Show Hint

Practice

(1/5)
1. What is the main purpose of a coverage report in pytest?
easy
A. To generate test data automatically
B. To run tests faster by skipping some tests
C. To fix bugs in the code automatically
D. To show which parts of the code were tested and which were not

Solution

  1. Step 1: Understand coverage report purpose

    Coverage reports show which lines or parts of code were executed during tests.
  2. Step 2: Compare options with coverage purpose

    Only To show which parts of the code were tested and which were not correctly describes this purpose; others describe unrelated actions.
  3. Final Answer:

    To show which parts of the code were tested and which were not -> Option D
  4. Quick Check:

    Coverage report = tested code visibility [OK]
Hint: Coverage reports show tested vs untested code [OK]
Common Mistakes:
  • Confusing coverage with test execution speed
  • Thinking coverage generates test data
  • Believing coverage fixes bugs automatically
2. Which pytest command option generates an HTML coverage report?
easy
A. --cov-report=xml
B. --cov-report=summary
C. --cov-report=html
D. --cov-report=term

Solution

  1. Step 1: Recall pytest coverage report options

    Common options include 'term' for terminal, 'html' for HTML, and 'xml' for XML reports.
  2. Step 2: Match option to HTML report

    Only '--cov-report=html' generates an HTML report.
  3. Final Answer:

    --cov-report=html -> Option C
  4. Quick Check:

    HTML report option = --cov-report=html [OK]
Hint: HTML report uses --cov-report=html option [OK]
Common Mistakes:
  • Using --cov-report=xml for HTML report
  • Confusing term with html option
  • Using non-existent --cov-report=summary
3. Given this pytest command:
pytest --cov=myapp --cov-report=term-missing
What will the terminal output show?
medium
A. An HTML file opened in the browser
B. A summary of coverage with missing lines shown
C. An XML file saved to disk
D. No coverage information displayed

Solution

  1. Step 1: Understand --cov-report=term-missing

    This option shows coverage summary in terminal and highlights missing lines.
  2. Step 2: Match output to options

    A summary of coverage with missing lines shown matches terminal summary with missing lines; others describe HTML, XML, or no output.
  3. Final Answer:

    A summary of coverage with missing lines shown -> Option B
  4. Quick Check:

    term-missing = terminal summary with missing lines [OK]
Hint: term-missing shows missing lines in terminal [OK]
Common Mistakes:
  • Thinking term-missing opens HTML report
  • Expecting XML output from term-missing
  • Assuming no coverage info is shown
4. You ran pytest --cov=myapp --cov-report=html but no HTML report was generated. What is the most likely cause?
medium
A. The HTML report is saved in the current directory as 'htmlcov'
B. You forgot to install the pytest-cov plugin
C. You need to add --cov-report=xml to generate HTML
D. HTML reports are not supported by pytest

Solution

  1. Step 1: Check where HTML report is saved

    By default, pytest-cov saves HTML reports in 'htmlcov' folder in current directory.
  2. Step 2: Understand common confusion

    Users may think no report generated if they don't check 'htmlcov' folder; plugin installation is needed but question assumes it is installed.
  3. Final Answer:

    The HTML report is saved in the current directory as 'htmlcov' -> Option A
  4. Quick Check:

    HTML report folder = htmlcov [OK]
Hint: HTML report saved in 'htmlcov' folder by default [OK]
Common Mistakes:
  • Assuming HTML report appears in terminal
  • Forgetting to look in 'htmlcov' folder
  • Thinking XML option is needed for HTML
5. You want to share coverage results with a CI tool that requires XML input. Which pytest command correctly generates the XML coverage report file?
hard
A. pytest --cov=myapp --cov-report=xml
B. pytest --cov=myapp --cov-report=html
C. pytest --cov=myapp --cov-report=term
D. pytest --cov=myapp --cov-report=term-missing

Solution

  1. Step 1: Identify XML report option

    The '--cov-report=xml' option generates coverage results in XML format.
  2. Step 2: Match option to CI tool requirement

    CI tools needing XML input require this exact option; others generate HTML or terminal output.
  3. Final Answer:

    pytest --cov=myapp --cov-report=xml -> Option A
  4. Quick Check:

    XML report option = --cov-report=xml [OK]
Hint: Use --cov-report=xml for CI XML coverage [OK]
Common Mistakes:
  • Using HTML or terminal options for XML output
  • Not specifying any --cov-report option
  • Confusing term-missing with XML