Diff Coverage: Measure and Gate Coverage on Changed Lines

Raghav Chamadiya9 min read
On this page

A repository at 90% coverage can still merge a pull request whose new lines no test ever ran.

Diff coverage is the share of the executable lines a change added or modified that your tests actually ran. Codecov calls it patch coverage; Azure DevOps calls it diff coverage. It answers a narrower question than total coverage: not "how much of this repository is tested" but "is the code in this pull request tested". If a change touches 50 executable lines and tests run 40 of them, its diff coverage is 80%, whatever the rest of the repository looks like.

For what test coverage itself means, see what is test coverage.

Part of the code quality guide.

What is diff coverage?

Diff coverage = covered changed executable lines / total changed executable lines. Three words in that sentence do the work.

  • Changed means lines the diff adds or modifies. Lines the change deletes are gone, so there is nothing left to cover.
  • Executable means lines the coverage tool counts as runnable. Comments, blank lines, imports in some languages and type declarations are not executable, and the report simply has no entry for them.
  • Covered means the report marks the line as run by at least one test during the coverage run.

The diff is taken against a base: usually the merge-base with your main branch, which is what a pull request actually changed. Compare against the tip of main instead and you also count whatever landed there after you branched.

Diff coverage needs two inputs and nothing else: a diff from git, and a line-level coverage report from your test run. That is why several tools compute it with no server at all.

Why diff coverage beats total coverage as a gate

A total-coverage gate cannot see a single pull request, because the pull request is too small a part of the whole. Here is the arithmetic, with illustrative line counts.

A repository has 100,000 executable lines and tests run 80,000 of them: 80% total coverage. A pull request adds 50 executable lines and writes tests that run only 10 of them.

MeasureBeforeAfterVerdict
Total coverage80,000 / 100,000 = 80.00%80,010 / 100,050 = 79.97%Moved 0.03 points. A gate set at 79% passes it.
Diff coveragen/a10 / 50 = 20%Fails any sensible threshold.

Scroll the table sideways to see every column.

The same pull request looks harmless through one lens and plainly under-tested through the other. Now run the opposite case: a repository at 40% total coverage where every pull request is fully tested. A total gate at 80% blocks all of them, and the team learns to ignore or disable the gate.

Diff coverage fixes both failure modes:

  • It judges the code the author just wrote, so the author can fix it in this pull request.
  • It works on legacy repositories. You do not need to pay down years of untested code before a gate means anything; you only stop adding to it.
  • It is harder to game with easy tests elsewhere, since coverage added to unrelated files does not raise the number.
  • It keeps the average from sliding. If every change meets the bar, total coverage trends up over time without a campaign.

None of this makes total coverage useless. It is still the trend line to watch, and a drop limit on it catches deletions of tests. Use diff coverage for the per-change gate and total coverage for direction.

How to compute diff coverage

Whichever tool you choose, you first need a line-level report from your test run. Pick the format your tool reads.

LanguageCommand that produces a reportFormat
Pythonpytest --cov --cov-report=xmlCobertura XML (coverage.xml)
JavaScript or TypeScript (Jest)jest --coverage --coverageReporters=lcovLCOV (coverage/lcov.info)
JavaJaCoCo report goalJaCoCo XML
Gogo test -coverprofile=coverage.out ./...Go coverprofile (convert it first for diff-cover; repowise reads it directly)

Scroll the table sideways to see every column.

diff-cover

diff-cover is an open-source command line tool that computes diff coverage locally or in any CI. Per its README, the test runner must write Cobertura, Clover or JaCoCo XML, or LCOV. It compares against origin/main by default.

bash
pytest --cov --cov-report=xml
diff-cover coverage.xml --compare-branch=origin/main --fail-under=80

--compare-branch sets the base, and --fail-under=80 exits non-zero when diff coverage is below 80%. Reports can be written with --format, for example --format html:report.html or --format markdown:report.md, and --show-uncovered prints the uncovered lines to the console. You can pass several coverage files at once, which helps in a monorepo.

Its sibling diff-quality applies the same idea to linters: it reports only the violations on changed lines.

Codecov patch status

Codecov reports diff coverage as the codecov/patch status. It measures only the lines changed in the pull request or commit. You configure it in codecov.yml:

yaml
coverage:
  status:
    patch:
      default:
        target: 80%
        threshold: 0%

target: auto, the default, compares against the base commit's coverage. A number such as 80% sets an absolute bar. threshold is how far the result may fall below the target and still pass.

GitLab

GitLab has two separate features, and the docs say configuring one does not enable the other. The coverage keyword reads a percentage from the job log and shows it, with its change against the target branch, on the merge request. The artifacts:reports:coverage_report keyword uploads a Cobertura or JaCoCo XML report so GitLab can mark covered and uncovered lines in the merge request diff, only on files the merge request changed. Neither gives you a pass/fail diff coverage number by itself. For a hard gate in GitLab, run diff-cover in the job. See GitLab's code coverage docs.

Azure DevOps

Azure Pipelines computes diff coverage natively for pull requests, but Microsoft's docs say the feature is available only for Azure Repos. Publish results with the Publish Code Coverage Results v2 task, then put a file named azurepipelines-coverage.yml at the repository root:

yaml
coverage:
  status:
    comments: on
    diff:
      target: 60%

The default target is 70% of changed lines. The status check is advisory until you add a branch policy that requires it. See Microsoft's code coverage documentation.

GitHub

GitHub has no built-in diff coverage. The usual options are a coverage service such as Codecov, a step that runs diff-cover and fails on its exit code, or the repowise GitHub Action described below.

Setting a threshold

Start at the level your team already hits, then ratchet. A diff coverage threshold only works if the typical pull request passes it with room to spare.

  • Measure the last 20 merged pull requests first. If the median is 85%, a gate at 80% is realistic. If it is 40%, starting at 80% blocks everyone.
  • In my experience 70% to 80% is a workable starting point, and Azure DevOps defaults to 70%. That is opinion, not a standard. Do not copy a number from a blog post, including this one.
  • Allow small changes to pass. A three-line change with one uncovered line is 67% and not worth a failed build. Set a minimum number of changed lines before the gate applies, or use a threshold with some tolerance.
  • Treat a miss as a conversation. Some changed lines are legitimately not worth a test, such as a logging statement. A gate that allows an override with a reason beats one that people disable.
  • Keep a separate, looser limit on total coverage, a maximum drop, so deleting tests still gets noticed.

For how much coverage is enough in general, including the 80% question, see what is test coverage. What 80% means is simple: 80% of executable lines ran during the test suite. It says nothing about whether the tests assert anything useful.

Pitfalls

Most wrong diff coverage numbers come from four causes.

  1. Deleted lines. A change that mostly deletes code has few or no changed executable lines. Tools report "no data" or 100%. That is correct, but do not read it as "well tested".
  2. Generated and vendored code. A regenerated protobuf file adds thousands of changed lines you never wrote or tested. Exclude generated paths from the coverage run or the diff. Codecov has an ignore setting for paths in codecov.yml.
  3. Moves and refactors. Moving a function to a new file shows up as added lines in the new file. If the old tests covered the code before the move and the report is measured correctly, the lines are covered; if the move breaks the path mapping, they read as uncovered. Check the path mapping before blaming the tests.
  4. Reports from the wrong commit. The report must come from the code under review. A stale report from an earlier run puts coverage on lines that have since moved, so line numbers no longer match the diff.

Two more habits help. Run the gate on the same test selection that produces the report: if CI shards the suite, merge the shards' reports first, or you will see false gaps. And remember what the number cannot tell you. A line can run without any assertion checking it, which is the argument for good review, not for dropping the gate.

Diff coverage with repowise

repowise computes patch coverage, the same figure, with repowise coverage check. It needs only git and a report: no index, no ingest, no LLM key.

bash
repowise coverage check origin/main...HEAD --report coverage/lcov.info --fail-under 80

The revision base...head diffs from the merge-base, which is what a pull request changed. Exit 0 means pass or nothing to judge, 1 means below the gate, and 2 means it could not run: no usable report, an unknown revision, a shallow clone with no merge-base, or bad config. Only files the report marks measured count. A changed file that is not in the report is listed as not_in_report, never counted as 0%, so a missing report entry does not silently fail the gate. With an index, each uncovered range names the test file to extend.

The gate settings live in the coverage: block of .repowise/config.yaml:

yaml
coverage:
  fail_under: 80          # patch-coverage gate for `coverage check`
  min_coverable_lines: 5  # small-change tolerance
  max_drop: 0.5           # most project coverage may fall from the base, in points
  gates:                  # path-scoped gates
    - {name: api, paths: ["/services/api/"], fail_under: 85}

That covers the threshold advice above: a small-change tolerance, a drop limit on the project total, and stricter gates for the paths that matter. The same patch coverage figure is in the patch_coverage block of the get_change_risk MCP tool, so an agent can check its own change before pushing. The repowise CI integrations, a GitHub Action and a GitLab template, run the same check; see the test coverage feature page.

Measured and inferred reach

repowise keeps two kinds of answer apart and never averages them. Measured answers come from an ingested coverage report and can be a percentage. Inferred answers come from the call and import graph and are always labelled inferred, never a percentage, because a call edge says control can reach a file, not that a run did.

That matters for the case diff coverage cannot handle: no report at all. Without one, repowise still tells you which tests reach a changed file from the graph, labelled as inferred, and it will not call a file untested when something reaches it. Patch coverage itself needs a report, and the CLI says so instead of inventing a number.

Impacted tests

Diff coverage tells you a change is covered. Test impact analysis tells you which tests to run for it. repowise impacted-tests main...HEAD looks up the changed lines in a per-test coverage map and returns the tests whose recorded coverage touches them.

bash
pytest --cov=<package> --cov-context=test
repowise coverage add .coverage
repowise impacted-tests main...HEAD --format list | xargs pytest

Each result says how it was found. Coverage-backed matches are separated from graph guesses, which appear in their own "NOT coverage-backed" table. When nothing can answer, the output says "unknown, run the full suite to be safe" and does not report an empty list as no tests needed.

Untested hotspots

The gap diff coverage cannot see is old code that never gets a test because nobody changes it in a pull request that is checked. After you ingest a report, repowise health flags an untested_hotspot: a file in the top quartile of churn, with at least 4 dependents and line coverage below 40%. That is the list to work from when you want to raise coverage where it protects the most. The ranking is explained in which important code has no tests, and the idea in the test coverage gap glossary entry. Using patch coverage on every change and the hotspot list on the backlog covers both directions, and both belong in your pull request checklist.

FAQ

What is diff coverage?
Diff coverage is the percentage of executable lines added or modified in a change that tests ran. Codecov calls it patch coverage. It judges one pull request, where total coverage judges the whole repository.
What is the difference between diff coverage and code coverage?
Code coverage, or total coverage, is the share of all executable lines that tests ran. Diff coverage counts only the lines a change touched. A repository can stay at 80% total while a pull request in it has 20% diff coverage, because a small change barely moves a large denominator.
How do I calculate diff coverage?
Generate a line-level coverage report, then compare it to the git diff. With diff-cover that is diff-cover coverage.xml --compare-branch=origin/main --fail-under=80. Codecov, Azure DevOps and repowise coverage check compute the same figure without a separate tool.
What is a good diff coverage threshold?
Start at what your recent pull requests already achieve, often somewhere around 70% to 80% in practice, and raise it gradually. Azure DevOps defaults to 70%. A gate that most pull requests fail gets disabled, so set it where passing is normal and failing means something.
What does 80% code coverage mean?
It means tests ran 80% of the executable lines in the measured code. It does not mean the other 20% is risky or that the 80% is well tested, since a line can run without any assertion on its result. Used as a per-change figure, 80% diff coverage says four in five changed lines ran under test.
Does diff coverage include deleted lines?
No. Deleted lines no longer exist, so there is nothing to run. A change that only deletes code usually reports no changed executable lines, and tools show no data or 100% for it.