← Reference notes

Unit tests with Python unittest

Unit tests with Python unittest

Summary

unittest is Python's built-in test framework. Subclass unittest.TestCase, write methods whose names start with test, and use assertions such as assertEqual and assertRaises. Put shared setup in setUp and tearDown. Run the tests with python -m unittest (it discovers them automatically) or unittest.main().

Draft. License: CC BY 4.0 (this summary). Sources: [S1] Python Software Foundation, "unittest: Unit testing framework (Python 3 docs)" (PSF License 2.0 docs; restated in our own words, no copied text).

Example

import unittest

def add(a, b): return a + b

class AddTests(unittest.TestCase):
    def test_ints(self):
        self.assertEqual(add(2, 3), 5)
    def test_type_error(self):
        with self.assertRaises(TypeError):
            add(1, None)

if __name__ == "__main__":
    unittest.main()

Facts

Caveats

Pointers

Source: https://docs.python.org/3/library/unittest.html · License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted), condensed and paraphrased; sources: Python Software Foundation, Python 3 documentation, unittest: Unit testing framework (PSF License 2.0); restated in our own words

Cite this

Permanent ID: iil:note:yzrt49jf

iinventedlight Library. 2026. "Unit tests with Python unittest." iinventedlight Library, iil:note:yzrt49jf, version of 2026-11-02. https://iinventedlight.com/library/reference/python-docs/python-unittest/. License: CC-BY-4.0. Summary of https://docs.python.org/3/library/unittest.html.

@misc{iil_note_yzrt49jf,
  author = {{iinventedlight Library}},
  title = {{Unit tests with Python unittest}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-02},
  url = {https://iinventedlight.com/library/reference/python-docs/python-unittest/},
  note = {Permanent ID iil:note:yzrt49jf. License: CC-BY-4.0. Summary of https://docs.python.org/3/library/unittest.html.},
}

For language models and agents: start at /llms.txt. This page in Markdown: /library/reference/python-docs/python-unittest.md.