This codemod demonstrates how to automatically migrate unittest test suites to pytest using Codegen. The migration script simplifies the process by handling all the tedious manual updates automatically.
The script automates the entire migration process in a few key steps:
-
Convert Test Classes and Setup Methods
# From: class TestUsers(unittest.TestCase): def setUp(self): self.db = setup_test_db() def test_create_user(self): user = self.db.create_user("test") self.assertEqual(user.name, "test") # To: @pytest.fixture def db(): db = setup_test_db() yield db def test_create_user(db): user = db.create_user("test") assert user.name == "test"
- Converts
unittest.TestCaseclasses to standalone functions - Replaces
setUpmethods withpytestfixtures
- Converts
-
Update Assertions
# From: def test_validation(self): self.assertTrue(is_valid("test")) self.assertEqual(count_items(), 0) self.assertRaises(ValueError, parse_id, "invalid") # To: def test_validation(): assert is_valid("test") assert count_items() == 0 with pytest.raises(ValueError): parse_id("invalid")
- Replaces
unittestassertions withpytestassertions - Uses
pytest.raisesfor exception testing
- Replaces
-
Convert Test Discovery
# From: if __name__ == '__main__': unittest.main() # To: # Remove unittest.main() and rename files to test_*.py
- Removes
unittest.main()calls - Ensures files are named for
pytestdiscovery
- Removes
-
Modernize Fixtures
# From: @classmethod def setUpClass(cls): cls.conn = create_db() # To: @pytest.fixture(scope="session") def conn(): return create_db()
- Converts class-level setup to session-scoped fixtures
# Install Codegen
pip install codegen
# Run the migration
python run.pyThe script will process all Python test files in the repo-before directory and apply the transformations in the correct order.
run.py- The migration scriptrepo-before/- Sampleunittesttest suite to migrateguide.md- Additional notes and explanations
Feel free to submit issues and enhancement requests!