What is Python unittest?

Key takeaways:

  • Python’s unittest is a unit testing framework inspired by JUnit that supports test automation, code setup, teardown sharing, aggregation of tests, and independence from reporting frameworks. It ensures the reliability of algorithms and software designs before deployment.

  • Using assertRaises in unittest, developers can validate function behavior by ensuring appropriate exceptions (e.g., ValueError, TypeError) are raised for invalid inputs, such as negative or boolean values, improving code robustness.

  • By testing a sphere volume calculation function, the framework highlights the importance of handling edge cases (like negative or invalid inputs) using test classes and refining the function with conditions to effectively meet test requirements.

Testing algorithms and software designs are one of programming’s key features. The right data for testing will always inform applications of bugs or fixes that need to be incorporated before they are released into the market. This is where Python’s unittest framework comes in.

Unittest

JUnit originally inspired the unittest unit testing framework and is similar to major unit testing frameworks in other languages. Unittest supports test automation, sharing setup and shutdown code for tests, aggregation of tests into collections, and independence of the tests from the reporting framework. Let’s look at an example to better understand the application of the unittest.

Example

Imagine that a software company asks you to design a function that calculates the volume of a sphere given a radius. You may remember from math class that the volume of a sphere is (4/3 * π * r3). This seems pretty easy, so let’s write the code for this problem:

def sphere_volume(radius):
pi = 3.141592653589793
return 4/3 *pi*(radius**3)
r = [1,2.5,3.4,5.6,7,9.0]
for x in r:
print("Volume of sphere with radius = ", x, "is = ", sphere_volume(x))

This is quite good. However, what if I pass a string or boolean value as a radius? Or what would happen if a negative value is passed as one of the radius values? Let’s incorporate the inputs from the code above:

def sphere_volume(radius):
pi = 3.141592653589793
return 4/3 *pi*(radius**3)
r = [1,2.5,3.4,5.6,7,9.0, -2, -5, True, False, "string"]
for x in r:
print("Volume of sphere with radius = ", x, "is = ", sphere_volume(x))

Now we have a testing problem. This function also gives an output on the following values instead of throwing an error:

  1. -2: Radius cannot be a negative value.
  2. -5: Radius cannot be a negative value.
  3. True: Radius cannot be a boolean value.
  4. False: Radius cannot be a boolean value.

Even though the program does not know that the radius is not supposed to be negative, it gave an error when the string value was passed as a radius. However, this case could fail in certain situations, so we must define a unittest class to validate the radius passed. Let’s write a code for the test file:

def sphere_volume(radius):
pi = 3.141592653589793
return 4/3 *pi*(radius**3)
r = [1,2.5,3.4,5.6,7,9.0, True,"string"]
for x in r:
if type(x) not in [int, float]:
raise TypeError("Invalid type")
if x<0:
raise ValueError("Radius Negative")
print("Volume of sphere with radius = ",x, "is",sphere_volume(x))

To run the following code, make sure that both of the files are in the same folder, and then type the following command in the terminal:

python -m unittest test_volume.py

Note: The test_volume.py refers to the name of our test file.

When we run this file, it will give an error for boolean and negative. This error tells us that our test has failed, so we are on the right track. So, we will remove the invalid values. Now, our test gives the correct output, and the tests run OK.

import unittest
from volume import sphere_volume
pi = 3.141592653589793

class TestVolumeSpehere(unittest.TestCase):
    def test_values(self):
        # parameters of assertRaises
        # 1: Type of error
        # 2: Volume caculated by the function
        # 3: The values which should raise the error.
        self.assertRaises(ValueError, sphere_volume, -2)
        self.assertRaises(ValueError, sphere_volume, -5)

    def test_values(self):
        # parameters of assertRaises
        # 1: Type of error
        # 2: Data type Volume caculated by the function
        # 3: The dataType which should raise an error
        self.assertRaises(TypeError, sphere_volume, "string")
        self.assertRaises(TypeError, sphere_volume, bool)

Let’s understand the code:

We defined a unittest class to test our function and learned that it is important to import the unittest library and to define a test class to perform test cases. In our function, we mostly encountered two major problems:

  1. The function was giving output on negative values. In this situation, we call the assertRaises method of our class module, which returns a ValueError if the radius is negative. We have given it examples -2 and -5 for testing purposes. Now, we know this function will raise an error for a negative input. How do we solve it? In the volume.py file, we define an if condition to only calculate the volume if the radius is positive. If not, it will raise a value error. Now, our code is aligned with our first test case.

  2. The function was given output on boolean values. In this situation, we call the assertRaises method of our class module, which returns TypeError if the radius is boolean, string, etc. For testing purposes, we have given it the examples of bool and string as input. Now we know that for invalid input, this function is going to raise an error. So, how do we solve it?

In the volume.py file, we define an if condition to calculate the volume only if the radius data type is either a float value or an int value. If not, this raises a Type error. Our code is also aligned with our second test case.

Ready to write cleaner, more maintainable code? Clean Code in Python guides you through Python fundamentals and advanced techniques, empowering you to create high-quality software with confidence.

Conclusion

In summary, Python’s unittest framework provides a structured and efficient way to test and validate software, ensuring that functions and algorithms behave as expected. Examples like testing the sphere volume calculation function highlight the importance of handling edge cases such as negative values, booleans, and invalid inputs. By incorporating assertRaises and defining proper test cases, we can ensure that our code works under normal conditions and gracefully handles errors and unexpected inputs.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How is Python used in testing?

Python is a versatile programming language used in testing to write scripts that validate the correctness of code. It offers frameworks like unittest, pytest, and nose to automate the testing process, ensuring software behaves as expected under various scenarios.


Why do we need unittest?

Unittest is needed to ensure that individual units of code (like functions or methods) work as intended. It provides automation, setup/teardown sharing, and independent test organization, making it easier to identify bugs and validate software before deployment.


What does a Python unittest assert do?

A Python unittest assert checks whether a condition in a test case holds true. If the condition fails, the test fails, providing feedback about what went wrong. Common assertions include assertEqual to check equality, assertRaises to verify exceptions, and assertTrue to confirm truthfulness. These assertions help validate the correctness of code during testing.


How to test the __init__ method in Python?

You can test the __init__ method in Python using unit tests, typically with a framework like unittest. Here’s a basic example:

import unittest

class MyClass:
    def __init__(self, value):
        self.value = value

class TestMyClass(unittest.TestCase):
    def test_init_sets_value(self):
        obj = MyClass(42)
        self.assertEqual(obj.value, 42)

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

What is integration testing and its type?

Integration testing verifies the interaction between combined software modules, ensuring they work together as expected. It helps identify defects in data flow and communication between components.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved