Python - Standard Libraries
unittest
module for writing and running tests.The unittest
module in Python provides a framework for writing and running tests. It follows the xUnit style of test automation and allows you to organize and execute test cases for your code. Let's explore an example using the unittest
module to test a simple function:
import unittest
# Function to be tested
def add(a, b):
return a + b
# Test case class
class TestAddition(unittest.TestCase):
# Test for positive numbers
def test_positive_numbers(self):
result = add(2, 3)
self.assertEqual(result, 5, "Adding 2 and 3 should equal 5")
# Test for negative numbers
def test_negative_numbers(self):
result = add(-2, -3)
self.assertEqual(result, -5, "Adding -2 and -3 should equal -5")
# Test for one positive and one negative number
def test_mixed_numbers(self):
result = add(5, -3)
self.assertEqual(result, 2, "Adding 5 and -3 should equal 2")
# Run the tests
if __name__ == '__main__':
unittest.main()
Output:
... ---------------------------------------------------------------------- Ran 3 tests in 0.000s OK
In this example, we create a simple function add()
that adds two numbers. We then create a test case class TestAddition
that inherits from unittest.TestCase
. Each test method in the class starts with the word test
and contains assertions using methods like assertEqual
.
The last block of code if __name__ == '__main__': unittest.main()
runs the tests when the script is executed directly.
To run the tests, you can execute the script, and it will display the test results. The output shows that all three tests passed successfully, indicated by the "OK" message.
The unittest
module provides various assertion methods and features for test discovery, test fixtures, and test suites, making it a comprehensive testing framework for Python developers.