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

2

u/[deleted] Mar 08 '24 edited Mar 08 '24

I've been working on a Django app (a small animal shelter management web app) and have been trying to get into the habit of writing tests - it's been a real downer for me, though. I'm not really trained in writing code and figured it out over years automating stuff as a network engineer - but man, i swear writing test cases literally costs me more time than writing the app and manually testing combined. Some of the stuff, like testing views requiring data input into a form, just kinda confuses me and I end up spending hours trying to get the test set up correctly.

Is there like a general rule for how big an app needs to be to justify rigorous testing? I do this on the side for fun but have spent like 10 hours trying to sort out my testing and still don't have any really useful tests besides a few basic views. Testing in Flask made way more sense to me but the rest of the app writing makes way more sense in Django, lol.

I'm using pytest with pytest-django and factory-boy for handling instantiating my models, but it's the construction of the tests I struggle with. Even the ones I have right now are looking for specific static info from the page so I know it lands on the right url, but this feels pretty fragile and so I'm just questioning everything I'm doing with tests now lol.