Debian Codegraph @

src/polymorphic/tests/utils.py

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