A pre-commit hook that enforces a coverage quality gate for Python projects.
It reads the line-rate from coverage.xml (generated by pytest-cov) and compares it against a baseline stored in .coverage-baseline. If coverage regresses the commit is blocked. When coverage improves, the baseline is updated automatically.
| Situation | Exit code | Message |
|---|---|---|
coverage.xml or .coverage-baseline missing |
1 |
[coverage-gate] ERROR: … |
| Current coverage < baseline | 1 |
[coverage-gate] FAIL: … |
| Current coverage == baseline | 0 |
[coverage-gate] OK: … |
| Current coverage > baseline | 0 |
[coverage-gate] SUCC: … — baseline file updated |
pip install pytest-coverage-gate- Python ≥ 3.9
- A
coverage.xmlfile produced bypytest --cov --cov-report=xml - A
.coverage-baselinefile containing a single floating-point number (e.g.85.00)
Add a step to your test run (locally or in CI) that produces coverage.xml:
pytest --cov=<your_package> --cov-report=xmlSet your initial baseline (you can use the current coverage percentage):
echo "0.00" > .coverage-baseline
git add .coverage-baselineTip: commit
.coverage-baselineto version control so the gate is enforced for every contributor.
repos:
- repo: https://github.com/kelsoncm/pytest-coverage-gate
rev: v1.0.1 # use the latest tag
hooks:
- id: pytest-coverage-gateIf coverage.xml or .coverage-baseline are not in the repository root (e.g. they live under src/), pass custom paths via args:
repos:
- repo: https://github.com/kelsoncm/pytest-coverage-gate
rev: v1.0.1
hooks:
- id: pytest-coverage-gate
args:
- --coverage-xml=src/coverage.xml
- --baseline=src/.coverage-baselinepre-commit run pytest-coverage-gate --all-filesOr it runs automatically on every git commit once pre-commit is installed:
pre-commit installThe script can also be run directly without pre-commit:
pip install pytest-coverage-gate
pytest-coverage-gateUse --coverage-xml and --baseline to point to files in non-default locations:
pytest-coverage-gate --coverage-xml src/coverage.xml --baseline src/.coverage-baseline[coverage-gate] SUCC: cobertura evoluiu de atual 82.00% para 85.50%
[coverage-gate] FAIL: cobertura regrediu de atual 85.50% para 79.00%
MIT