This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 8: Unit testing

Other testing libraries

face Josiah Wang

unittest is a useful module for easier automated unit testing. It is also part of the Python Standard Library, so there is no need to install it separately.

It has other useful features like being able to skip tests and to manually load tests. I will not cover all these, but you may read the official documentation for the unittest module to find out more when needed.

The reason I am not spending more time discussing unittest is because most software developers nowadays prefer to use an external package called pytest, which further simplifies whatever unittest has to offer.

For example, you do not have to create a TestCase class, but only need to list out functions like what we had before we started with unittest (!) And rather than trying to figure out which of TestCase‘s assert() methods to use, you will use Python’s general assert statements AND still get detailed information about any assertion errors (!)

I decided it is better for you to get a clearer understanding of these unit testing ideas first (like what test fixtures are in a traditional sense). Then you can appreciate packages like pytest better once you use them! Also, unittest is more object-oriented than pytest, and more importantly comes with Python!

You can now go ahead and explore pytest if you like, and use it to your heart’s content! You have my permission! And yes, you will have to pick it up on your own, I’m afraid! (It is not essential to our course)

doctest

Also, a quick mention of another module from the Python Standard Library called doctest. The idea is that since you have to write your docstrings, you might as well write tests directly inside the docstrings itself! Take a look at the documentation to get an idea! Again, I will not discuss this in any more detail.