How do I test a Python program or component?

Testing is essential for ensuring your Python code works correctly. Python provides built-in testing modules like unittest and doctest, along with support for third-party frameworks to create comprehensive test suites.

The doctest Module

The doctest module searches for pieces of text that look like interactive Python sessions in docstrings, then executes those sessions to verify they work as shown ?

def add_numbers(a, b):
    """
    Add two numbers and return the result.
    
    >>> add_numbers(2, 3)
    5
    >>> add_numbers(-1, 1)
    0
    """
    return a + b

if __name__ == "__main__":
    import doctest
    doctest.testmod()
Test passed quietly (no output means success)

The unittest Module

The unittest module supports test automation, sharing of setup and shutdown code for tests, aggregation of tests into collections, and independence of the tests from the reporting framework.

Key Testing Concepts

  • Test fixture Preparation needed to perform tests and any associated cleanup actions

  • Test case Individual unit of testing that checks for a specific response to particular inputs

  • Test suite Collection of test cases or test suites to be executed together

  • Test runner Component that orchestrates test execution and provides results to the user

Creating Unit Tests

Here's how to create a comprehensive test class using unittest ?

import unittest

class TestStringMethods(unittest.TestCase):
    
    def test_lower(self):
        self.assertEqual('AMIT'.lower(), 'amit')
    
    def test_islower(self):
        self.assertTrue('amit'.islower())
        self.assertFalse('Amit'.islower())
    
    def test_split(self):
        text = 'Demo Text'
        self.assertEqual(text.split(), ['Demo', 'Text'])
        # Test that split fails when separator is not a string
        with self.assertRaises(TypeError):
            text.split(2)
    
    def test_upper(self):
        self.assertEqual('hello'.upper(), 'HELLO')

if __name__ == '__main__':
    unittest.main()
....
----------------------------------------------------------------------
Ran 4 tests in 0.001s

OK

Common Assertion Methods

Method Checks That Example
assertEqual(a, b) a == b assertEqual(2+2, 4)
assertTrue(x) bool(x) is True assertTrue('hello'.islower())
assertRaises(exc, fun, *args) fun(*args) raises exc assertRaises(ValueError, int, 'abc')

Testing with Setup and Teardown

Use setUp() and tearDown() methods for test preparation and cleanup ?

import unittest

class TestListOperations(unittest.TestCase):
    
    def setUp(self):
        """Called before each test method"""
        self.test_list = [1, 2, 3, 4, 5]
    
    def tearDown(self):
        """Called after each test method"""
        self.test_list = None
    
    def test_append(self):
        self.test_list.append(6)
        self.assertEqual(len(self.test_list), 6)
        self.assertEqual(self.test_list[-1], 6)
    
    def test_remove(self):
        self.test_list.remove(3)
        self.assertEqual(len(self.test_list), 4)
        self.assertNotIn(3, self.test_list)

if __name__ == '__main__':
    unittest.main()
..
----------------------------------------------------------------------
Ran 2 tests in 0.001s

OK

Conclusion

Use unittest for comprehensive test suites with setup/teardown capabilities. Use doctest for simple tests embedded in docstrings. Both approaches help ensure code reliability and maintainability.

Updated on: 2026-03-26T21:52:27+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements