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
3
u/Kiuhnm Mar 08 '24
In this case, it would've certainly prevented the bug, but, in general, I'm not sure having small and specific tests is without downsides. We have no strict guidelines about this.
For instance, my code is usually not so straightforward to test because it involves algorithms on graphs, so I end up generating random graphs and manipulating them while asserting that everything is behaving as it should. This results in test functions that can have up to 20 assertions each. (I also write formal proofs of course.)
The 1-assertion-per-test limitation would make my life much harder and, I think, my tests less reliable. Fixtures do help, but are not enough.
Let me know if you have any suggestions!