unittest | Python Standard Library – Real Python

The Python unittest module provides a framework for creating and running unit tests, allowing developers to ensure their code behaves as expected.

It supports test automation, sharing setup and shutdown code for tests, aggregation of tests into collections, and independence of the tests from the reporting framework.

Here’s a quick example:

Key Features

  • Organizes tests into test suites
  • Supports test fixtures for setup and teardown operations
  • Provides automated test discovery capabilities
  • Includes a wide range of built-in assertions for verifying test results
  • Allows for test skipping, expected failures, and subtests
  • Enables running tests from the command line or programmatically
  • Integrates with test runners, continuous integration (CI) tools, and IDEs for comprehensive test reporting

Frequently Used Classes and Functions

Examples

Creating a test case:

Using .setUp() and .tearDown() methods for test preparation and cleanup:

Common Use Cases

  • Writing and organizing unit tests for functions and classes
  • Automating test runs with CI tools
  • Ensuring code changes do not break existing functionality
  • Documenting the expected behavior of code through test cases
  • Testing edge cases and error handling
  • Writing regression tests to prevent bugs from reappearing
  • Refactoring code confidently by ensuring all tests pass

Real-World Example

Say that you’re building a basic calculator and want to test it to ensure it works correctly. Here’s how you could use the unittest module to achieve this:

In this example, you use the unittest module to verify that the add() function produces the expected results for different input values, ensuring reliability and correctness.

Python's unittest: Writing Unit Tests for Your Code

For additional information on related topics, take a look at the following resources: