Write good Python tests

submited by
Style Pass
2024-11-16 16:00:02

Python testing practices aimed at producing maintainable code bases with test suites that are understandable, brings confidence to the correctness of the program, and that in general optimizes for smooth future interactions with your code.

This article lists rules to follow to achieve the above-mentioned properties, focusing on how to write good unit tests. There are generally plenty more aspects to take into account, such as using static type checking, and complementing unit tests with integrated testing. Those are aspects that are not within the scope of this article.

Write test names that do not describe the input to the unit under test, instead, write test names that describe the expected outcome of the test.

The reason for this is that it much better communicates the original intent of the author of the test. If there is a bug in the code, being met with a name that clearly communicates what the original author expected the code to do, can immensely help in quickly understanding what the correct fix is.

As a logical consequence of following this rule, you are forced to introduce at least a certain number of distinct test functions given the behavior of a unit under test. If the unit has behavior such that it has two distinct expected outcomes, you write those as two distinct test functions and so on.

Leave a Comment