Unit tests with Python
Posted on December 13, 2021 by Adrian Wyssmann ‐ 3 min read
In my previous post I gave an introduction to unit testing with Java. As personally I use Python, hence I give you a quick intro into unit testing with Python
As we know now, we need a unit test framework to do unit testing. If we have a look at Python, it comes with a unittest framework included:
The unittest unit testing framework was originally inspired by JUnit and has a similar flavor as major unit testing frameworks in other languages.
It offers the concepts I discussed here:
- test fixture - well, provide text fixture
- test case - the individual unit of testing
- test suite - a collection of test cases, test suites, or both
- test runner - the component which orchestrates the execution of tests and provides the outcome to the user
Let’s say we have a script example.py
with the following content:
We would create a test case which tests the different path of simpleFunction
. We call the file test_example.py
as follows
Some things which you need to know
- a test class is usually
test_classname.py
- don’t use a.
i.eclassname.test.py
as this will result in an error when executing the tests - it must import
unittest
as well as test object - in this caseexample
- a test classis subclassing
unittest.TestCase
. - the name of the test class does not matter, but the test functions have to be prefixed with
test_
- otherwise the functions will not be considered test cases - call
unittest.main()
when__name__ == '__main__
- this provides a command-line interface to the test script
You can call now the unit tests from the command line - we use -v
to see the name of the test cases:
If you have multiple files, you can also test discovery, which automatically detects tests.
Or
It also offers setUp()
and tearDown()
methods, which will be executed before and after each test method.
You also can skip tests using the skip()
-decorator or raise skipTest
. Here an example of the official documentation:
If you want to group test cases together, you can build TestSuites
You can run this as follows:
Another interesting feature is SubTests
, which allows you to distinguish small differences for some parameters, using the same test method.
I recommend to read organize test code to better understand how you should organize your test code.
When writing code, it’s important you understand unit testing and the framework, the language of your choice offers. Whether it’s unittest for Python or JUnit for Java, they support the same important concepts, even so they differ in syntax.