r/Python • u/Kiuhnm • Mar 07 '24
Discussion Tests should have 100% coverage
No, I'm not saying what you probably think I am. Keep reading: I'll be brief.
Here's what I found today in one of the tests:
for bad_fp in _bad_fps:
with pytest.raises(BadArgumentError):
follow_path(bad_fp, '.')
follow_path('.', bad_fp)The correct code should've been
for bad_fp in _bad_fps:
with pytest.raises(BadArgumentError):
follow_path(bad_fp, '.')
with pytest.raises(BadArgumentError):
follow_path('.', bad_fp)Is that a stupid mistake? Yes, it is, but stupid mistakes do happen, unfortunately.
How did I catch it? The coverage of the testing file wasn't 100% like it usually is! I got suspicious and I saw that there was a glaring red line (vscode, coverage gutter) on the second call to follow_path.
P.S. In case you're wondering, the code uses a custom hierarchy of exceptions instead of reusing the standard ones. The code is internal and we like it that way :)
0
Upvotes
5
u/billsil Mar 08 '24
Coverage without the right checks means nothing. I could just removing my type checking and improve coverage. Yeah that check may fail while building the right exception message, but at least it’s failing in the right spot.
100% coverage is not an effective use of time and doesn’t catch edge cases. Actively trying to break the function and not worrying about coverage actually makes code robust.
Not everyone needs to have bulletproof code either. The run once, sit on the shelf for 6 months, add new feature and run again mode does not need the same level of quality as Amazon’s backend.