Let's talk about Unittests

Introduction

Unit testing is a crucial aspect of software development that ensures the individual components of your code work as expected. It allows developers to identify bugs early, maintain code reliability, and facilitate smooth code integration.

What is unit testing?

Let's say you want to buy a car you go to the dealer and the salesperson shows you the cars available and you even allow yourself to test drive one of the cars. This helps you in making decisions. This is the same case that exactly happens when we write a program. We first write tests for our program, then write the program and see if it works. That's the definition of unit tests for programmers it is continuous and important in development and never stops. We also call it Test driven development.

Now let's see exactly what's about this unit testing in python

Python is a popular programming language that is used in a wide range of applications, including web development, data analysis, and machine learning. As with any programming language, testing is a critical aspect of the development process. One approach to testing in Python is to use the built-in unit test module. Let me introduce you to the unit test module and explain why it is important, as well as provide an example of how we need to do a unit test using a basic example. But first, let's understand why we need to do the unit test.

Why do we need unit tests?

The main reason for doing a unit test is to ensure that your code works as expected and helps catch bugs before they cause problems.

By running the tests after making changes, you can ensure that the code still works as expected. We do this by importing unit test modules in our code. More reasons are;

  1. Early Bug Detection

    Unit tests help catch bugs in the early stages of development, reducing the cost and effort required for debugging later.

  2. Code Refactoring

    They provide a safety net for refactoring your code. If the unit tests pass after making changes, you can be confident that you didn't break existing functionality.

  3. Documentation

    Unit tests serve as executable documentation, explaining how various parts of your code should work.

  4. Continuous Integration

    Automated unit tests are essential for continuous integration and continuous deployment (CI/CD) pipelines.

Example

In the example below we are using a simple Python program that is calculating the area of a rectangle. Let's use a function called calculate_area.

def calculate_area(length, width):
    area = length * width 
    return area

Now let's write unit tests to test our program above remember to call the program in your test. You can save the program above in a file let's call it an area.py file

from area import calculate_area
import unittest

class TestCalculateArea(unittest.TestCase):

    def setUp(self):

        self.length = 5

        self.width = 10

    def tearDown(self):

        pass

    def test_calculate_area(self):
        expected_result = 50
        actual_result = calculate_area(self.length, self.width)
        self.assertEqual(expected_result, actual_result)

if __name__ == '__main__':

    unittest.main()

Explanation

Let me explain how the code above works

  • We first import the unit test module, which provides the framework for writing unit tests.

  • We then define a test case class called TestCalculateArea. This class inherits from the unit test TestCase class, which provides several useful assertion methods for testing.

  • Inside the TestCalculateArea class, we define a test method called test_calculate_area. This method sets the length and width variables to 5 and 10, respectively, and sets the expected_result variable to 50. It then calls the calculate_area function with the length and width arguments and stores the result in actual_result.

  • Finally, we use the self.assertEqual method to compare the expected_result and actual_result variables. This method checks that the two variables are equal and raises an AssertionError if they are not.

NB : The Setup and tearDown methods are special methods provided by the unit test.TestCase class allows you to set up and tear down resources that are needed for your test cases. The the setUp method is called before each test case is run, while the tearDown method is called after each test case is run. These methods are useful for initializing variables, opening files or database connections, or any other setup that is needed for your tests.

You can go ahead and save the file in a Python script and run it on your terminal. The unit test module will automatically discover and run any test cases defined in the script.

If your test is successful your results will be ok or successful otherwise you will see results failed. And an error message telling you what happens and how to fix it.

Same case on the example I used above when you go to a car dealer and he offers you a car to test drive, after the test drive you will be able to give feedback if you enjoyed the drive or not. I hope this now helps you understand that testing your program will save you a whole lot of time to discover the mistakes you make before implementing it. Below are resources I used that helped me understand this concept. I the references section. I hope they can help you too.

If you would like to connect with me, do send me DM on my Twitter @myrajarenga, I would love to hear from you if you enjoyed reading it as I enjoyed writing it. Thank you for your time. You can also support me by following me on this blog here Myra Jarenga's Blog .

References

https://realpython.com/python-testing/

https://youtu.be/6tNS--WetLI