Skip to main content
Migrating from unittest to pytest involves converting test classes and assertions to pytest’s more modern and concise style. This guide will walk you through using Codegen to automate this migration.
You can find the complete example code in our examples repository.

Overview

The migration process involves four main steps:
  1. Converting test class inheritance and setup/teardown methods
  2. Updating assertions to pytest style
  3. Converting test discovery patterns
  4. Modernizing fixture usage
Let’s walk through each step using Codegen.

Step 1: Convert Test Classes and Setup Methods

The first step is to convert unittest’s class-based tests to pytest’s function-based style. This includes:
  • Removing unittest.TestCase inheritance
  • Converting setUp and tearDown methods to fixtures
  • Updating class-level setup methods

Step 2: Update Assertions

Next, we’ll convert unittest’s assertion methods to pytest’s plain assert statements:

Step 3: Update Test Discovery

pytest uses a different test discovery pattern than unittest. We’ll update the test file names and patterns:

Step 4: Modernize Fixture Usage

Finally, we’ll update how test dependencies are managed using pytest’s powerful fixture system:

Common Patterns

Here are some common patterns you’ll encounter when migrating to pytest:
  1. Parameterized Tests
  1. Exception Testing
  1. Temporary Resources

Tips and Notes

  1. pytest fixtures are more flexible than unittest’s setup/teardown methods:
    • They can be shared across test files
    • They support different scopes (function, class, module, session)
    • They can be parameterized
  2. pytest’s assertion introspection provides better error messages by default:
  3. You can gradually migrate to pytest:
    • pytest can run unittest-style tests
    • Convert one test file at a time
    • Start with assertion style updates before moving to fixtures
  4. Consider using pytest’s built-in fixtures:
    • tmp_path for temporary directories
    • capsys for capturing stdout/stderr
    • monkeypatch for modifying objects
    • caplog for capturing log messages