unittest: TestCase, Assertions & Fixtures
unittest is Python's built-in testing framework, part of the standard library -- no installation required. It follows the xUnit style pioneered by JUnit: tests grouped into classes, with setup/teardown lifecycle hooks and a rich family of assert* methods.
Writing a TestCase
import unittest
class TestMathUtils(unittest.TestCase):
def test_addition(self):
self.assertEqual(2 + 2, 4)
def test_division_by_zero_raises(self):
with self.assertRaises(ZeroDivisionError):
1 / 0
def test_string_contains(self):
self.assertIn('py', 'python')
if __name__ == '__main__':
unittest.main()Only methods whose names start with test are picked up as tests. assertEqual, assertIn, assertRaises, etc. produce detailed failure output automatically -- meaningfully better than a bare assert statement, which gives no context on failure.
setUp & tearDown: Per-Test Fixtures
import tempfile
import shutil
class TestFileProcessor(unittest.TestCase):
def setUp(self):
# Runs before EACH test method -- guarantees fresh, isolated state
self.temp_dir = tempfile.mkdtemp()
def tearDown(self):
# Runs after EACH test method, even if it raised an exception --
# reliable cleanup regardless of pass/fail
shutil.rmtree(self.temp_dir)
def test_writes_output_file(self):
result_path = process_file('input.txt', self.temp_dir)
self.assertTrue(result_path.endswith('.out'))setUpClass: Shared, Expensive Setup
class TestUserRepository(unittest.TestCase):
@classmethod
def setUpClass(cls):
# Runs ONCE for the whole class -- for setup genuinely safe to
# share across tests, like an expensive DB connection
cls.db = connect_to_test_db()
@classmethod
def tearDownClass(cls):
cls.db.close()
def test_user_lookup(self):
user = self.db.find_user('alice')
self.assertIsInstance(user, dict)Common Assertion Methods
assertEqual(a, b) / assertNotEqual(a, b) -- value equality, with a detailed diff on failure.
assertTrue(x) / assertFalse(x) -- truthiness checks.
assertIn(item, container) / assertNotIn(item, container) -- membership.
assertIsInstance(obj, cls) -- type checking.
assertAlmostEqual(a, b) -- floating-point comparison within a tolerance, since 0.1 + 0.2 == 0.3 is False due to floating-point representation.
assertRaises(ExceptionType) -- used as a context manager to assert an exception is raised.
Keep your own version of these notes — editable, searchable, and organised by your stack.
Start free