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:
- Import
unittest. - Import the function you want to test.
- Create a class that inherits from
unittest.TestCase. - 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
Fmeans an assertion Failed. - An
Emeans an unhandled Exception crashed your code.
Quick Summary
| Assertion Method | Checks | Example |
|---|---|---|
self.assertEqual(a, b) | a == b | self.assertEqual(add(2, 3), 5) |
self.assertNotEqual(a, b) | a != b | self.assertNotEqual(result, 0) |
self.assertTrue(x) | bool(x) is True | self.assertTrue(is_logged_in) |
self.assertFalse(x) | bool(x) is False | self.assertFalse(is_locked) |
self.assertIsNone(x) | x is None | self.assertIsNone(user_found) |
self.assertIn(item, list) | item in list | self.assertIn("Python", skills) |
self.assertAlmostEqual(a, b) | Floating point match | self.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)!