unittest
unittest is the standard-library xUnit framework: you subclass TestCase, write methods named test_*, and assert with self.assertEqual and friends. python -m unittest discovers and runs them.
Detailed Explanation
unittest arrived with Python 2.1 and is still the builtin option. A test class inherits unittest.TestCase. Each test_... method is a test. setUp / tearDown run around each method. setUpClass / tearDownClass run once around the class. subTest parameterises a loop without stopping at the first failure.
Assertions are methods: assertEqual, assertIn, assertRaises (as a context manager), assertAlmostEqual for floats, assertCountEqual for bags. A plain assert works but reports less detail. assertRaises is the right way to check exceptions; a manual try that forgets to fail() can pass.
Discovery: python -m unittest discover -s tests. File names test_*.py, class names Test*, methods test_*. You can run one test with python -m unittest tests.test_order.TestOrder.test_total.
unittest is verbose next to pytest. Teams still use it because it is in the stdlib, because they extend Django's SimpleTestCase, or because they cannot add a dependency. Pytest can run TestCase subclasses, so a mixed suite is possible.
Mocks live in unittest.mock. Skip with @unittest.skip, @skipIf, @expectedFailure. Loaders and runners can be replaced; you rarely need to.
Keep tests independent. Shared setUp state that one test mutates will flake the next. Prefer local arrangement inside the method when the setup is three lines.
Code Examples
import unittest
class TestCents(unittest.TestCase):
def test_positive(self):
self.assertEqual(2500 // 100, 25)
def test_raises(self):
with self.assertRaises(ZeroDivisionError):
1 // 0
if __name__ == "__main__":
unittest.main()class TestRows(unittest.TestCase):
def test_each_sku(self):
for sku in ("A-1", "B-2"):
with self.subTest(sku=sku):
self.assertTrue(sku.startswith(("A", "B")))Common Gotchas
Test methods must start with `test_`
`def check_total` will not run. The class will look empty.
`assert` vs `self.assertEqual`
`assert a == b` gives less output, and `-O` can strip `assert`.
Order dependence
`unittest` does not promise order. Do not use one test to set up the next.
Pytest will collect `TestCase` classes
you can migrate file by file.