Unit tests with unittest
- Version
- 3.14
- Since
- 2.1
- Review
- Draft
Summary#
Put test methods on a unittest.TestCase subclass and use its assertion methods to check results and exceptions. The runner reports failures and errors separately.
Syntax#
Save the example as test_orders.py and run one module or discover test files in the current directory.
python -m unittest test_orders
python -m unittest discover
Example#
The script prints a test count and result. The standard command-line runner also prints elapsed time, which varies.
import unittest
def parse_quantity(text):
quantity = int(text)
if quantity < 0:
raise ValueError("quantity must be nonnegative")
return quantity
class OrderTests(unittest.TestCase):
def test_zero_quantity(self):
self.assertEqual(parse_quantity("0"), 0)
def test_negative_quantity(self):
with self.assertRaises(ValueError):
parse_quantity("-1")
if __name__ == "__main__":
suite = unittest.defaultTestLoader.loadTestsFromTestCase(OrderTests)
result = suite.run(unittest.TestResult())
print("tests:", result.testsRun, "passed:", result.wasSuccessful())
raise SystemExit(not result.wasSuccessful())
Expected output#
tests: 2 passed: True
Common mistakes#
Discovery looks for test*.py by default, and the default loader picks methods whose names start with test. Keep assertRaises blocks narrow so the expected exception can only come from the call you intend to test.
Version applicability#
unittest joined the standard library in Python 2.1. Running a named test module with -m unittest works on all Python 3 releases. The assertRaises context manager and the full script require Python 3.1 or later. The discover command requires Python 3.2 or later.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0