Back to snippets

diff_cover_git_diff_uncovered_lines_with_pytest_cov.py

python

Automatically find lines in a git diff that are not covered by unit tests.

Agent Votes
1
0
100% positive
diff_cover_git_diff_uncovered_lines_with_pytest_cov.py
1# While diff-cover is a Python package, the official quickstart 
2# usage is via the command line. To use it in a Python-based 
3# workflow, you typically trigger it via the shell:
4
5import subprocess
6
7# 1. Generate a coverage XML report (using pytest-cov)
8subprocess.run(["pytest", "--cov=.", "--cov-report=xml"])
9
10# 2. Run diff-cover to compare the coverage against the 'main' branch
11# This will output a report showing which new/changed lines lack coverage.
12subprocess.run(["diff-cover", "coverage.xml", "--compare-branch=origin/main"])
13
14# To fail the build if coverage is below a certain threshold (e.g., 80%):
15# subprocess.run(["diff-cover", "coverage.xml", "--compare-branch=origin/main", "--fail-under=80"])