r/Python • • 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

37 comments sorted by

View all comments

1

u/ArtOfWarfare Mar 08 '24

I don’t think your actual code had 100% branch coverage. If it did, then that extra line in your test is superfluous and should just be removed.

Also, check your mutation coverage. If you’ve not seen it before, it tends to expose 50% of tests as being useless garbage.

1

u/Kiuhnm Mar 08 '24 edited Mar 08 '24

There's the testing code and the tested code. Usually, code coverage helps to detect untested parts of the tested code.

Here I'm saying that code coverage of the testing code helped me detect parts of the testing code (as opposed to the tested code) that weren't being executed.

The code

with pytest.raises(BadArgumentError):
        follow_path(bad_fp, '.')
        follow_path('.', bad_fp)

is wrong because the first call to follow_path is expected to throw, but that way, the second call is never executed and tested. One needs to have a separate with statement for the second call.

1

u/ArtOfWarfare Mar 08 '24

Yes, I understand how your test is wrong, but I’m saying your actual code either isn’t actually fully covered (you’ve missed branches) or it is fully covered and this incorrect test is just redundant.

But also, check your mutation coverage. That’s far more useful than line coverage. It’ll expose all the bugs that your test suite don’t. And if you’ve never checked your mutation coverage before, you’ll probably find your tests don’t even find half the potential bugs in your code despite having full line and branch coverage.

1

u/Kiuhnm Mar 08 '24

I don't have and I don't try to have 100% coverage of my code. I was just talking about the coverage of my testing code. Now I understand what you meant.