Excluding code from coverage.py¶
You may have code in your project that you know won’t be executed, and you wantto tell coverage.py to ignore it. For example, you may have debugging-onlycode that won’t be executed during your unit tests. You can tell coverage.py toexclude this code during reporting so that it doesn’t clutter your reports withnoise about code that you don’t need to hear about.
Coverage.py will look for comments marking clauses for exclusion. In thiscode, the “if debug” clause is excluded from reporting:
a=my_function1()ifdebug:# pragma: no covermsg="blah blah"log_message(msg,a)b=my_function2()
Any line with a comment of “pragma: no cover” is excluded. If that lineintroduces a clause, for example, an if clause, or a function or classdefinition, then the entire clause is also excluded. Here the __repr__function is not reported as missing:
classMyObject(object):def__init__(self):blah1()blah2()def__repr__(self):# pragma: no coverreturn"<MyObject>"
Excluded code is executed as usual, and its execution is recorded in thecoverage data as usual. When producing reports though, coverage.py excludes itfrom the list of missing code.
Branch coverage¶
When measuringbranch coverage, a conditional will not becounted as a branch if one of its choices is excluded:
defonly_one_choice(x):ifx:blah1()blah2()else:# pragma: no cover# x is always true.blah3()
Because theelse
clause is excluded, theif
only has one possible nextline, so it isn’t considered a branch at all.
Advanced exclusion¶
Coverage.py identifies exclusions by matching lines against a list of regularexpressions. Usingconfiguration files or the coverageAPI, you can add to that list. This is useful if you haveoften-used constructs to exclude that can be matched with a regex. You canexclude them all at once without littering your code with exclusion pragmas.
For example, you might decide that __repr__ functions are usually only used indebugging code, and are uninteresting to test themselves. You could excludeall of them by adding a regex to the exclusion list:
[report]exclude_lines=def__repr__
For example, here’s a list of exclusions I’ve used:
[report]exclude_lines=pragma:nocoverdef__repr__ifself.debug:ifsettings.DEBUGraiseAssertionErrorraiseNotImplementedErrorif0:if__name__==.__main__.:
Note that when using theexclude_lines
option in a configuration file, youare taking control of the entire list of regexes, so you need to re-specify thedefault “pragma: no cover” match if you still want it to apply.
A similar pragma, “no branch”, can be used to tailor branch coveragemeasurement. SeeBranch coverage measurement for details.
Excluding source files¶
SeeSpecifying source files for ways to limit what files coverage.py measures or reportson.