Bird
Raised Fist0
PyTesttesting~15 mins

Coverage in CI pipelines 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
Verify test coverage report generation in CI pipeline using pytest
Preconditions (3)
Step 1: Run pytest with coverage option in the CI pipeline
Step 2: Generate coverage report in XML format
Step 3: Upload or save the coverage report as an artifact
Step 4: Verify the coverage report file exists after the test run
✅ Expected Result: The coverage report XML file is generated and saved successfully in the CI pipeline after running pytest tests
Automation Requirements - pytest
Assertions Needed:
Assert that the coverage XML report file exists after test execution
Best Practices:
Use pytest-cov plugin for coverage measurement
Use explicit command line options to generate coverage report
Check for coverage report file existence as proof of coverage generation
Keep test code clean and modular
Automated Solution
PyTest
import os
import subprocess
import pytest


def test_coverage_report_generation():
    # Run pytest with coverage options to generate XML report
    result = subprocess.run([
        'pytest',
        '--cov=.',
        '--cov-report=xml:coverage.xml',
        '--maxfail=1',
        '--disable-warnings'
    ], capture_output=True, text=True)

    # Assert pytest run was successful
    assert result.returncode == 0, f"Pytest failed:\n{result.stdout}\n{result.stderr}"

    # Assert coverage.xml file is created
    assert os.path.exists('coverage.xml'), "Coverage XML report was not generated"

    # Clean up coverage file after test
    os.remove('coverage.xml')

if __name__ == '__main__':
    pytest.main([__file__])

This test runs pytest as a subprocess with coverage options to generate an XML report named coverage.xml.

We capture the output and check the return code to ensure tests passed.

Then we assert that the coverage.xml file exists, confirming coverage data was generated.

Finally, we clean up the coverage file to keep the environment clean.

This simulates what a CI pipeline would do: run tests with coverage and produce a report file.

Common Mistakes - 3 Pitfalls
Not using the pytest-cov plugin and trying to measure coverage manually
Not checking the pytest return code before asserting coverage file existence
Hardcoding file paths without cleanup
Bonus Challenge

Now add data-driven testing to run coverage report generation on multiple test folders

Show Hint

Practice

(1/5)
1. What is the main purpose of using coverage tools like pytest --cov in CI pipelines?
easy
A. To generate user documentation
B. To speed up the test execution time
C. To deploy the application automatically
D. To measure how much of the code is tested automatically

Solution

  1. Step 1: Understand coverage tools in testing

    Coverage tools measure the percentage of code executed by tests.
  2. Step 2: Role in CI pipelines

    In CI, coverage helps ensure tests cover enough code to catch bugs early.
  3. Final Answer:

    To measure how much of the code is tested automatically -> Option D
  4. Quick Check:

    Coverage measures tested code = D [OK]
Hint: Coverage shows tested code percentage in CI [OK]
Common Mistakes:
  • Confusing coverage with test speed
  • Thinking coverage deploys code
  • Assuming coverage creates docs
2. Which of the following is the correct command to run pytest with coverage reporting?
easy
A. pytest --cov=.
B. pytest --cov-report=html --cov
C. pytest -coverage
D. pytest --coverage=report

Solution

  1. Step 1: Identify correct pytest coverage syntax

    The correct syntax uses --cov to specify coverage on the current directory.
  2. Step 2: Analyze options

    pytest --cov=. correctly runs coverage on the current directory with default terminal reporting.
  3. Final Answer:

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

    Correct pytest coverage command = B [OK]
Hint: Use --cov and --cov-report together for coverage output [OK]
Common Mistakes:
  • Using incorrect flags like --coverage=report
  • Missing --cov option
  • Wrong flag syntax like -coverage
3. Given this pytest command in a CI pipeline:
pytest --cov=myapp --cov-report=term

What will be the output shown in the CI logs?
medium
A. A summary of coverage percentages printed in the terminal
B. No coverage information will be shown
C. A detailed HTML coverage report saved to disk
D. An error because --cov-report=term is invalid

Solution

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

    The term option prints coverage summary in the terminal output.
  2. Step 2: Analyze expected CI log output

    The CI logs will show coverage percentages summary, not an HTML file or error.
  3. Final Answer:

    A summary of coverage percentages printed in the terminal -> Option A
  4. Quick Check:

    --cov-report=term shows summary in terminal = C [OK]
Hint: term report prints coverage summary in console [OK]
Common Mistakes:
  • Expecting HTML report in terminal
  • Assuming no coverage output
  • Thinking --cov-report=term is invalid
4. You added coverage to your CI pipeline with this command:
pytest --cov=myapp --cov-report=html

But the coverage report is missing after the run. What is the most likely cause?
medium
A. The --cov option is misspelled
B. The coverage report is saved in a different directory, not checked by CI
C. pytest does not support coverage reporting
D. The tests did not run because of a syntax error

Solution

  1. Step 1: Understand where coverage HTML reports are saved

    By default, HTML reports are saved in a folder named htmlcov in the current directory.
  2. Step 2: Check CI pipeline file handling

    If the CI pipeline does not collect or upload this folder, the report will appear missing.
  3. Final Answer:

    The coverage report is saved in a different directory, not checked by CI -> Option B
  4. Quick Check:

    HTML report saved in htmlcov folder = A [OK]
Hint: Check htmlcov folder location in CI artifacts [OK]
Common Mistakes:
  • Assuming --cov is misspelled without checking
  • Believing pytest lacks coverage support
  • Ignoring test run errors
5. In a CI pipeline, you want to fail the build if coverage falls below 80%. Which pytest coverage option helps enforce this?
hard
A. --fail-if-coverage-below=80
B. --coverage-threshold=80
C. --cov-fail-under=80
D. --cov-minimum=80

Solution

  1. Step 1: Identify pytest coverage option for minimum coverage

    The correct option is --cov-fail-under which sets a minimum coverage percentage.
  2. Step 2: Understand CI build failure behavior

    If coverage is below the set value, pytest returns a failure status causing CI to fail the build.
  3. Final Answer:

    --cov-fail-under=80 -> Option C
  4. Quick Check:

    Fail build if coverage under 80% = B [OK]
Hint: Use --cov-fail-under to enforce coverage minimum [OK]
Common Mistakes:
  • Using incorrect or non-existent flags
  • Confusing coverage reporting with build failure
  • Assuming coverage threshold is set elsewhere