|Ned Batchelder : Blog | Code | Text | Site|
Excluding code from coverage
» Home : Code : coverage.py
Created 13 June 2009, last updated 4 June 2011
You may have code in your project that you know won’t be executed, and you want to tell coverage to ignore it. For example, you may have debugging-only code that won’t be executed during your unit tests. You can tell coverage to exclude this code during reporting so that it doesn’t clutter your reports with noise about code that you don’t need to hear about.
Coverage will look for comments marking clauses for exclusion. In this code, the “if debug” clause is excluded from reporting:
Any line with a comment of “pragma: no cover” is excluded. If that line introduces a clause, for example, an if clause, or a function or class definition, then the entire clause is also excluded. Here the __repr__ function is not reported as missing:
Excluded code is executed as usual, and its execution is recorded in the coverage data as usual. When producing reports though, coverage excludes it from the list of missing code.
When measuring branch coverage, a condtional will not be counted as a branch if one of its choices is excluded:
Because the else clause is excluded, the if only has one possible next line, so it isn’t considered a branch at all.
Coverage identifies exclusions by matching lines against a list of regular expressions. Using configuration files or the coverage API, you can add to that list. This is useful if you have often-used constructs to exclude that can be matched with a regex. You can exclude them all at once without littering your code with exclusion pragmas.
For example, you might decide that __repr__ functions are usually only used in debugging code, and are uninteresting to test themselves. You could exclude all of them by adding a regex to the exclusion list:
For example, here’s a list of exclusions I’ve used:
Note that when using the exclude_lines option in a configuration file, you are taking control of the entire list of regexes, so you need to re-specify the default “pragma: no cover” match if you still want it to apply.
A similar pragma, “no branch”, can be used to tailor branch coverage measurement. See Branch coverage measurement for details.
Excluding source files
See Specifying source files for ways to limit what files coverage.py measures or reports on.