liveBook · Manning

Unittest

As explained in Get Programming: Learn to code with Python

unittest is Python's standard-library framework for defining, running, and reporting unit tests.

unittest is Python’s standard-library framework for organizing tests, checking program behavior, and reporting failures. A test suite is a class whose test methods begin with test_. section 36.0 section 36.1

A basic unittest workflow is:

  • Import unittest and create a TestCase subclass for the tests. section 36.1
  • Write descriptive test_ methods and use assertions such as assertEqual and assertNotEqual. section 36.1
  • Read failure output for the failing suite, method, source line, expected value, and received value. section 36.1
  • Keep program code and tests in separate files, then rerun tests after each incremental change. section 36.2

Testing functions

A module can define functions such as is_prime and absolute_value, while a separate test file imports that module and checks several inputs. For example, test_prime_5 expects is_prime(5) to be True, and test_abs_neg5 expects absolute_value(-5) to be 5. When a buggy function returns None instead of 0, unittest identifies the exact test and shows “None != 0.”

How Get Programming: Learn to code with Python covers it

How deep it goes
Defines suites, methods, assertions, separation, and failure reports, but defers the complete assertion list to documentation.
Examples
Uses arithmetic assertions, prime-number tests, absolute-value tests, failure traces, and a buggy list-removal exercise.
What it assumes
Assumes basic Python functions and expressions while teaching library imports, test organization, assertions, and failure reading.
What you can do after
Diagnose/debug with it by writing tests, running suites, interpreting failures, and checking fixes incrementally.
How it connects
Connects unit testing with test suites, assertions, functions, debugging, and libraries.

Also explained in

Compare how 4 books explain unittest →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.