Unit Testing in Python — The Basics
Increase the quality, trustworthiness and flexibility of your code base
--
Unit testing is the number one skill which separates people who just finished their degrees from people with practical experience. Especially for Python, that’s a shame as it is trivial to learn this skill.
In this article, you will learn how to write and run unit tests in Python as well as some interesting pytest plugins I usually use. Let’s get started.
The most basic Unit Test
A unit test is atomic- it just tests one unit of code. Typically one function or one method of a class. As an example, let’s say we want to test math_functions.py
which contains the Fibonacci function and a function for the Collatz sequence:
We want to test this function. I will explain the reasons for testing and what testing means later. For now, let’s just say we want to avoid programming errors.
First, create a file test_math_functions.py
:
Now, you have to install pytest:
$ pip install pytest
And run it:
$ pytest
============ test session starts ===================================
platform linux -- Python 3.8.1, pytest-5.4.3, py-1.9.0, pluggy-0.13.1
rootdir: /home/moose/GitHub/MartinThoma/algorithms/medium/unit-testing
collected 5 itemstest_math_functions.py ..... [100%]============ 5 passed in 0.03s =====================================
Awesome! You can see that it took 0.03 seconds to execute. There are 5 dots after the test_math_functions.py
. Those indicate that 5 tests were executed and…