Debian Codegraph @

sandbox/tests/bugs/test_migrations_in_base_models.py

raw
1 import warnings
2 from unittest.mock import patch
3
4 import pytest
5 from django.apps import apps
6 from django.core import management
7 from django.core.management.base import CommandError
8 from django.db import models
9 from django.db.utils import ProgrammingError
10
11 from django_pgschemas.checks import check_schema_names
12 from django_pgschemas.models import TenantModel as BaseTenantModel
13 from django_pgschemas.utils import get_tenant_model
14
15
16 def patched_get_tenant_model(*args, **kwargs):
17 if RealTenantModel := get_tenant_model():
18
19 class TenantModel(BaseTenantModel):
20 dummy = models.TextField()
21
22 class Meta:
23 app_label = RealTenantModel._meta.app_label
24
25 return TenantModel
26
27 return None
28
29
30 @pytest.mark.bug
31 def test_database_checks_with_zero_migrations(transactional_db):
32 """
33 Provoke a handled ProgrammingError by migrating models from empty database.
34 """
35 management.call_command("migrate", "shared_public", "zero", verbosity=0)
36 # The goal is that the next line doesn't raise ProgrammingError
37 check_schema_names(apps.get_app_config("django_pgschemas"))
38 management.call_command("migrate", verbosity=0)
39
40
41 @pytest.mark.bug
42 @patch("django_pgschemas.management.commands.get_tenant_model", patched_get_tenant_model)
43 def test_whowill_with_pending_migrations(TenantModel, db):
44 """
45 Provoke a handled ProgrammingError by running tenant command with pending model changes.
46 """
47 if TenantModel is None:
48 pytest.skip("Dynamic tenants are not in use")
49
50 with warnings.catch_warnings():
51 warnings.simplefilter("ignore") # Avoid warnings about model being registered twice
52
53 with pytest.raises(CommandError) as ctx:
54 management.call_command("whowill", all_schemas=True, verbosity=0)
55
56 assert str(ctx.value) == (
57 "Error while attempting to retrieve dynamic schemas. "
58 "Perhaps you need to migrate the 'public' schema first?"
59 )
60
61
62 @pytest.mark.bug
63 def test_migrate_with_exclusions(TenantModel, db):
64 if TenantModel is None:
65 pytest.skip("Dynamic tenants are not in use")
66
67 # We first unapply a migration with fake so we can reapply it without fake
68 # This should work without errors
69 management.call_command(
70 "migrate", "app_tenants", "0001_initial", fake=True, schemas=["tenant1"], verbosity=0
71 )
72
73 # We then migrate on all schemas except for tenant1, THIS IS THE CASE WE WANT TO TEST
74 # This should work without errors
75 management.call_command("migrate", all_schemas=True, excluded_schemas=["tenant1"], verbosity=0)
76
77 # If we try to global migrate now, we should get a ProgrammingError
78 with pytest.raises(ProgrammingError):
79 management.call_command("migrate", all_schemas=True, verbosity=0)
80 # We finally apply the migration again with fake
81 # This should work without errors
82
83 management.call_command("migrate", fake=True, all_schemas=True, verbosity=0)