Last Updated : 22 Apr, 2024
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 Frameworkunittest 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
.
The White Box Testing method is used for Unit tests. Below are some of supported oops concept by Unitttest framework:
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.
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.001sOK
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.001sFAILED (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) ... okOutcomes Possible in Unit Testing
test_add_negative_numbers (__main__.TestAddFunction) ... ok
test_add_positive_numbers (__main__.TestAddFunction) ... ok----------------------------------------------------------------------
Ran 3 tests in 0.002sOK
There are three types of possible test outcomes :
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 :
Description of Tests
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.000sOK
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4