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
1
u/Kiuhnm Mar 08 '24
I still consider them unit tests because there's nothing below them, but a unit may be a small class instead of a single function or method.
If I'm trying to prove 10 different behaviors of a class, I'll write 10 different test functions.
I'm under the impression that many programmers want to know what's wrong with their test just by looking at the logs. I'm just happy to know that there's a problem with a particular graph and sequence of operations. Then I analyze the whole thing (we're still talking of a single class) and find out what's wrong.
I guess different problems require different approaches.
The mistake I talked about wasn't mine :), but I dislike relying on "advanced" pytest features as well. I feel that they're too limited for my taste. For instance,
pytest.mark.parametrizeonly supports a single sequence of args. Repeating the decorator results in the cartesian product of the args, which is not what I want.Why should I try to combine big lego blocks to get what I want when I can just use Python itself?
Also, if I change testing library, most of what I wrote will still work.
I'm probably the only guy who organizes his notes as a tree of small txt files, so maybe it's just me. I like to keep things simple. Luckily for me, I have lots of freedom.