Migrating from unittest to pytest
Learn how to migrate unittest test suites to pytest using Codegen
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:
- Converting test class inheritance and setup/teardown methods
- Updating assertions to pytest style
- Converting test discovery patterns
- 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
andtearDown
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:
- Parameterized Tests
- Exception Testing
- Temporary Resources
Tips and Notes
-
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
-
pytest’s assertion introspection provides better error messages by default:
-
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
-
Consider using pytest’s built-in fixtures:
tmp_path
for temporary directoriescapsys
for capturing stdout/stderrmonkeypatch
for modifying objectscaplog
for capturing log messages
Was this page helpful?