Python Unit Testing Frameworks with examples

Posted by Marta on December 18, 2020 Viewed 2125 times

Card image cap

In this article you will learn what unit testing is exactly, why it is important to write unit tests and the most popular python unit testing frameworks with some examples.

Have you seen developers that seem to know what their code will do in every single case? They cover everything, every single scenario, how do they do it? Are they incredibly smart? Well, possibly, and they write code that check if their code works. Code to test code. Also known as unit testing.

What is unit testing?

Let’s say you are writing code, at some point you ask yourself, does this code work? That’s exactly the question that unit testing will answer.

Unit Testing basically means writing a piece of code that will check that the class or function you wrote works as it is supposed to. Given some specific parameters or inputs, unit tests ensure the your code returns the correct and expected output.

For instance let’s say you write a function in python that, given a list of numbers, will check if there are duplicates in the list, returning false if there are no duplicates and true if duplicates were found. If you like to unit test that function you can write some code that call your function, get the result and then check that the result is correct.

Why should you write unit test? 

Here are some reasons why I find unit testing. Based on my experience as a software developer, I think It is useful for any beginner software developer to start unit testing with python or any language as soon as possible.

  • Prepare for interview : Unit testing is not something optional anymore. As a software engineer, any company would expect you to be familiar with creating unit tests and testing your code as you write it.
  • Increase the quality of your code: Unit test will improve the quality of your code since it forces you to think about different test cases, edge cases, and basically experiment with your code and see how it behaves with different parameters. After writing a unit test you will know if your code is working as you want it to work.
  • Save time: The best thing about unit test is that once you write it and get it working, you can run it over and over, no more manual testing required. This will save you a huge amount of time. In case you make a changes in your code later on, you can just run the unit test to check that everything is still working as expected.
  • Your code will be easier to use: You could think of unit tests as the instructions about how to use your code. The unit test states how the code behaves when you provide different parameters.
  • Better design: Another benefit is that it usually leads to better designs, which is not the main goal of a unit test, however it’s a nice side effect.
  • Keep the growth of your project steady: When you start writing code for a project, things tend to move quickly. You keep adding code and testing it. As the project grow, you got more and more code to maintain, and more bugs will start popping out. Therefore adding new features become more costly. Unit test help you to keep this under control.

Unit Testing Frameworks: Unittest & PyTest

There are different libraries in python unit testing frameworks that will provide you the functionality to write unit test: unittest, pytest, and a few more. I will use unittest and pytest in this post, however feel free to experiment with the others 🙂

Unittest is a build in library, in other words,  you don’t need to install it. It was installed when you installed Python. 

In this example, I will use the exercise mentioned above, a function that check if there are duplicates in a list of numbers

#File name: 
def is_there_duplicates(list): 
   return len(list) != len(set(list))

Does this code works? Will it work if I pass an empty list? Let’s do some unit testing with python to answer that question! 

import unittest 
from check_duplicates import is_there_duplicates 

class TestCheckDuplicates(unittest.TestCase): 
   def test1(self): 
      duplicates = is_there_duplicates([1,2,3,4]) 
   def test2(self): 
      duplicates = is_there_duplicates([1,2,3,1,2]) 

   def test3(self): 
       duplicates = is_there_duplicates([]) 

Unittest example

Another sample unit test. Let’s say that we will like to check if a text is a palindrome. Palindrome means its reverse is same as the original text. So I will write the following code:

def is_palindrome(text):
    reversed_text = text[::-1]
    return text == reversed_text

After seen that code, the first question is, does this code actually work? What does it do if I pass in an empty string? what if I pass a number? All those are things to need to consider when writing code. Writing a unit test will help you to understand how your code behave with different inputs.

from palindrome import is_palindrome
import unittest

class TestPalindrome(unittest.TestCase):
    def test_valid_case(self):
        check_palindome = is_palindrome('dad')

    def test_invalid_case(self):
        check_palindrome = is_palindrome('Hello there')

    def test_empty_case(self):
        check_palindrome = is_palindrome('')

    def test_number_case(self):
        self.assertRaises(TypeError, is_palindrome, 3)

Note that all method names should be prefixed with the word test, for the unittest module to recognise them as tests and run them

Pytest example

There are different unit test libraries available, another quite well known unit test library is pytest. Let’s see how to translate the tests above to pytest:

from palindrome import is_palindrome
import pytest

def test_valid_case():
    assert is_palindrome('dad') == True

def test_invalid_case():
    assert is_palindrome('Hello there') == False

def test_empty_case():
    assert is_palindrome('') == True

def test_number_case():
    with pytest.raises(TypeError):

You can run these tests from you terminal using the command:


Note for this command to work, you will need to install the pytest module using pip.

Perfect! The tests passed! So I just confirmed that my code works. The more code you create and integrate, the more important unit test is to make sure all pieces work as expected. Knowing the python unit testing frameworks available and writing unit testing will save you a lot of time when writing code. Plus you will gain confidence in your code, and even more important, your programming skills!

What’s next?

Make your code more readable using object oriented programming

Fun python projects to work on

Is your code as fast as it can be? Find out using Big O Notation

Hope you enjoyed this article and you are now considering start writing unit test for your new code 

If you like the article and you would like to be notified when I publish more articles about how to become a software developer and how to improve your skills, feel free to subscribe

Project-Based Programming Introduction

Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications

100% Recommended book for Java Beginners

Unique lay-out and teaching programming style helping new concepts stick in your memory

90 Specific Ways to Write Better Python

Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples

Grow Your Java skills as a developer

Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.

Write Code as a Professional Developer

Excellent read for anyone who already know how to program and want to learn Best Practices

Every Developer should read this

Perfect book for anyone transitioning into the mid/mid-senior developer level

Great preparation for interviews

Great book and probably the best way to practice for interview. Some really good information on how to perform an interview. Code Example in Java