Unit Testing in Python — The Basics

Increase the quality, trustworthiness and flexibility of your code base

Martin Thoma
The Startup

--

Image Source: Mohamed Hassan

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 :

--

--

Martin Thoma
The Startup

I’m a Software Engineer with over 10 years of Python experience (Backend/ML/AI). Support me via https://martinthoma.medium.com/membership