Python · testing
conditional-assertion-in-test
python:conditional-assertion-in-test Tests should guarantee that at least one assertion runs on every execution path.
- Code
- SARJ065
- Default
- error
- Fix
- none
- Languages
- python
Why
Assertions confined to optional branches or loops let tests pass when a branch is skipped or a collection is empty.
Fix
Add an unconditional assertion, assert collection size before iterating, or make every branch assert or fail.
Before / after
Executed by this rule’s unit tests.
Before
Assertion may never run
def test_rows():
rows = fetch()
for row in rows:
assert row.id > 0
After
Test first asserts the collection size
def test_rows():
rows = fetch()
assert len(rows) == 3
for row in rows:
assert row.id > 0
Limits
- Only collected tests are analyzed.
- Exhaustive branches and explicit failure paths count as guaranteed checks.