AI Hints
CI/CD with GitHub Actions · Lesson 63 of 138

Test Coverage

What the tests touch.

⏱ 2 min read▶ Video at 1:11:56🎓 Free
Watch this lesson in the CI/CD with GitHub Actions courseWatch on YouTube ↗Full CI/CD with GitHub Actions course

Passing tests are good, but how much of the code do they actually run? Coverage measures that. It shows the percentage of lines executed during the tests, and which lines were never touched.

Test Coverage
From the video: Test Coverage
  • Do tests run all the code?
  • Coverage measures it
  • Lines never touched

Measuring coverage

Pytest, with dash dash cov, measures coverage of app dot py. All lines are covered. Now we add a new function, without a test. Coverage drops, and the missing column shows exactly which lines no test runs. Cov fail under makes the command fail if coverage drops below ninety percent.

Terminal
pytest -q --cov=app --cov-report=term-missing | grep -E "app.py|TOTAL"
app.py       6      0   100%
TOTAL        6      0   100%
printf '\n\ndef shipping(total):\n    if total > 50:\n        return 0\n    return 5\n' >> app.py
pytest -q --cov=app --cov-report=term-missing --cov-fail-under=90 | grep -E "app.py|FAIL|Required"
app.py      10      3    70%   12-14
FAIL Required test coverage of 90% not reached. Total coverage: 70.00%

A full quality job

Here's a quality job with three gates. Lint with flake8, check formatting with black, and run the tests with a minimum coverage. If any gate fails, the job fails, and the pull request can't be merged.

.github/workflows/quality.ymlyaml
name: Quality
on: [push, pull_request]
jobs:
  quality:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: pip install -q -r requirements.txt
      - name: Lint
        run: flake8
      - name: Format
        run: black --check .
      - name: Tests with coverage
        run: pytest -q --cov=app --cov-fail-under=90

Summary

Coverage shows how much code the tests run, and cov fail under turns it into a gate. Next, getting feedback fast.

Key takeaways
  • pytest --cov
  • term-missing
  • --cov-fail-under
Next up: Fast Feedback — minutes, not hours