Test Overview
This test runs a simple function and verifies its output. It uses coverage exclusion comments to skip a part of the code from coverage reports.
Jump into concepts and practice - no test required
This test runs a simple function and verifies its output. It uses coverage exclusion comments to skip a part of the code from coverage reports.
import pytest def greet(name): if name == "": # pragma: no cover return "Hello, Stranger!" return f"Hello, {name}!" def test_greet(): assert greet("Alice") == "Hello, Alice!"
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | Python environment ready with pytest and coverage installed | — | PASS |
| 2 | pytest runs test_greet function | Function greet is called with argument 'Alice' | Check if greet('Alice') returns 'Hello, Alice!' | PASS |
| 3 | pytest asserts the returned value matches expected | Returned value is 'Hello, Alice!' | assert 'Hello, Alice!' == 'Hello, Alice!' | PASS |
| 4 | Coverage tool analyzes code coverage | Coverage report generated excluding lines marked with '# pragma: no cover' | Verify lines with '# pragma: no cover' are excluded from coverage | PASS |
| 5 | Test ends with all assertions passing | Test report shows 1 test passed, coverage excludes specified lines | — | PASS |
# pragma: no cover in your Python test code when using pytest and coverage.py?# pragma: no cover tells coverage.py to ignore that line when measuring test coverage.# pragma: no cover exactly as written.def func(x):
if x > 0:
return x
else:
return -x # pragma: no cover
What will coverage.py report about the line with return -x if it is never executed?# pragma: no cover tells coverage.py to ignore that line regardless of execution.def example():
print('Start') # pragma no cover
print('End')But coverage.py still counts the first print line as uncovered. What is the likely problem?# pragma: no cover. Missing colon causes coverage.py to ignore the comment.# pragma: no cover only works line-by-line. Which approach correctly excludes multiple lines without affecting other code?# pragma: no cover comment excludes coverage only for the line it is on, so each line must have it to be excluded.if False: changes code behavior or testability; partial comments on first and last lines do not exclude intermediate lines.