Unit testing in Python
Understanding the what’s and how’s of testing your Python code
It is important to test your Python code as this will help you make changes or update the code to make sure the program is running correctly. There are several testing tools but the most popular are:
1.unittest
This built-in library allows the testing of programs and checks if the desired output is generated. It also allows you to write your own test program.
To understand how this works, we will create two python scripts namely ‘main_script.py” and “test_script.py”. The main_script.py will define the function which inputs a string and output the upper case of the string.
The test_script.py will test this function. So in this file we will import unittest and the main_script. Then define a class where a method is defined for testing the result.
Now let’s run the test code and there is no error raised at all.
2. pylint
This is a library that scans through the code and reports back with issues if any. It also checks for styling. By style, it means that Python has a set of style convention rules known as “PEP 8".
So let’s install the library by typing this command in your command prompt:
pip install pylint
Now we will create a python file where we deliberately make a mistake while calling the print function as seen below. Here print(num3) is called whereas num2 should have been called. There is no variable num3.
Now we will check for error using pylint. Go to the directory where the python file is saved and run the command below.
Look at the yellow highlighted line, its written as “E0602” where E means the error and we need to look out for this. And it says num3 is undefined noting that we called the wrong variable for printing. Also see the score is in negative which is worse.
Now let's try to clean the code by adding docstring, newline and fixing the names of variables as mentioned in the output and try to get a better score.
The score for this script is as follows:
Refer to the notebook here.
Beginner-level books to refer to learn Python:
Advance-level books to refer to learn Python:
Reach out to me: LinkedIn
Check out my other work: GitHub