Debian Codegraph @

src/polymorphic/tests/utils.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 import os
2 import shutil
3 import re
4 from pathlib import Path
5 from functools import lru_cache
6 import pytest
7
8 from django.core.management import call_command
9 from django_test_migrations.migrator import Migrator
10 from django.contrib.auth import get_user_model
11 from django.contrib.staticfiles.testing import StaticLiveServerTestCase
12 from django.db import connections
13 from django.urls import reverse
14 from django.apps import apps
15
16 from playwright.sync_api import sync_playwright, expect
17 from polymorphic import tests
18
19
20 DSN_RE = re.compile(r"^(?P<host>[^:/]+)(:(?P<port>\d+))?/(?P<service>.+)$")
21
22
23 @lru_cache()
24 def is_sqlite_in_memory(db_name: str = "default") -> bool:
25 from django.conf import settings
26
27 return (
28 settings.DATABASES[db_name]["ENGINE"] == "django.db.backends.sqlite3"
29 and settings.DATABASES[db_name]["NAME"] == ":memory:"
30 )
31
32
33 @lru_cache()
34 def is_oracle(db_name: str = "default") -> bool:
35 from django.conf import settings
36
37 return settings.DATABASES[db_name]["ENGINE"] == "django.db.backends.oracle"
38
39
40 def get_subprocess_test_db_env(db_name: str = "default") -> dict[str, str]:
41 """
42 If you need to run a test in a subprocess that accesses the active test database
43 (e.g. to call management commands), you need to set up the environment variables
44 so that the subprocess can connect to the correct test database.
45 This function returns a copy of os.environ with the necessary variables set.
46 """
47 env = os.environ.copy()
48 db = connections[db_name].settings_dict
49 # this is where django's renaming of test databases gets very annoying - we need
50 # to make sure our subprocess invocation uses the test database - which it wont
51 # do by default because it thinks we aren't in test mode.
52 if is_oracle(db_name):
53 dsn = db["NAME"]
54 m = DSN_RE.match(dsn)
55
56 if not m:
57 raise AssertionError(
58 f"Can't parse Oracle DSN from NAME={dsn!r}. "
59 "Expected format like 'host:1521/service' or 'host/service'."
60 )
61
62 host = m.group("host")
63 port = m.group("port") or "1521"
64 service = m.group("service")
65
66 env["ORACLE_DATABASES"] = service
67 env["ORACLE_USER"] = db["USER"]
68 env["ORACLE_PASSWORD"] = db["PASSWORD"]
69
70 # Only set non-empty values
71 env["ORACLE_HOST"] = host
72 env["ORACLE_PORTS"] = port
73 else:
74 env["PYTEST_DB_NAME"] = db["NAME"]
75 # since Django 6.1, management commands run model checks against every
76 # configured database alias, so the subprocess must also resolve the
77 # secondary alias to its live test database
78 if "secondary" in connections:
79 env["PYTEST_DB2_NAME"] = connections["secondary"].settings_dict["NAME"]
80 return env
81
82
83 class GeneratedMigrationsPerClassMixin:
84 """
85 Generates migrations at class setup, applies them, and rolls them back at teardown.
86
87 Configure:
88 - apps_to_migrate = ["my_app", ...]
89 - database = "default" (optional)
90 """
91
92 apps_to_migrate: list[str] = []
93 database: str = "default"
94 settings: str = os.environ.get("DJANGO_SETTINGS_MODULE", "polymorphic.tests.settings")
95
96 @classmethod
97 def setUpClass(cls):
98 super().setUpClass()
99
100 if not cls.apps_to_migrate:
101 raise RuntimeError("Set apps_to_migrate = ['your_app', ...]")
102
103 for app_label in cls.apps_to_migrate:
104 call_command(
105 "makemigrations",
106 app_label,
107 interactive=False,
108 verbosity=0,
109 )
110
111 # 2) Apply all migrations (up to latest) using django-test-migrations
112 cls.migrator = Migrator(database=cls.database)
113
114 cls._applied_states = {}
115 for app_label in cls.apps_to_migrate:
116 latest = cls._find_latest_migration_name(app_label)
117 # apply_initial_migration applies all migrations up to and including `latest`
118 cls._applied_states[app_label] = cls.migrator.apply_initial_migration(
119 (app_label, latest)
120 )
121
122 @classmethod
123 def tearDownClass(cls):
124 try:
125 # Roll everything back / cleanup:
126 if hasattr(cls, "migrator"):
127 cls.migrator.reset()
128 finally:
129 # remove files
130 for app_label in cls.apps_to_migrate:
131 app_config = apps.get_app_config(app_label) # app *label*
132 mig_dir = Path(app_config.path) / "migrations"
133
134 for mig_file in mig_dir.glob("*.py"):
135 if mig_file.name != "__init__.py" and mig_file.name[0:4].isdigit():
136 os.remove(mig_file)
137
138 # also remove __pycache__ if exists
139 pycache_dir = mig_dir / "__pycache__"
140 if pycache_dir.exists() and pycache_dir.is_dir():
141 shutil.rmtree(pycache_dir)
142
143 super().tearDownClass()
144
145 @classmethod
146 def _find_latest_migration_name(cls, app_label: str) -> str:
147 """
148 Returns "000X_..." latest migration filename (without .py).
149 """
150 app_config = apps.get_app_config(app_label) # app *label*
151 mig_dir = Path(app_config.path) / "migrations"
152
153 candidates = sorted(
154 p for p in mig_dir.glob("*.py") if p.name != "__init__.py" and p.name[0:4].isdigit()
155 )
156 if not candidates:
157 raise RuntimeError(f"No migrations generated for {app_label}")
158 return candidates[-1].stem
159
160
161 class _GenericUITest(StaticLiveServerTestCase):
162 """Generic admin form test using Playwright."""
163
164 HEADLESS = tests.HEADLESS
165
166 admin_username = "admin"
167 admin_password = "password"
168 admin = None
169
170 pytestmark = pytest.mark.ui
171
172 def admin_url(self):
173 return f"{self.live_server_url}{reverse('admin:index')}"
174
175 def add_url(self, model):
176 path = reverse(f"admin:{model._meta.label_lower.replace('.', '_')}_add")
177 return f"{self.live_server_url}{path}"
178
179 def change_url(self, model, id):
180 path = reverse(
181 f"admin:{model._meta.label_lower.replace('.', '_')}_change",
182 args=[id],
183 )
184 return f"{self.live_server_url}{path}"
185
186 def list_url(self, model):
187 path = reverse(f"admin:{model._meta.label_lower.replace('.', '_')}_changelist")
188 return f"{self.live_server_url}{path}"
189
190 def get_object_ids(self, model):
191 self.page.goto(self.list_url(model))
192 return self.page.eval_on_selector_all(
193 "input[name='_selected_action']", "elements => elements.map(e => e.value)"
194 )
195
196 @classmethod
197 def setUpClass(cls):
198 """Set up the test class with a live server and Playwright instance."""
199 os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "1"
200 super().setUpClass()
201 try:
202 cls.playwright = sync_playwright().start()
203 cls.browser = cls.playwright.chromium.launch(headless=cls.HEADLESS)
204 except Exception as e:
205 if "asyncio loop" in str(e) or "executable" in str(e).lower():
206 raise RuntimeError(
207 "Playwright failed to start. This often happens if browser drivers are missing. "
208 "Please run 'just install-playwright' to install them."
209 ) from e
210 raise
211
212 @classmethod
213 def tearDownClass(cls):
214 """Clean up Playwright instance after tests."""
215 cls.browser.close()
216 cls.playwright.stop()
217 super().tearDownClass()
218 del os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"]
219
220 def setUp(self):
221 """Create an admin user before running tests."""
222 self.admin = get_user_model().objects.create_superuser(
223 username=self.admin_username, email="[email protected]", password=self.admin_password
224 )
225 self.page = self.browser.new_page()
226 # Log in to the Django admin
227 self.page.goto(f"{self.live_server_url}/admin/login/")
228 self.page.fill("input[name='username']", self.admin_username)
229 self.page.fill("input[name='password']", self.admin_password)
230 self.page.click("input[type='submit']")
231
232 # Ensure login is successful
233 expect(self.page).to_have_url(f"{self.live_server_url}/admin/")
234
235 def tearDown(self):
236 if self.page:
237 self.page.close()