Skip to content

Commit

Permalink
ref(hc): MigrationTest case infers database connection from table_hint
Browse files Browse the repository at this point in the history
  • Loading branch information
corps committed Sep 18, 2023
1 parent 3d314d5 commit 10a4612
Showing 1 changed file with 21 additions and 2 deletions.
23 changes: 21 additions & 2 deletions src/sentry/testutils/cases.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,9 @@
from django.contrib.auth.models import AnonymousUser
from django.core import signing
from django.core.cache import cache
from django.db import DEFAULT_DB_ALIAS, connection, connections
from django.db import DEFAULT_DB_ALIAS, connection, connections, router
from django.db.migrations.executor import MigrationExecutor
from django.db.migrations.loader import MigrationLoader
from django.http import HttpRequest
from django.test import TestCase as DjangoTestCase
from django.test import TransactionTestCase as DjangoTransactionTestCase
Expand Down Expand Up @@ -2242,7 +2243,25 @@ def migrate_to(self):

@property
def connection(self):
return "default"
# Infer connection from table_name
m = MigrationLoader(connections["default"]).get_migration(self.app, self.migrate_to[0][1])
hinted_tables = {
table
for op in m.operations
for tables in op.hints.get("tables", [])
for table in tables
}

hinted_migrations = set()
for table_name in hinted_tables:
for connection_name in connections:
if router.allow_migrate(connection_name, self.app, table_name=table_name):
hinted_migrations.add(connection_name)

assert (
len(hinted_migrations) == 1
), f"Could not determine migration test connection from tables hints Found {hinted_migrations}"
return next(iter(hinted_migrations))

def setUp(self):
super().setUp()
Expand Down

0 comments on commit 10a4612

Please sign in to comment.