Standard Library

Testing

Tests make expected behavior executable and repeatable.

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

5
arrangeset up stateactperform behaviorassertcompare result
arrange-act-assert: set up the state, perform the behavior under test, compare the result to expectations.

unittest.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
True

Notes

See also

Run the complete example

Example code

Expected output

3
True

Execution time appears here after you run the example.