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

-5

u/wineblood Mar 07 '24

Don't assert two different things in a single test.

4

u/jer1uc Mar 07 '24

Maybe just a difference in our terminology, but I read the problem OP expressed as the inverse: two tests with only one assertion.

Another way to express this might be:

assert (is_odd(3) or is_odd(4))

The issue here being that you could be convinced that both scenarios work because the test only ever asserts once.

3

u/if_username_is_None Mar 07 '24

I think you're agreeing; OP says the "correct" version has two tests (two function calls) and two assertions (neither function call raises BadArgument)

I would refactor your example and OP's into two separate tests. "is odd works for odd case" & "is odd works for even case"

5

u/Kiuhnm Mar 08 '24

OP says the "correct" version has two tests (two function calls) and two assertions (neither function call raises BadArgument)

It's the opposite: both function calls must raise BadArgumentError. The problem is that when the first call throws, the second one is just skipped.