Skip to main content

Python's Built-in unittest Framework

Python comes pre-packaged with a complete, enterprise-grade test runner and assertion library called unittest (based on standard xUnit patterns).


1. Structure of a unittest Test File

To write a test suite:

  1. Import unittest.
  2. Import the function you want to test.
  3. Create a class that inherits from unittest.TestCase.
  4. Create test methods whose names must start with test_.
# calculator.py (Code to test)
def add(a, b):
return a + b

def divide(a, b):
if b == 0:
raise ZeroDivisionError("Cannot divide by zero!")
return a / b
# test_calculator.py (The Test File)
import unittest
from calculator import add, divide

class TestCalculator(unittest.TestCase):

def test_add_positive_numbers(self):
result = add(10, 5)
self.assertEqual(result, 15)

def test_add_negative_numbers(self):
result = add(-3, -7)
self.assertEqual(result, -10)

def test_divide_valid(self):
result = divide(10, 2)
self.assertEqual(result, 5.0)

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

2. Running Tests from the Terminal

# Run a specific test file
python test_calculator.py

# Run all test files automatically (Test Discovery)
python -m unittest discover

Understanding the Terminal Output

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

OK
  • Each . (dot) represents a passing test.
  • An F means an assertion Failed.
  • An E means an unhandled Exception crashed your code.

Quick Summary

Assertion MethodChecksExample
self.assertEqual(a, b)a == bself.assertEqual(add(2, 3), 5)
self.assertNotEqual(a, b)a != bself.assertNotEqual(result, 0)
self.assertTrue(x)bool(x) is Trueself.assertTrue(is_logged_in)
self.assertFalse(x)bool(x) is Falseself.assertFalse(is_locked)
self.assertIsNone(x)x is Noneself.assertIsNone(user_found)
self.assertIn(item, list)item in listself.assertIn("Python", skills)
self.assertAlmostEqual(a, b)Floating point matchself.assertAlmostEqual(0.1+0.2, 0.3, places=5)
  • Method Naming: Test method names must start with test_ for automatic test discovery.

What's Next?

Let's learn how to manage database setup, API teardown fixtures, and test exceptions using Writing Test Cases & Test Fixtures (setUp/tearDown)!