How do you write unit tests for Python?
In a nutshell,
-
pytest(and Tox/Nox, but those are more for CI/CD) is the industry standard, so use that unless you really like the boilerplate ofunittestfor whatever reason. -
Write tests that each test a particular edge case or feature, including correct rising of exceptions. The number of tests doesn't matter, but follow the KISS principle for individual tests.
-
If you need setup code for your tests, make those as fixtures in a
conftest.pyfile and have your tests call those. -
Try breaking up your tests either per-file, or in some other logical grouping.
-
Try not to write your tests too tightly coupled with the actual program, because if you need to change your tests every time you make a change to the codebase that's not good.
On that note, try to also design your codebase to be easier to test:
-
Write "pure" functions (meaning, they don't depend on external mutable state and they give the same output from the same passed arguments every time if possible).
-
Encapsulate all mutable state in classes (in other words, don't use global variables - constants are fine).
-
Keep your individual functions/methods relatively short, and have them mostly do one thing.