On this page
unittest
Prev: unicodedata | Up: stdlib_module | Next: urllib
Rel: typing, annotationlib, pydoc, pydoc_data, doctest
Ref: docs.python.org — unittest
Tags: #public #python3 #stdlib
Import
import unittest
Overview
Zero-dependency xUnit-style test runner, assertion library, and mocking framework (unittest.mock) built into Python. Ideal for stdlib-only packages (python -m unittest discover -s tests) where you want reliable CI across platforms with zero external test dependencies.
Quick Start
import unittest
def add(a: int, b: int) -> int:
return a + b
class TestMath(unittest.TestCase):
def test_add(self) -> None:
self.assertEqual(add(2, 3), 5)
def test_type_error(self) -> None:
with self.assertRaises(TypeError):
add("a", 1) # type: ignore[arg-type]
Implementation Walkthrough
1. Parameterized Cases with subTest() & Guaranteed Cleanup (addCleanup)
subTest() reports every failing case instead of stopping at the first failure; addCleanup() runs even if setUp() fails partway through:
import tempfile
import unittest
from pathlib import Path
class TestSlugify(unittest.TestCase):
def setUp(self) -> None:
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
def test_cases(self) -> None:
for raw, expected in [("Hello World", "hello-world"), ("A B", "a-b")]:
with self.subTest(raw=raw):
self.assertEqual("-".join(raw.lower().split()), expected)
2. Isolating External Calls with unittest.mock.patch
from unittest.mock import patch
import os
with patch.dict(os.environ, {"APP_ENV": "test"}, clear=False):
assert os.environ["APP_ENV"] == "test"
Gotchas & Boundaries
- Patch where an object is looked up, not where it's defined: If
app.pydoesfrom time import sleep, patch"app.sleep", not"time.sleep". - Test methods must start with
test_: Helper methods without that prefix won't be discovered or run. - Use
IsolatedAsyncioTestCaseforasync def test_*methods: PlainTestCasedoes not await coroutine test functions. - Run with
python -m unittest discover -s tests -v: Avoid relying onunittest.main()boilerplate in every file.
Common Functions
- unittest.addModuleCleanup() —
addModuleCleanup(function, /, *args, **kwargs)— Same as addCleanup, except the cleanup items are called even if setUpModule fails (unlike tearDownModule). - unittest.doModuleCleanups() —
doModuleCleanups()— Execute all module cleanup functions. Normally called for you after tearDownModule. - unittest.enterModuleContext() —
enterModuleContext(cm)— Same as enterContext, but module-wide. - unittest.expectedFailure() —
expectedFailure(test_item)—unittest.expectedFailure()function. - unittest.installHandler() —
installHandler()—unittest.installHandler()function. - unittest.registerResult() —
registerResult(result)—unittest.registerResult()function. - unittest.removeHandler() —
removeHandler(method=None)—unittest.removeHandler()function. - unittest.removeResult() —
removeResult(result)—unittest.removeResult()function. - unittest.skip() —
skip(reason)— Unconditionally skip a test. - unittest.skipIf() —
skipIf(condition, reason)— Skip a test if the condition is true. - unittest.skipUnless() —
skipUnless(condition, reason)— Skip a test unless the condition is true.
Classes & Objects
- unittest.FunctionTestCase — A test case that wraps a test function. (Methods:
.addClassCleanup(),.addCleanup(),.addTypeEqualityFunc(),.assertAlmostEqual(),.assertCountEqual(),.assertDictEqual()) - unittest.IsolatedAsyncioTestCase —
unittest.IsolatedAsyncioTestCaseclass. (Methods:.addAsyncCleanup(),.addClassCleanup(),.addCleanup(),.addTypeEqualityFunc(),.assertAlmostEqual(),.assertCountEqual()) - unittest.main — A command-line program that runs a set of tests; this is primarily for making test modules conveniently executable. (Methods:
.createTests(),.parseArgs(),.runTests()) - unittest.SkipTest — Raise this exception in a test to skip it. (Methods:
.add_note(),.with_traceback()) - unittest.TestCase — A class whose instances are single test cases. (Methods:
.addClassCleanup(),.addCleanup(),.addTypeEqualityFunc(),.assertAlmostEqual(),.assertCountEqual(),.assertDictEqual()) - unittest.TestLoader — This class is responsible for loading tests according to various criteria and returning them wrapped in a TestSuite (Methods:
.discover(),.getTestCaseNames(),.loadTestsFromModule(),.loadTestsFromName(),.loadTestsFromNames(),.loadTestsFromTestCase()) - unittest.TestResult — Holder for test result information. (Methods:
.addDuration(),.addError(),.addExpectedFailure(),.addFailure(),.addSkip(),.addSubTest()) - unittest.TestSuite — A test suite is a composite test consisting of a number of TestCases. (Methods:
.addTest(),.addTests(),.countTestCases(),.debug(),.run()) - unittest.TextTestResult — A test result class that can print formatted text results to a stream. (Methods:
.addDuration(),.addError(),.addExpectedFailure(),.addFailure(),.addSkip(),.addSubTest()) - unittest.TextTestRunner — A test runner class that displays results in textual form. (Methods:
.resultclass(),.run())
Constants & Attributes
unittest.defaultTestLoader(TestLoader) =<unittest.loader.TestLoader object at 0x109e4fcb0>
Linked from
- tuts/python3
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/annotationlib
- tuts/python3/stdlib_module/doctest
- tuts/python3/stdlib_module/pydoc
- tuts/python3/stdlib_module/pydoc_data
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/stdlib_module/typing
- tuts/python3/stdlib_module/unicodedata
- tuts/python3/stdlib_module/unittest/addModuleCleanup
- tuts/python3/stdlib_module/unittest/doModuleCleanups
- tuts/python3/stdlib_module/unittest/enterModuleContext
- tuts/python3/stdlib_module/unittest/expectedFailure
- tuts/python3/stdlib_module/unittest/FunctionTestCase
- tuts/python3/stdlib_module/unittest/installHandler
- tuts/python3/stdlib_module/unittest/IsolatedAsyncioTestCase
- tuts/python3/stdlib_module/unittest/main
- tuts/python3/stdlib_module/unittest/registerResult
- tuts/python3/stdlib_module/unittest/removeHandler
- tuts/python3/stdlib_module/unittest/removeResult
- tuts/python3/stdlib_module/unittest/skip
- tuts/python3/stdlib_module/unittest/skipIf
- tuts/python3/stdlib_module/unittest/SkipTest
- tuts/python3/stdlib_module/unittest/skipUnless
- tuts/python3/stdlib_module/unittest/TestCase
- tuts/python3/stdlib_module/unittest/TestLoader
- tuts/python3/stdlib_module/unittest/TestResult
- tuts/python3/stdlib_module/unittest/TestSuite
- tuts/python3/stdlib_module/unittest/TextTestResult
- tuts/python3/stdlib_module/unittest/TextTestRunner
- tuts/python3/stdlib_module/urllib
- tuts/python3/tutorials/intermediate_python_and_software_engineering
- tuts/python3/tutorials/intermediate_python_and_software_engineering/testing_and_debugging
Related notes
- tuts/python3/stdlib_module/annotationlib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/doctest Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/pydoc Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/pydoc_data Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/typing Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/unicodedata Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/unittest/addModuleCleanup Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/unittest/doModuleCleanups Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/unittest/enterModuleContext Linked here; links to this page; shared tags: #stdlib