Skip to content

Commit 1117c03

Browse files
authored
perf(migrations): Improve performance of migration tests a little (#86007)
It takes ~5s to create `ProjectState`, which is used 3 times when rolling migrations backwards and forwards. Caching it should make running multiple migrations a little faster. Unfortunately, rolling back doesn't use the passed `state` param, so we're always going to be doing extra work there. <!-- Describe your PR here. -->
1 parent e8eba8f commit 1117c03

File tree

1 file changed

+18
-3
lines changed

1 file changed

+18
-3
lines changed

src/sentry/testutils/cases.py

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
from django.core.cache import cache
3030
from django.db import connection, connections
3131
from django.db.migrations.executor import MigrationExecutor
32+
from django.db.migrations.state import ProjectState
3233
from django.http import HttpRequest
3334
from django.test import RequestFactory
3435
from django.test import TestCase as DjangoTestCase
@@ -2672,6 +2673,20 @@ def create_user_member_role(self):
26722673
self.login_as(self.user)
26732674

26742675

2676+
_project_state_cache: dict[str, ProjectState] = {}
2677+
2678+
2679+
def get_project_state(connection: str) -> ProjectState:
2680+
global _project_state_cache
2681+
2682+
if connection not in _project_state_cache:
2683+
executor = MigrationExecutor(connections[connection])
2684+
_project_state_cache[connection] = executor._create_project_state(
2685+
with_applied_migrations=True
2686+
)
2687+
return _project_state_cache[connection].clone()
2688+
2689+
26752690
@pytest.mark.migrations
26762691
class TestMigrations(TransactionTestCase):
26772692
"""
@@ -2712,22 +2727,22 @@ def setUp(self):
27122727
old_apps = executor.loader.project_state(migrate_from).apps
27132728

27142729
# Reverse to the original migration
2715-
executor.migrate(migrate_from)
2730+
executor.migrate(migrate_from, state=get_project_state(self.connection))
27162731

27172732
self.setup_before_migration(old_apps)
27182733

27192734
# Run the migration to test
27202735
executor = MigrationExecutor(connection)
27212736
executor.loader.build_graph() # reload.
2722-
executor.migrate(migrate_to)
2737+
executor.migrate(migrate_to, state=get_project_state(self.connection))
27232738

27242739
self.apps = executor.loader.project_state(migrate_to).apps
27252740

27262741
def tearDown(self):
27272742
super().tearDown()
27282743
executor = MigrationExecutor(connection)
27292744
executor.loader.build_graph() # reload.
2730-
executor.migrate(self.current_migration)
2745+
executor.migrate(self.current_migration, state=get_project_state(self.connection))
27312746

27322747
def setup_initial_state(self):
27332748
# Add code here that will run before we roll back the database to the `migrate_from`

0 commit comments

Comments
 (0)