Open In App

Python Unittest Tutorial | Unit Testing in Python using unittest Framework

Last Updated : 22 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Unit Testing is the first level of software testing where the smallest testable parts of software are tested. This is used to validate that each software unit performs as designed. The unittest test framework is Python xUnit style framework. In this article, we will learn about unittest framework with the help of examples.

What is Python Unittest?

Python Unittest is a built-in testing framework that provides a set of tools for testing our code’s functionality in a more systematic and organized manner. With unittest framework, we can create test cases, fixtures, and suites to verify if our code behaves as expected. It allows us to write test methods within classes that check different aspects of our code such as input, output, and edge cases. It also supports test discovery making it easy for us to automate test execution across our project.

Why Choose Unittest in Python?

Developers often choose Python’s unittest framework for its built-in nature, widespread familiarity, comprehensive features, seamless integration with other tools, and proven reliability. As part of Python’s standard library, unittest requires no additional installations, making it easily accessible. Unit tests promote consistency in testing practices, aiding collaboration and maintenance. While other frameworks like Pytest and nose offer alternatives, unittest remains a popular choice for its stability and versatility.

Assert Methods in Python Unittest Framework

unittest has lots of methods to assert on the values, types, and existence of variables. Below are some of the methods that are commonly used to write assertions.

Method

Description

.assertEqual(a, b)

Checks if a is equal to b, similar to the expression a == b.

.assertTrue(x)

Asserts that the boolean value of x is True, equivalent to bool(x) is True.

.assertIsInstance(a, b)

Asserts that a is an instance of class b, similar to the expression isinstance(a, b).

.assertIsNone(x)

Ensures that x is None, similar to the expression x is None.

.assertFalse(x)

Asserts that the boolean value of x is False, similar to bool(x) is False.

.assertIs(a, b)

Verifies if a is identical to b, akin to the expression a is b.

.assertIn(a, b)

Checks if a is a member of b, akin to the expression a in b.

OOP Concepts Supported by Unittest Framework

The White Box Testing method is used for Unit tests. Below are some of supported oops concept by Unitttest framework:

  • test fixture: A test fixture is used as a baseline for running tests to ensure that there is a fixed environment in which tests are run so that results are repeatable. Examples :
    • creating temporary databases.
    • starting a server process.
  • test case: A test case is a set of conditions which is used to determine whether a system under test works correctly.
  • test suite: Test suite is a collection of testcases that are used to test a software program to show that it has some specified set of behaviours by executing the aggregated tests together.
  • test runner: A test runner is a component which set up the execution of tests and provides the outcome to the user.

Python Unittest Example

Now, we will implement the unit test using Python Unittest framework.

Example 1: test.py

Here, we will write a a simple function named add() that takes two numbers and returns their sum. Additionally, it includes a test case class TestAddFunction that inherits from unittest.TestCase. Within this class, three test methods are defined to verify different scenarios of the add() function.

Python3
import unittest

def add(a, b):
    return a + b

class TestAddFunction(unittest.TestCase):
    def test_add_positive_numbers(self):
        self.assertEqual(add(1, 2), 3)

    def test_add_negative_numbers(self):
        self.assertEqual(add(-1, -2), -3)

    def test_add_mixed_numbers(self):
        self.assertEqual(add(1, -2), -1)
        self.assertEqual(add(-1, 2), 1)

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

This is the basic test code using unittest framework, which is having a single test. This test() method will fail if TRUE is ever FALSE.

Now, we will see how to run Unittest file in Python. To run the unit tests, run the following command in your terminal:

python test.py

Output:

...
----------------------------------------------------------------------
Ran 3 tests in 0.001s

OK

For instance, if we change the expected value from 3 to, let’s say, 2 in the test_add_positive_numbers, the test would fail and we’d have this output.

Output:

..F
======================================================================
FAIL: test_add_positive_numbers (__main__.TestAddFunction)
----------------------------------------------------------------------
Traceback (most recent call last):
File "f:\GeeksforGeeks\example_package\main.py", line 8, in test_add_positive_numbers
self.assertEqual(add(1, 2), 2)
AssertionError: 3 != 2

----------------------------------------------------------------------
Ran 3 tests in 0.001s

FAILED (failures=1)

Here, in the output the “.” on the first line of output means that a test passed. “-v” option is added in the command line while running the tests to obtain more detailed test results.

Command:

python test.py -v

Output:

test_add_mixed_numbers (__main__.TestAddFunction) ... ok
test_add_negative_numbers (__main__.TestAddFunction) ... ok
test_add_positive_numbers (__main__.TestAddFunction) ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.002s

OK

Outcomes Possible in Unit Testing

There are three types of possible test outcomes :

  • OK – This means that all the tests are passed.
  • FAIL – This means that the test did not pass and an AssertionError exception is raised.
  • ERROR – This means that the test raises an exception other than AssertionError.

Let’s walk through an another example to understand the implementation of unittest framework.

Example 2

Python3
import unittest

class TestStringMethods(unittest.TestCase):

    def setUp(self):
        pass

    # Returns True if the string contains 4 a.
    def test_strings_a(self):
        self.assertEqual('a'*4, 'aaaa')

    # Returns True if the string is in upper case.
    def test_upper(self):
        self.assertEqual('foo'.upper(), 'FOO')

    def test_isupper(self):
        self.assertTrue('FOO'.isupper())
        self.assertFalse('Foo'.isupper())

    def test_strip(self):
        s = 'geeksforgeeks'
        self.assertEqual(s.strip('geek'), 'sforgeeks')

    # Returns true if the string splits and matches
    # the given output.
    def test_split(self):
        s = 'hello world'
        self.assertEqual(s.split(), ['hello', 'world'])
        with self.assertRaises(TypeError):
            s.split(2)

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

unittest.TestCase is used to create test cases by subclassing it. The last block of the code at the bottom allows us to run all the tests just by running the file. Basic terms used in the code :

  1. assertEqual() – This statement is used to check if the result obtained is equal to the expected result.
  2. assertTrue() / assertFalse() – This statement is used to verify if a given statement is true or false.
  3. assertRaises() – This statement is used to raise a specific exception.

Description of Tests

  1. test_strings_a(): This test is used to test the property of string in which a character say ‘a’ multiplied by a number say ‘x’ gives the output as x times ‘a’. The assertEqual() statement returns true in this case if the result matches the given output.
  2. test_upper(): This test is used to check if the given string is converted to uppercase or not. The assertEqual() statement returns true if the string returned is in uppercase.
  3. test_isupper(): This test is used to test the property of string which returns TRUE if the string is in uppercase else returns False. The assertTrue() / assertFalse() statement is used for this verification.
  4. test_strip(): This test is used to check if all chars passed in the function have been stripped from the string. The assertEqual() statement returns true if the string is stripped and matches the given output.
  5. test_split(): This test is used to check the split function of the string which splits the string through the argument passed in the function and returns the result as list. The assertEqual() statement returns true in this case if the result matches the given output.

unittest.main() provides a command-line interface to the test script. On running the above script from the command line, following output is produced:

.....
----------------------------------------------------------------------
Ran 5 tests in 0.000s

OK

FAQs

Difference between Unitest and Pytest?

Unittest is Python’s built-in testing framework, following the xUnit style. It relies on classes and methods for organizing tests and assertions for validation while Pytest is a third-party testing framework that offers a more concise syntax, powerful fixtures, and advanced features like parameterized testing and plugin support. Pytest is often favored for its simplicity and flexibility, making it easier to write and maintain tests.

Where to Put Python Unit Test file?

In Python, unit test files are usually placed next to the module or package they’re testing. They often start with test_ in their names, like test_module.py or test_package/. This setup makes tests easy to find and integrates smoothly with testing frameworks like unittest or Pytest, which can automatically locate and run them.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads