Python coverage is an invaluable tool for ensuring your code is reliable and maintainable. It highlights untested areas, helping you aim for 100% coverage.
But achieving full coverage doesn’t mean testing every single line—it’s about being strategic and practical.
When coverage tools identify untested code, you have choices: write a test or decide that the code is trivial and doesn’t warrant one. For example, testing simple logic like this is often unnecessary:
if page_num:
url += f'?page={page_num}'
Testing trivial cases wastes time and resources better spent elsewhere. Instead, focus on components where bugs are likely or have been recurring issues. My rules for writing tests are:
- Anticipate Bugs: If a component is prone to edge cases or critical to your application, write a test.
- Address Recurring Problems: If you’ve seen regressions in a specific area, improve its coverage to avoid repeated issues.
When you write tests, don’t try to cover every possible edge case upfront. Start with common scenarios, and if a bug arises later, add a targeted test for that case. This approach is efficient and ensures your tests remain practical without being overburdened.
Sometimes, certain lines of code may not be worth testing at all. For those cases, you can use # pragma: no coverage
to skip them in coverage checks. For example:
if __name__ == "__main__": # pragma: no coverage
main()
This tells the coverage tool to ignore the marked lines, ensuring your reports focus on meaningful code.
I run tests automatically with pre-commit hooks, ensuring all tests are executed before any changes are committed. This practice will help you detect issues early and will keep your codebase stable.
The goal isn’t perfection but intentionality. By using coverage tools wisely, you ensure every part of your codebase is either tested or thoughtfully excluded, creating a robust and maintainable application.
So, at the end when you run your coverage reports, you should always see 100%. It doesn't mean you've tested "perfectly" but you have accounted for all areas of your code and you are taking responsibility for its reliability.
apps/transformations/settings.py 6 0 100%
apps/transformations/signals.py 4 0 100%
apps/transformations/tests.py 0 0 100%
config/urls.py 4 0 100%
extensions/apps/dashlets/tests.py 0 0 100%
----------------------------------------------------------------------------------------
TOTAL 2532 0 100%
If you do it this way, you will always have time for writing unit tests.
Top comments (0)