Automated tests verify your code does what you think — and keep doing it as you change things. Tests are what let you refactor fearlessly. unittest is Python's built-in, batteries-included test framework, modelled on the classic xUnit style.
Tests in a TestCase
Tests are methods named test_* on a TestCase subclass. Each uses assert* methods to check expectations:
import unittestdef add(a, b):return a + bclass TestAdd(unittest.TestCase):def test_positives(self):self.assertEqual(add(2, 3), 5)def test_negatives(self):self.assertEqual(add(-1, -1), -2)def test_type_error(self):with self.assertRaises(TypeError):add(1, "x")if __name__ == "__main__":unittest.main()
Assertions & fixtures
Common assertions: assertEqual, assertTrue, assertIn, assertRaises. Use setUp to build test data before each test and tearDown to clean up after.
Key takeaways
- 01unittest is the built-in xUnit-style test framework.
- 02Tests are test_* methods on a TestCase subclass.
- 03assertEqual/assertTrue/assertIn/assertRaises check expectations.
- 04setUp/tearDown provide per-test fixtures.
- 05Structure tests as Arrange–Act–Assert; automated tests catch regressions.
