Skip to content

Instantly share code, notes, and snippets.

@timkofu
Created September 23, 2022 10:42
Show Gist options
  • Save timkofu/0bfaa99293c31d9650ee6b0b68b067f9 to your computer and use it in GitHub Desktop.
Save timkofu/0bfaa99293c31d9650ee6b0b68b067f9 to your computer and use it in GitHub Desktop.
Test coverage.py elif branching.
## requirements.pip
# pytest
# pytest-cov
# black
## .coveragerc
# [run]
# branch = True
# [report]
# skip_covered = True
# skip_empty = True
# show_missing = True
# sort = Cover
# fail_under = 100
## pytest command
# pytest -rsxX -l --tb=short --strict-markers -x --cov=. --cov-config=.coveragerc
from enum import Enum
class Choices(Enum):
ZERO = 0
ONE = 1
def coverage_test_if(x: Choices) -> None:
if x == Choices.ONE:
print("One")
else: # This works
print("Zero")
def coverage_test_elif(x: Choices) -> None:
if x == Choices.ONE:
print("One")
elif x == Choices.ZERO: # This doesn't work
print("Zero")
def test_coverage_if_tests() -> None:
assert coverage_test_elif(x=Choices.ONE) is None
assert coverage_test_elif(x=Choices.ZERO) is None
assert coverage_test_if(x=Choices.ONE) is None
assert coverage_test_if(x=Choices.ZERO) is None
## Coverage report
# ---------- coverage: platform linux, python 3.10.7-final-0 -----------
# Name Stmts Miss Branch BrPart Cover Missing
# ----------------------------------------------------------------
# test_cov_branch.py 18 0 8 1 96% 37->exit
# ----------------------------------------------------------------
# TOTAL 18 0 8 1 96%
# FAIL Required test coverage of 100.0% not reached. Total coverage: 96.15%
@timkofu
Copy link
Author

timkofu commented Sep 23, 2022

Line 37 "doesn't work" because:

< nedbat> timkofu: right, because you never tested the case that line 37 was run, and the condition was false.
< nedbat> timkofu: another way to say it: line 37 is a condition that is always true

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment