Posted by Marta on December 18, 2020 Viewed 507 times
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.
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.
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.
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.
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: check_duplicates.py 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!
#Filename: test_check_duplicates.py import unittest from check_duplicates import is_there_duplicates class TestCheckDuplicates(unittest.TestCase): def test1(self): duplicates = is_there_duplicates([1,2,3,4]) self.assertFalse(duplicates) def test2(self): duplicates = is_there_duplicates([1,2,3,1,2]) self.assertTrue(duplicates) def test3(self): duplicates = is_there_duplicates() self.assertFalse(duplicates)
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') self.assertTrue(check_palindome) def test_invalid_case(self): check_palindrome = is_palindrome('Hello there') self.assertFalse(check_palindrome) def test_empty_case(self): check_palindrome = is_palindrome('') self.assertTrue(check_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
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): is_palindrome(3)
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!
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
Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications
Unique lay-out and teaching programming style helping new concepts stick in your memory
Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples
Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.
Excellent read for anyone who already know how to program and want to learn Best Practices
Perfect book for anyone transitioning into the mid/mid-senior developer level
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