Unit Testing with Python unittest

Introduction

In this article, we will go through how to use the Python unittest module to do unit testing on your code. First, let’s define the various forms of testing.

There are two types of testing

  1. Manual testing: Manual testing is a testing approach in which people do the test manually after the development is completed.
  2. Automated testing: Automation testing is a testing technique where programs perform the test automatically and give the results to us.

You would have realized that manual testing takes time and is difficult to complete. As a result, engineers create code to run tests (automatic testing). There are several types of testing in automated testing. Some examples are unit testing, integrating testing, end-to-end testing, stress testing, and so on.

Let’s see the standard flow of testing:

  • Write or Update the code.
  • Write or Update tests for different cases for your code.
  • Run the tests (either manually or using a test runner).
  • See the test results. If there are any errors, fix them and repeat the steps.

In this article, we will go through the most fundamental and simplest sort of testing, known as unit testing. Without further delay, let’s get started with the tutorial.

What is Unit Testing?

Unit test is a technique of testing a tiny chunk of independent code. In most circumstances, the small-block code will be a function. The term “independent” refers to the fact that it is not dependent on other pieces of code in the project.

Assume we need to determine whether a string is equal to “Softhunt” or not. For this, we wrote a function that accepts one input and returns whether or not it is equal to “Softhunt.”

def is_equal_to_softhunt(string):
	return string == "Softhunt"

The above function is not dependent on any other code. As a result, we may test it independently by providing alternative inputs. A single piece of code may be used throughout the project.

What is Python unittest?

Python unittest is a testing framework integrated into Python that allows you to test your programs. It includes a test runner, which allows us to execute the tests quickly. As a result, we can test using the built-in unittest module rather than using third-party modules. However, it varies depending on your needs. To get started with testing in Python, use the built-in unittest module.

To test the Python code with the unittest module, we must follow the procedures given below.

  • Write the code
  • Import the unittest module.
  • Create a file starting with the keyword test. For example test_softhunt.py. The keyword test is used to identify the test files.
  • Create a class extending the class unittest.TestCase.
  • Inside the class, write methods (tests). Depending on your needs, each technique includes a distinct set of test cases. The method’s name must begin with the keyword test.
  • Run the tests. We can run the tests in different ways.
    • Run the command python -m unittest test_filename.py
    • We execute the test files with the command python test filename.py, just like any other Python file. To make this technique work, we must call the main method of the unittest in the test file.
    • Finally, use the discover. We may run the tests automatically by typing python -m unittest discover without specifying the test’s filename. It will discover the tests based on the naming convention we used. As a result, we must begin by naming our test files with the keyword test.

In general, during testing, we compare the code’s output to the expected output. As a result, unittest provides many techniques for comparing outcomes.

Coding Activity of Python Unittest

We’ll start by building some functions, and then we’ll go on to writing tests. To begin, open a folder in your preferred code editor. Also, make a file named utils.py. Copy and paste the following code into the file.

import math


def is_prime(n):
    if n < 0:
        return 'Negative numbers are not allowed'

    if n <= 1:
        return False

    if n == 2:
        return True

    if n % 2 == 0:
        return False

    for i in range(2, int(math.sqrt(n)) + 1):
        if n % i == 0:
            return False
    return True


def cubic(a):
    return a * a * a


def say_hello(name):
    return "Hello, " + name

In the utils.py file, we have three separate functions. Now we must test each function with a new set of test scenarios. Let’s start with the first function, is_prime.

  • Create a file called test_utils.py in the sample folder as utils.py.
  • Import the utils and unittest module.
  • Create a class with the name TestUtils extending unittest.TestCase class. The name of the class can be anything. Try to give the class a meaningful name.
  • Inside the class, write a method called test_is_prime which accepts self as an argument.
  • Write different test cases with arguments to the is_prime and compare the output with the expected output.
  • Example test case self.assertFalse(utils.is_prime(1)).
  • We are expecting the output of the is_prime(1) will be false in the above case.
  • Similar to the above case, we will different tests cases based on the function we are testing.
import unittest

import utils


class TestUtils(unittest.TestCase):
    def test_is_prime(self):
        self.assertFalse(utils.is_prime(4))
        self.assertTrue(utils.is_prime(2))
        self.assertTrue(utils.is_prime(3))
        self.assertFalse(utils.is_prime(8))
        self.assertFalse(utils.is_prime(10))
        self.assertTrue(utils.is_prime(7))
        self.assertEqual(utils.is_prime(-3),
                         "Negative numbers are not allowed")


if __name__ == '__main__':
    unittest.main()


Using the command python filename.py, we call the main function of the unittest module to execute the tests. Run the tests now.

Output:

$ python test_utils.py 
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK

Now try the remaining functions one by one.

Conclusion

That’s all for this article, if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn

Suggested Articles:

  1. Python Dictionary [With Examples]

Leave a Comment