Standard Library
Testing
A test starts with behavior small enough to name. The function can be ordinary code; the test supplies a representative input and expected result.
Source
def add(left, right):
return left + right
print(add(2, 3))Output
5unittest.TestCase groups test methods. setUp runs before each test method to build per-test fixtures, assertEqual checks values, and assertRaises asserts that a block raises the expected exception type.
Source
import unittest
def divide(left, right):
if right == 0:
raise ZeroDivisionError("denominator is zero")
return left / right
class AddTests(unittest.TestCase):
def setUp(self):
self.zero = 0
def test_adds_numbers(self):
self.assertEqual(add(self.zero + 2, 3), 5)
def test_adds_empty_strings(self):
self.assertEqual(add("", "py"), "py")
def test_divide_by_zero_raises(self):
with self.assertRaises(ZeroDivisionError):
divide(1, 0)
print([name for name in dir(AddTests) if name.startswith("test_")])Output
['test_adds_empty_strings', 'test_adds_numbers', 'test_divide_by_zero_raises']A runner executes the suite and records whether every assertion passed. Capturing the runner stream keeps this page's output deterministic.
Source
import io
loader = unittest.defaultTestLoader
suite = loader.loadTestsFromTestCase(AddTests)
stream = io.StringIO()
runner = unittest.TextTestRunner(stream=stream, verbosity=0)
result = runner.run(suite)
print(result.testsRun)
print(result.wasSuccessful())Output
3
TrueNotes
- Test method names should describe behavior, not implementation details.
- A good unit test is deterministic and independent of test order.
- Use broader integration tests when the behavior depends on several components working together.
See also
- prerequisite: Assertions
- prerequisite: Exceptions
- prerequisite: Modules
Run the complete example
Expected output
3
True
Execution time appears here after you run the example.