Debian Codegraph @

tests/apps/tests.py

raw
1 import os
2 from unittest.mock import patch
3
4 import django
5 from django.apps import AppConfig, apps
6 from django.apps.registry import Apps
7 from django.contrib.admin.models import LogEntry
8 from django.core.exceptions import AppRegistryNotReady, ImproperlyConfigured
9 from django.db import connections, models
10 from django.test import (
11 SimpleTestCase,
12 TransactionTestCase,
13 override_settings,
14 skipUnlessDBFeature,
15 )
16 from django.test.utils import extend_sys_path, isolate_apps
17
18 from .models import SoAlternative, TotallyNormal, new_apps
19 from .one_config_app.apps import OneConfig
20 from .two_configs_one_default_app.apps import TwoConfig
21
22 # Small list with a variety of cases for tests that iterate on installed apps.
23 # Intentionally not in alphabetical order to check if the order is preserved.
24
25 SOME_INSTALLED_APPS = [
26 "apps.apps.MyAdmin",
27 "apps.apps.MyAuth",
28 "django.contrib.contenttypes",
29 "django.contrib.sessions",
30 "django.contrib.messages",
31 "django.contrib.staticfiles",
32 ]
33
34 SOME_INSTALLED_APPS_NAMES = [
35 "django.contrib.admin",
36 "django.contrib.auth",
37 ] + SOME_INSTALLED_APPS[2:]
38
39 HERE = os.path.dirname(__file__)
40
41
42 class AppsTests(SimpleTestCase):
43 def test_singleton_main(self):
44 """
45 Only one main registry can exist.
46 """
47 with self.assertRaises(RuntimeError):
48 Apps(installed_apps=None)
49
50 def test_ready(self):
51 """
52 Tests the ready property of the main registry.
53 """
54 # The main app registry is always ready when the tests run.
55 self.assertIs(apps.ready, True)
56 # Non-main app registries are populated in __init__.
57 self.assertIs(Apps().ready, True)
58 # The condition is set when apps are ready
59 self.assertIs(apps.ready_event.is_set(), True)
60 self.assertIs(Apps().ready_event.is_set(), True)
61
62 def test_bad_app_config(self):
63 """
64 Tests when INSTALLED_APPS contains an incorrect app config.
65 """
66 msg = "'apps.apps.BadConfig' must supply a name attribute."
67 with self.assertRaisesMessage(ImproperlyConfigured, msg):
68 with self.settings(INSTALLED_APPS=["apps.apps.BadConfig"]):
69 pass
70
71 def test_not_an_app_config(self):
72 """
73 Tests when INSTALLED_APPS contains a class that isn't an app config.
74 """
75 msg = "'apps.apps.NotAConfig' isn't a subclass of AppConfig."
76 with self.assertRaisesMessage(ImproperlyConfigured, msg):
77 with self.settings(INSTALLED_APPS=["apps.apps.NotAConfig"]):
78 pass
79
80 def test_no_such_app(self):
81 """
82 Tests when INSTALLED_APPS contains an app that doesn't exist, either
83 directly or via an app config.
84 """
85 with self.assertRaises(ImportError):
86 with self.settings(INSTALLED_APPS=["there is no such app"]):
87 pass
88 msg = (
89 "Cannot import 'there is no such app'. Check that "
90 "'apps.apps.NoSuchApp.name' is correct."
91 )
92 with self.assertRaisesMessage(ImproperlyConfigured, msg):
93 with self.settings(INSTALLED_APPS=["apps.apps.NoSuchApp"]):
94 pass
95
96 def test_no_such_app_config(self):
97 msg = "Module 'apps' does not contain a 'NoSuchConfig' class."
98 with self.assertRaisesMessage(ImportError, msg):
99 with self.settings(INSTALLED_APPS=["apps.NoSuchConfig"]):
100 pass
101
102 def test_no_such_app_config_with_choices(self):
103 msg = (
104 "Module 'apps.apps' does not contain a 'NoSuchConfig' class. "
105 "Choices are: 'BadConfig', 'ModelPKAppsConfig', 'MyAdmin', "
106 "'MyAuth', 'NoSuchApp', 'PlainAppsConfig', 'RelabeledAppsConfig'."
107 )
108 with self.assertRaisesMessage(ImportError, msg):
109 with self.settings(INSTALLED_APPS=["apps.apps.NoSuchConfig"]):
110 pass
111
112 def test_no_config_app(self):
113 """Load an app that doesn't provide an AppConfig class."""
114 with self.settings(INSTALLED_APPS=["apps.no_config_app"]):
115 config = apps.get_app_config("no_config_app")
116 self.assertIsInstance(config, AppConfig)
117
118 def test_one_config_app(self):
119 """Load an app that provides an AppConfig class."""
120 with self.settings(INSTALLED_APPS=["apps.one_config_app"]):
121 config = apps.get_app_config("one_config_app")
122 self.assertIsInstance(config, OneConfig)
123
124 def test_two_configs_app(self):
125 """Load an app that provides two AppConfig classes."""
126 with self.settings(INSTALLED_APPS=["apps.two_configs_app"]):
127 config = apps.get_app_config("two_configs_app")
128 self.assertIsInstance(config, AppConfig)
129
130 def test_two_default_configs_app(self):
131 """Load an app that provides two default AppConfig classes."""
132 msg = (
133 "'apps.two_default_configs_app.apps' declares more than one "
134 "default AppConfig: 'TwoConfig', 'TwoConfigBis'."
135 )
136 with self.assertRaisesMessage(RuntimeError, msg):
137 with self.settings(INSTALLED_APPS=["apps.two_default_configs_app"]):
138 pass
139
140 def test_two_configs_one_default_app(self):
141 """
142 Load an app that provides two AppConfig classes, one being the default.
143 """
144 with self.settings(INSTALLED_APPS=["apps.two_configs_one_default_app"]):
145 config = apps.get_app_config("two_configs_one_default_app")
146 self.assertIsInstance(config, TwoConfig)
147
148 @override_settings(INSTALLED_APPS=SOME_INSTALLED_APPS)
149 def test_get_app_configs(self):
150 """
151 Tests apps.get_app_configs().
152 """
153 app_configs = apps.get_app_configs()
154 self.assertEqual(
155 [app_config.name for app_config in app_configs], SOME_INSTALLED_APPS_NAMES
156 )
157
158 @override_settings(INSTALLED_APPS=SOME_INSTALLED_APPS)
159 def test_get_app_config(self):
160 """
161 Tests apps.get_app_config().
162 """
163 app_config = apps.get_app_config("admin")
164 self.assertEqual(app_config.name, "django.contrib.admin")
165
166 app_config = apps.get_app_config("staticfiles")
167 self.assertEqual(app_config.name, "django.contrib.staticfiles")
168
169 with self.assertRaises(LookupError):
170 apps.get_app_config("admindocs")
171
172 msg = "No installed app with label 'django.contrib.auth'. Did you mean 'myauth'"
173 with self.assertRaisesMessage(LookupError, msg):
174 apps.get_app_config("django.contrib.auth")
175
176 @override_settings(INSTALLED_APPS=SOME_INSTALLED_APPS)
177 def test_is_installed(self):
178 """
179 Tests apps.is_installed().
180 """
181 self.assertIs(apps.is_installed("django.contrib.admin"), True)
182 self.assertIs(apps.is_installed("django.contrib.auth"), True)
183 self.assertIs(apps.is_installed("django.contrib.staticfiles"), True)
184 self.assertIs(apps.is_installed("django.contrib.admindocs"), False)
185
186 @override_settings(INSTALLED_APPS=SOME_INSTALLED_APPS)
187 def test_get_model(self):
188 """
189 Tests apps.get_model().
190 """
191 self.assertEqual(apps.get_model("admin", "LogEntry"), LogEntry)
192 with self.assertRaises(LookupError):
193 apps.get_model("admin", "LogExit")
194
195 # App label is case-sensitive, Model name is case-insensitive.
196 self.assertEqual(apps.get_model("admin", "loGentrY"), LogEntry)
197 with self.assertRaises(LookupError):
198 apps.get_model("Admin", "LogEntry")
199
200 # A single argument is accepted.
201 self.assertEqual(apps.get_model("admin.LogEntry"), LogEntry)
202 with self.assertRaises(LookupError):
203 apps.get_model("admin.LogExit")
204 with self.assertRaises(ValueError):
205 apps.get_model("admin_LogEntry")
206
207 @override_settings(INSTALLED_APPS=SOME_INSTALLED_APPS)
208 def test_clear_cache(self):
209 # Set cache.
210 self.assertIsNone(apps.get_swappable_settings_name("admin.LogEntry"))
211 apps.get_models()
212
213 apps.clear_cache()
214
215 self.assertEqual(apps.get_swappable_settings_name.cache_info().currsize, 0)
216 self.assertEqual(apps.get_models.cache_info().currsize, 0)
217
218 @override_settings(INSTALLED_APPS=["apps.apps.RelabeledAppsConfig"])
219 def test_relabeling(self):
220 self.assertEqual(apps.get_app_config("relabeled").name, "apps")
221
222 def test_duplicate_labels(self):
223 with self.assertRaisesMessage(
224 ImproperlyConfigured, "Application labels aren't unique"
225 ):
226 with self.settings(INSTALLED_APPS=["apps.apps.PlainAppsConfig", "apps"]):
227 pass
228
229 def test_duplicate_names(self):
230 with self.assertRaisesMessage(
231 ImproperlyConfigured, "Application names aren't unique"
232 ):
233 with self.settings(
234 INSTALLED_APPS=["apps.apps.RelabeledAppsConfig", "apps"]
235 ):
236 pass
237
238 def test_import_exception_is_not_masked(self):
239 """
240 App discovery should preserve stack traces. Regression test for #22920.
241 """
242 with self.assertRaisesMessage(ImportError, "Oops"):
243 with self.settings(INSTALLED_APPS=["import_error_package"]):
244 pass
245
246 def test_models_py(self):
247 """
248 The models in the models.py file were loaded correctly.
249 """
250 self.assertEqual(apps.get_model("apps", "TotallyNormal"), TotallyNormal)
251 with self.assertRaises(LookupError):
252 apps.get_model("apps", "SoAlternative")
253
254 with self.assertRaises(LookupError):
255 new_apps.get_model("apps", "TotallyNormal")
256 self.assertEqual(new_apps.get_model("apps", "SoAlternative"), SoAlternative)
257
258 def test_models_not_loaded(self):
259 """
260 apps.get_models() raises an exception if apps.models_ready isn't True.
261 """
262 apps.models_ready = False
263 try:
264 # The cache must be cleared to trigger the exception.
265 apps.get_models.cache_clear()
266 with self.assertRaisesMessage(
267 AppRegistryNotReady, "Models aren't loaded yet."
268 ):
269 apps.get_models()
270 finally:
271 apps.models_ready = True
272
273 def test_dynamic_load(self):
274 """
275 Makes a new model at runtime and ensures it goes into the right place.
276 """
277 old_models = list(apps.get_app_config("apps").get_models())
278 # Construct a new model in a new app registry
279 body = {}
280 new_apps = Apps(["apps"])
281 meta_contents = {
282 "app_label": "apps",
283 "apps": new_apps,
284 }
285 meta = type("Meta", (), meta_contents)
286 body["Meta"] = meta
287 body["__module__"] = TotallyNormal.__module__
288 temp_model = type("SouthPonies", (models.Model,), body)
289 # Make sure it appeared in the right place!
290 self.assertEqual(list(apps.get_app_config("apps").get_models()), old_models)
291 with self.assertRaises(LookupError):
292 apps.get_model("apps", "SouthPonies")
293 self.assertEqual(new_apps.get_model("apps", "SouthPonies"), temp_model)
294
295 def test_model_clash(self):
296 """
297 Test for behavior when two models clash in the app registry.
298 """
299 new_apps = Apps(["apps"])
300 meta_contents = {
301 "app_label": "apps",
302 "apps": new_apps,
303 }
304
305 body = {}
306 body["Meta"] = type("Meta", (), meta_contents)
307 body["__module__"] = TotallyNormal.__module__
308 type("SouthPonies", (models.Model,), body)
309
310 # When __name__ and __module__ match we assume the module
311 # was reloaded and issue a warning. This use-case is
312 # useful for REPL. Refs #23621.
313 body = {}
314 body["Meta"] = type("Meta", (), meta_contents)
315 body["__module__"] = TotallyNormal.__module__
316 msg = (
317 "Model 'apps.southponies' was already registered. "
318 "Reloading models is not advised as it can lead to inconsistencies, "
319 "most notably with related models."
320 )
321 with self.assertRaisesMessage(RuntimeWarning, msg):
322 type("SouthPonies", (models.Model,), body)
323
324 # If it doesn't appear to be a reloaded module then we expect
325 # a RuntimeError.
326 body = {}
327 body["Meta"] = type("Meta", (), meta_contents)
328 body["__module__"] = TotallyNormal.__module__ + ".whatever"
329 with self.assertRaisesMessage(
330 RuntimeError, "Conflicting 'southponies' models in application 'apps':"
331 ):
332 type("SouthPonies", (models.Model,), body)
333
334 def test_get_containing_app_config_apps_not_ready(self):
335 """
336 apps.get_containing_app_config() should raise an exception if
337 apps.apps_ready isn't True.
338 """
339 apps.apps_ready = False
340 try:
341 with self.assertRaisesMessage(
342 AppRegistryNotReady, "Apps aren't loaded yet"
343 ):
344 apps.get_containing_app_config("foo")
345 finally:
346 apps.apps_ready = True
347
348 @isolate_apps("apps", kwarg_name="apps")
349 def test_lazy_model_operation(self, apps):
350 """
351 Tests apps.lazy_model_operation().
352 """
353 model_classes = []
354 initial_pending = set(apps._pending_operations)
355
356 def test_func(*models):
357 model_classes[:] = models
358
359 class LazyA(models.Model):
360 pass
361
362 # Test models appearing twice, and models appearing consecutively
363 model_keys = [
364 ("apps", model_name)
365 for model_name in ["lazya", "lazyb", "lazyb", "lazyc", "lazya"]
366 ]
367 apps.lazy_model_operation(test_func, *model_keys)
368
369 # LazyModelA shouldn't be waited on since it's already registered,
370 # and LazyModelC shouldn't be waited on until LazyModelB exists.
371 self.assertEqual(
372 set(apps._pending_operations) - initial_pending, {("apps", "lazyb")}
373 )
374
375 # Multiple operations can wait on the same model
376 apps.lazy_model_operation(test_func, ("apps", "lazyb"))
377
378 class LazyB(models.Model):
379 pass
380
381 self.assertEqual(model_classes, [LazyB])
382
383 # Now we are just waiting on LazyModelC.
384 self.assertEqual(
385 set(apps._pending_operations) - initial_pending, {("apps", "lazyc")}
386 )
387
388 class LazyC(models.Model):
389 pass
390
391 # Everything should be loaded - make sure the callback was executed properly.
392 self.assertEqual(model_classes, [LazyA, LazyB, LazyB, LazyC, LazyA])
393
394
395 class Stub:
396 def __init__(self, **kwargs):
397 self.__dict__.update(kwargs)
398
399
400 class AppConfigTests(SimpleTestCase):
401 """Unit tests for AppConfig class."""
402
403 def test_path_set_explicitly(self):
404 """If subclass sets path as class attr, no module attributes needed."""
405
406 class MyAppConfig(AppConfig):
407 path = "foo"
408
409 ac = MyAppConfig("label", Stub())
410
411 self.assertEqual(ac.path, "foo")
412
413 def test_explicit_path_overrides(self):
414 """If path set as class attr, overrides __path__ and __file__."""
415
416 class MyAppConfig(AppConfig):
417 path = "foo"
418
419 ac = MyAppConfig("label", Stub(__path__=["a"], __file__="b/__init__.py"))
420
421 self.assertEqual(ac.path, "foo")
422
423 def test_dunder_path(self):
424 """If single element in __path__, use it (in preference to __file__)."""
425 ac = AppConfig("label", Stub(__path__=["a"], __file__="b/__init__.py"))
426
427 self.assertEqual(ac.path, "a")
428
429 def test_no_dunder_path_fallback_to_dunder_file(self):
430 """If there is no __path__ attr, use __file__."""
431 ac = AppConfig("label", Stub(__file__="b/__init__.py"))
432
433 self.assertEqual(ac.path, "b")
434
435 def test_empty_dunder_path_fallback_to_dunder_file(self):
436 """If the __path__ attr is empty, use __file__ if set."""
437 ac = AppConfig("label", Stub(__path__=[], __file__="b/__init__.py"))
438
439 self.assertEqual(ac.path, "b")
440
441 def test_multiple_dunder_path_fallback_to_dunder_file(self):
442 """If the __path__ attr is length>1, use __file__ if set."""
443 ac = AppConfig("label", Stub(__path__=["a", "b"], __file__="c/__init__.py"))
444
445 self.assertEqual(ac.path, "c")
446
447 def test_no_dunder_path_or_dunder_file(self):
448 """If there is no __path__ or __file__, raise ImproperlyConfigured."""
449 with self.assertRaises(ImproperlyConfigured):
450 AppConfig("label", Stub())
451
452 def test_empty_dunder_path_no_dunder_file(self):
453 """If the __path__ attr is empty and there is no __file__, raise."""
454 with self.assertRaises(ImproperlyConfigured):
455 AppConfig("label", Stub(__path__=[]))
456
457 def test_multiple_dunder_path_no_dunder_file(self):
458 """If the __path__ attr is length>1 and there is no __file__, raise."""
459 with self.assertRaises(ImproperlyConfigured):
460 AppConfig("label", Stub(__path__=["a", "b"]))
461
462 def test_duplicate_dunder_path_no_dunder_file(self):
463 """
464 If the __path__ attr contains duplicate paths and there is no
465 __file__, they duplicates should be deduplicated (#25246).
466 """
467 ac = AppConfig("label", Stub(__path__=["a", "a"]))
468 self.assertEqual(ac.path, "a")
469
470 def test_repr(self):
471 ac = AppConfig("label", Stub(__path__=["a"]))
472 self.assertEqual(repr(ac), "<AppConfig: label>")
473
474 def test_invalid_label(self):
475 class MyAppConfig(AppConfig):
476 label = "invalid.label"
477
478 msg = "The app label 'invalid.label' is not a valid Python identifier."
479 with self.assertRaisesMessage(ImproperlyConfigured, msg):
480 MyAppConfig("test_app", Stub())
481
482 @override_settings(
483 INSTALLED_APPS=["apps.apps.ModelPKAppsConfig"],
484 DEFAULT_AUTO_FIELD="django.db.models.SmallAutoField",
485 )
486 def test_app_default_auto_field(self):
487 apps_config = apps.get_app_config("apps")
488 self.assertEqual(
489 apps_config.default_auto_field,
490 "django.db.models.BigAutoField",
491 )
492 self.assertIs(apps_config._is_default_auto_field_overridden, True)
493
494 @override_settings(
495 INSTALLED_APPS=["apps.apps.PlainAppsConfig"],
496 DEFAULT_AUTO_FIELD="django.db.models.SmallAutoField",
497 )
498 def test_default_auto_field_setting(self):
499 apps_config = apps.get_app_config("apps")
500 self.assertEqual(
501 apps_config.default_auto_field,
502 "django.db.models.SmallAutoField",
503 )
504 self.assertIs(apps_config._is_default_auto_field_overridden, False)
505
506
507 class NamespacePackageAppTests(SimpleTestCase):
508 # We need nsapp to be top-level so our multiple-paths tests can add another
509 # location for it (if its inside a normal package with an __init__.py that
510 # isn't possible). In order to avoid cluttering the already-full tests/ dir
511 # (which is on sys.path), we add these new entries to sys.path temporarily.
512 base_location = os.path.join(HERE, "namespace_package_base")
513 other_location = os.path.join(HERE, "namespace_package_other_base")
514 app_path = os.path.join(base_location, "nsapp")
515
516 def test_single_path(self):
517 """
518 A Py3.3+ namespace package can be an app if it has only one path.
519 """
520 with extend_sys_path(self.base_location):
521 with self.settings(INSTALLED_APPS=["nsapp"]):
522 app_config = apps.get_app_config("nsapp")
523 self.assertEqual(app_config.path, self.app_path)
524
525 def test_multiple_paths(self):
526 """
527 A Py3.3+ namespace package with multiple locations cannot be an app.
528
529 (Because then we wouldn't know where to load its templates, static
530 assets, etc. from.)
531 """
532 # Temporarily add two directories to sys.path that both contain
533 # components of the "nsapp" package.
534 with extend_sys_path(self.base_location, self.other_location):
535 with self.assertRaises(ImproperlyConfigured):
536 with self.settings(INSTALLED_APPS=["nsapp"]):
537 pass
538
539 def test_multiple_paths_explicit_path(self):
540 """
541 Multiple locations are ok only if app-config has explicit path.
542 """
543 # Temporarily add two directories to sys.path that both contain
544 # components of the "nsapp" package.
545 with extend_sys_path(self.base_location, self.other_location):
546 with self.settings(INSTALLED_APPS=["nsapp.apps.NSAppConfig"]):
547 app_config = apps.get_app_config("nsapp")
548 self.assertEqual(app_config.path, self.app_path)
549
550
551 class QueryPerformingAppTests(TransactionTestCase):
552 available_apps = ["apps"]
553 databases = {"default", "other"}
554 expected_msg = (
555 "Accessing the database during app initialization is discouraged. To fix this "
556 "warning, avoid executing queries in AppConfig.ready() or when your app "
557 "modules are imported."
558 )
559
560 def test_query_default_database_using_model(self):
561 query_results = self.run_setup("QueryDefaultDatabaseModelAppConfig")
562 self.assertSequenceEqual(query_results, [("new name",)])
563
564 def test_query_other_database_using_model(self):
565 query_results = self.run_setup("QueryOtherDatabaseModelAppConfig")
566 self.assertSequenceEqual(query_results, [("new name",)])
567
568 def test_query_default_database_using_cursor(self):
569 query_results = self.run_setup("QueryDefaultDatabaseCursorAppConfig")
570 self.assertSequenceEqual(query_results, [(42,)])
571
572 def test_query_other_database_using_cursor(self):
573 query_results = self.run_setup("QueryOtherDatabaseCursorAppConfig")
574 self.assertSequenceEqual(query_results, [(42,)])
575
576 def test_query_many_default_database_using_cursor(self):
577 self.run_setup("QueryDefaultDatabaseCursorManyAppConfig")
578
579 def test_query_many_other_database_using_cursor(self):
580 self.run_setup("QueryOtherDatabaseCursorManyAppConfig")
581
582 @skipUnlessDBFeature("create_test_procedure_without_params_sql")
583 def test_query_default_database_using_stored_procedure(self):
584 connection = connections["default"]
585 with connection.cursor() as cursor:
586 cursor.execute(connection.features.create_test_procedure_without_params_sql)
587
588 try:
589 self.run_setup("QueryDefaultDatabaseStoredProcedureAppConfig")
590 finally:
591 with connection.schema_editor() as editor:
592 editor.remove_procedure("test_procedure")
593
594 @skipUnlessDBFeature("create_test_procedure_without_params_sql")
595 def test_query_other_database_using_stored_procedure(self):
596 connection = connections["other"]
597 with connection.cursor() as cursor:
598 cursor.execute(connection.features.create_test_procedure_without_params_sql)
599
600 try:
601 self.run_setup("QueryOtherDatabaseStoredProcedureAppConfig")
602 finally:
603 with connection.schema_editor() as editor:
604 editor.remove_procedure("test_procedure")
605
606 def run_setup(self, app_config_name):
607 custom_settings = override_settings(
608 INSTALLED_APPS=[f"apps.query_performing_app.apps.{app_config_name}"]
609 )
610 custom_settings.enable()
611 old_stored_app_configs = apps.stored_app_configs
612 apps.stored_app_configs = []
613 try:
614 with patch.multiple(apps, ready=False, loading=False, app_configs={}):
615 with self.assertWarnsMessage(RuntimeWarning, self.expected_msg):
616 django.setup()
617
618 app_config = apps.get_app_config("query_performing_app")
619 return app_config.query_results
620 finally:
621 setattr(apps, "stored_app_configs", old_stored_app_configs)
622 custom_settings.disable()