tests.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. import os
  2. from django.apps import AppConfig, apps
  3. from django.apps.registry import Apps
  4. from django.contrib.admin.models import LogEntry
  5. from django.core.exceptions import AppRegistryNotReady, ImproperlyConfigured
  6. from django.db import models
  7. from django.test import SimpleTestCase, override_settings
  8. from django.test.utils import extend_sys_path, isolate_apps
  9. from .models import SoAlternative, TotallyNormal, new_apps
  10. from .one_config_app.apps import OneConfig
  11. from .two_configs_one_default_app.apps import TwoConfig
  12. # Small list with a variety of cases for tests that iterate on installed apps.
  13. # Intentionally not in alphabetical order to check if the order is preserved.
  14. SOME_INSTALLED_APPS = [
  15. "apps.apps.MyAdmin",
  16. "apps.apps.MyAuth",
  17. "django.contrib.contenttypes",
  18. "django.contrib.sessions",
  19. "django.contrib.messages",
  20. "django.contrib.staticfiles",
  21. ]
  22. SOME_INSTALLED_APPS_NAMES = [
  23. "django.contrib.admin",
  24. "django.contrib.auth",
  25. ] + SOME_INSTALLED_APPS[2:]
  26. HERE = os.path.dirname(__file__)
  27. class AppsTests(SimpleTestCase):
  28. def test_singleton_main(self):
  29. """
  30. Only one main registry can exist.
  31. """
  32. with self.assertRaises(RuntimeError):
  33. Apps(installed_apps=None)
  34. def test_ready(self):
  35. """
  36. Tests the ready property of the main registry.
  37. """
  38. # The main app registry is always ready when the tests run.
  39. self.assertIs(apps.ready, True)
  40. # Non-main app registries are populated in __init__.
  41. self.assertIs(Apps().ready, True)
  42. # The condition is set when apps are ready
  43. self.assertIs(apps.ready_event.is_set(), True)
  44. self.assertIs(Apps().ready_event.is_set(), True)
  45. def test_bad_app_config(self):
  46. """
  47. Tests when INSTALLED_APPS contains an incorrect app config.
  48. """
  49. msg = "'apps.apps.BadConfig' must supply a name attribute."
  50. with self.assertRaisesMessage(ImproperlyConfigured, msg):
  51. with self.settings(INSTALLED_APPS=["apps.apps.BadConfig"]):
  52. pass
  53. def test_not_an_app_config(self):
  54. """
  55. Tests when INSTALLED_APPS contains a class that isn't an app config.
  56. """
  57. msg = "'apps.apps.NotAConfig' isn't a subclass of AppConfig."
  58. with self.assertRaisesMessage(ImproperlyConfigured, msg):
  59. with self.settings(INSTALLED_APPS=["apps.apps.NotAConfig"]):
  60. pass
  61. def test_no_such_app(self):
  62. """
  63. Tests when INSTALLED_APPS contains an app that doesn't exist, either
  64. directly or via an app config.
  65. """
  66. with self.assertRaises(ImportError):
  67. with self.settings(INSTALLED_APPS=["there is no such app"]):
  68. pass
  69. msg = (
  70. "Cannot import 'there is no such app'. Check that "
  71. "'apps.apps.NoSuchApp.name' is correct."
  72. )
  73. with self.assertRaisesMessage(ImproperlyConfigured, msg):
  74. with self.settings(INSTALLED_APPS=["apps.apps.NoSuchApp"]):
  75. pass
  76. def test_no_such_app_config(self):
  77. msg = "Module 'apps' does not contain a 'NoSuchConfig' class."
  78. with self.assertRaisesMessage(ImportError, msg):
  79. with self.settings(INSTALLED_APPS=["apps.NoSuchConfig"]):
  80. pass
  81. def test_no_such_app_config_with_choices(self):
  82. msg = (
  83. "Module 'apps.apps' does not contain a 'NoSuchConfig' class. "
  84. "Choices are: 'BadConfig', 'ModelPKAppsConfig', 'MyAdmin', "
  85. "'MyAuth', 'NoSuchApp', 'PlainAppsConfig', 'RelabeledAppsConfig'."
  86. )
  87. with self.assertRaisesMessage(ImportError, msg):
  88. with self.settings(INSTALLED_APPS=["apps.apps.NoSuchConfig"]):
  89. pass
  90. def test_no_config_app(self):
  91. """Load an app that doesn't provide an AppConfig class."""
  92. with self.settings(INSTALLED_APPS=["apps.no_config_app"]):
  93. config = apps.get_app_config("no_config_app")
  94. self.assertIsInstance(config, AppConfig)
  95. def test_one_config_app(self):
  96. """Load an app that provides an AppConfig class."""
  97. with self.settings(INSTALLED_APPS=["apps.one_config_app"]):
  98. config = apps.get_app_config("one_config_app")
  99. self.assertIsInstance(config, OneConfig)
  100. def test_two_configs_app(self):
  101. """Load an app that provides two AppConfig classes."""
  102. with self.settings(INSTALLED_APPS=["apps.two_configs_app"]):
  103. config = apps.get_app_config("two_configs_app")
  104. self.assertIsInstance(config, AppConfig)
  105. def test_two_default_configs_app(self):
  106. """Load an app that provides two default AppConfig classes."""
  107. msg = (
  108. "'apps.two_default_configs_app.apps' declares more than one "
  109. "default AppConfig: 'TwoConfig', 'TwoConfigBis'."
  110. )
  111. with self.assertRaisesMessage(RuntimeError, msg):
  112. with self.settings(INSTALLED_APPS=["apps.two_default_configs_app"]):
  113. pass
  114. def test_two_configs_one_default_app(self):
  115. """
  116. Load an app that provides two AppConfig classes, one being the default.
  117. """
  118. with self.settings(INSTALLED_APPS=["apps.two_configs_one_default_app"]):
  119. config = apps.get_app_config("two_configs_one_default_app")
  120. self.assertIsInstance(config, TwoConfig)
  121. @override_settings(INSTALLED_APPS=SOME_INSTALLED_APPS)
  122. def test_get_app_configs(self):
  123. """
  124. Tests apps.get_app_configs().
  125. """
  126. app_configs = apps.get_app_configs()
  127. self.assertEqual(
  128. [app_config.name for app_config in app_configs], SOME_INSTALLED_APPS_NAMES
  129. )
  130. @override_settings(INSTALLED_APPS=SOME_INSTALLED_APPS)
  131. def test_get_app_config(self):
  132. """
  133. Tests apps.get_app_config().
  134. """
  135. app_config = apps.get_app_config("admin")
  136. self.assertEqual(app_config.name, "django.contrib.admin")
  137. app_config = apps.get_app_config("staticfiles")
  138. self.assertEqual(app_config.name, "django.contrib.staticfiles")
  139. with self.assertRaises(LookupError):
  140. apps.get_app_config("admindocs")
  141. msg = "No installed app with label 'django.contrib.auth'. Did you mean 'myauth'"
  142. with self.assertRaisesMessage(LookupError, msg):
  143. apps.get_app_config("django.contrib.auth")
  144. @override_settings(INSTALLED_APPS=SOME_INSTALLED_APPS)
  145. def test_is_installed(self):
  146. """
  147. Tests apps.is_installed().
  148. """
  149. self.assertIs(apps.is_installed("django.contrib.admin"), True)
  150. self.assertIs(apps.is_installed("django.contrib.auth"), True)
  151. self.assertIs(apps.is_installed("django.contrib.staticfiles"), True)
  152. self.assertIs(apps.is_installed("django.contrib.admindocs"), False)
  153. @override_settings(INSTALLED_APPS=SOME_INSTALLED_APPS)
  154. def test_get_model(self):
  155. """
  156. Tests apps.get_model().
  157. """
  158. self.assertEqual(apps.get_model("admin", "LogEntry"), LogEntry)
  159. with self.assertRaises(LookupError):
  160. apps.get_model("admin", "LogExit")
  161. # App label is case-sensitive, Model name is case-insensitive.
  162. self.assertEqual(apps.get_model("admin", "loGentrY"), LogEntry)
  163. with self.assertRaises(LookupError):
  164. apps.get_model("Admin", "LogEntry")
  165. # A single argument is accepted.
  166. self.assertEqual(apps.get_model("admin.LogEntry"), LogEntry)
  167. with self.assertRaises(LookupError):
  168. apps.get_model("admin.LogExit")
  169. with self.assertRaises(ValueError):
  170. apps.get_model("admin_LogEntry")
  171. @override_settings(INSTALLED_APPS=["apps.apps.RelabeledAppsConfig"])
  172. def test_relabeling(self):
  173. self.assertEqual(apps.get_app_config("relabeled").name, "apps")
  174. def test_duplicate_labels(self):
  175. with self.assertRaisesMessage(
  176. ImproperlyConfigured, "Application labels aren't unique"
  177. ):
  178. with self.settings(INSTALLED_APPS=["apps.apps.PlainAppsConfig", "apps"]):
  179. pass
  180. def test_duplicate_names(self):
  181. with self.assertRaisesMessage(
  182. ImproperlyConfigured, "Application names aren't unique"
  183. ):
  184. with self.settings(
  185. INSTALLED_APPS=["apps.apps.RelabeledAppsConfig", "apps"]
  186. ):
  187. pass
  188. def test_import_exception_is_not_masked(self):
  189. """
  190. App discovery should preserve stack traces. Regression test for #22920.
  191. """
  192. with self.assertRaisesMessage(ImportError, "Oops"):
  193. with self.settings(INSTALLED_APPS=["import_error_package"]):
  194. pass
  195. def test_models_py(self):
  196. """
  197. The models in the models.py file were loaded correctly.
  198. """
  199. self.assertEqual(apps.get_model("apps", "TotallyNormal"), TotallyNormal)
  200. with self.assertRaises(LookupError):
  201. apps.get_model("apps", "SoAlternative")
  202. with self.assertRaises(LookupError):
  203. new_apps.get_model("apps", "TotallyNormal")
  204. self.assertEqual(new_apps.get_model("apps", "SoAlternative"), SoAlternative)
  205. def test_models_not_loaded(self):
  206. """
  207. apps.get_models() raises an exception if apps.models_ready isn't True.
  208. """
  209. apps.models_ready = False
  210. try:
  211. # The cache must be cleared to trigger the exception.
  212. apps.get_models.cache_clear()
  213. with self.assertRaisesMessage(
  214. AppRegistryNotReady, "Models aren't loaded yet."
  215. ):
  216. apps.get_models()
  217. finally:
  218. apps.models_ready = True
  219. def test_dynamic_load(self):
  220. """
  221. Makes a new model at runtime and ensures it goes into the right place.
  222. """
  223. old_models = list(apps.get_app_config("apps").get_models())
  224. # Construct a new model in a new app registry
  225. body = {}
  226. new_apps = Apps(["apps"])
  227. meta_contents = {
  228. "app_label": "apps",
  229. "apps": new_apps,
  230. }
  231. meta = type("Meta", (), meta_contents)
  232. body["Meta"] = meta
  233. body["__module__"] = TotallyNormal.__module__
  234. temp_model = type("SouthPonies", (models.Model,), body)
  235. # Make sure it appeared in the right place!
  236. self.assertEqual(list(apps.get_app_config("apps").get_models()), old_models)
  237. with self.assertRaises(LookupError):
  238. apps.get_model("apps", "SouthPonies")
  239. self.assertEqual(new_apps.get_model("apps", "SouthPonies"), temp_model)
  240. def test_model_clash(self):
  241. """
  242. Test for behavior when two models clash in the app registry.
  243. """
  244. new_apps = Apps(["apps"])
  245. meta_contents = {
  246. "app_label": "apps",
  247. "apps": new_apps,
  248. }
  249. body = {}
  250. body["Meta"] = type("Meta", (), meta_contents)
  251. body["__module__"] = TotallyNormal.__module__
  252. type("SouthPonies", (models.Model,), body)
  253. # When __name__ and __module__ match we assume the module
  254. # was reloaded and issue a warning. This use-case is
  255. # useful for REPL. Refs #23621.
  256. body = {}
  257. body["Meta"] = type("Meta", (), meta_contents)
  258. body["__module__"] = TotallyNormal.__module__
  259. msg = (
  260. "Model 'apps.southponies' was already registered. "
  261. "Reloading models is not advised as it can lead to inconsistencies, "
  262. "most notably with related models."
  263. )
  264. with self.assertRaisesMessage(RuntimeWarning, msg):
  265. type("SouthPonies", (models.Model,), body)
  266. # If it doesn't appear to be a reloaded module then we expect
  267. # a RuntimeError.
  268. body = {}
  269. body["Meta"] = type("Meta", (), meta_contents)
  270. body["__module__"] = TotallyNormal.__module__ + ".whatever"
  271. with self.assertRaisesMessage(
  272. RuntimeError, "Conflicting 'southponies' models in application 'apps':"
  273. ):
  274. type("SouthPonies", (models.Model,), body)
  275. def test_get_containing_app_config_apps_not_ready(self):
  276. """
  277. apps.get_containing_app_config() should raise an exception if
  278. apps.apps_ready isn't True.
  279. """
  280. apps.apps_ready = False
  281. try:
  282. with self.assertRaisesMessage(
  283. AppRegistryNotReady, "Apps aren't loaded yet"
  284. ):
  285. apps.get_containing_app_config("foo")
  286. finally:
  287. apps.apps_ready = True
  288. @isolate_apps("apps", kwarg_name="apps")
  289. def test_lazy_model_operation(self, apps):
  290. """
  291. Tests apps.lazy_model_operation().
  292. """
  293. model_classes = []
  294. initial_pending = set(apps._pending_operations)
  295. def test_func(*models):
  296. model_classes[:] = models
  297. class LazyA(models.Model):
  298. pass
  299. # Test models appearing twice, and models appearing consecutively
  300. model_keys = [
  301. ("apps", model_name)
  302. for model_name in ["lazya", "lazyb", "lazyb", "lazyc", "lazya"]
  303. ]
  304. apps.lazy_model_operation(test_func, *model_keys)
  305. # LazyModelA shouldn't be waited on since it's already registered,
  306. # and LazyModelC shouldn't be waited on until LazyModelB exists.
  307. self.assertEqual(
  308. set(apps._pending_operations) - initial_pending, {("apps", "lazyb")}
  309. )
  310. # Multiple operations can wait on the same model
  311. apps.lazy_model_operation(test_func, ("apps", "lazyb"))
  312. class LazyB(models.Model):
  313. pass
  314. self.assertEqual(model_classes, [LazyB])
  315. # Now we are just waiting on LazyModelC.
  316. self.assertEqual(
  317. set(apps._pending_operations) - initial_pending, {("apps", "lazyc")}
  318. )
  319. class LazyC(models.Model):
  320. pass
  321. # Everything should be loaded - make sure the callback was executed properly.
  322. self.assertEqual(model_classes, [LazyA, LazyB, LazyB, LazyC, LazyA])
  323. class Stub:
  324. def __init__(self, **kwargs):
  325. self.__dict__.update(kwargs)
  326. class AppConfigTests(SimpleTestCase):
  327. """Unit tests for AppConfig class."""
  328. def test_path_set_explicitly(self):
  329. """If subclass sets path as class attr, no module attributes needed."""
  330. class MyAppConfig(AppConfig):
  331. path = "foo"
  332. ac = MyAppConfig("label", Stub())
  333. self.assertEqual(ac.path, "foo")
  334. def test_explicit_path_overrides(self):
  335. """If path set as class attr, overrides __path__ and __file__."""
  336. class MyAppConfig(AppConfig):
  337. path = "foo"
  338. ac = MyAppConfig("label", Stub(__path__=["a"], __file__="b/__init__.py"))
  339. self.assertEqual(ac.path, "foo")
  340. def test_dunder_path(self):
  341. """If single element in __path__, use it (in preference to __file__)."""
  342. ac = AppConfig("label", Stub(__path__=["a"], __file__="b/__init__.py"))
  343. self.assertEqual(ac.path, "a")
  344. def test_no_dunder_path_fallback_to_dunder_file(self):
  345. """If there is no __path__ attr, use __file__."""
  346. ac = AppConfig("label", Stub(__file__="b/__init__.py"))
  347. self.assertEqual(ac.path, "b")
  348. def test_empty_dunder_path_fallback_to_dunder_file(self):
  349. """If the __path__ attr is empty, use __file__ if set."""
  350. ac = AppConfig("label", Stub(__path__=[], __file__="b/__init__.py"))
  351. self.assertEqual(ac.path, "b")
  352. def test_multiple_dunder_path_fallback_to_dunder_file(self):
  353. """If the __path__ attr is length>1, use __file__ if set."""
  354. ac = AppConfig("label", Stub(__path__=["a", "b"], __file__="c/__init__.py"))
  355. self.assertEqual(ac.path, "c")
  356. def test_no_dunder_path_or_dunder_file(self):
  357. """If there is no __path__ or __file__, raise ImproperlyConfigured."""
  358. with self.assertRaises(ImproperlyConfigured):
  359. AppConfig("label", Stub())
  360. def test_empty_dunder_path_no_dunder_file(self):
  361. """If the __path__ attr is empty and there is no __file__, raise."""
  362. with self.assertRaises(ImproperlyConfigured):
  363. AppConfig("label", Stub(__path__=[]))
  364. def test_multiple_dunder_path_no_dunder_file(self):
  365. """If the __path__ attr is length>1 and there is no __file__, raise."""
  366. with self.assertRaises(ImproperlyConfigured):
  367. AppConfig("label", Stub(__path__=["a", "b"]))
  368. def test_duplicate_dunder_path_no_dunder_file(self):
  369. """
  370. If the __path__ attr contains duplicate paths and there is no
  371. __file__, they duplicates should be deduplicated (#25246).
  372. """
  373. ac = AppConfig("label", Stub(__path__=["a", "a"]))
  374. self.assertEqual(ac.path, "a")
  375. def test_repr(self):
  376. ac = AppConfig("label", Stub(__path__=["a"]))
  377. self.assertEqual(repr(ac), "<AppConfig: label>")
  378. def test_invalid_label(self):
  379. class MyAppConfig(AppConfig):
  380. label = "invalid.label"
  381. msg = "The app label 'invalid.label' is not a valid Python identifier."
  382. with self.assertRaisesMessage(ImproperlyConfigured, msg):
  383. MyAppConfig("test_app", Stub())
  384. @override_settings(
  385. INSTALLED_APPS=["apps.apps.ModelPKAppsConfig"],
  386. DEFAULT_AUTO_FIELD="django.db.models.SmallAutoField",
  387. )
  388. def test_app_default_auto_field(self):
  389. apps_config = apps.get_app_config("apps")
  390. self.assertEqual(
  391. apps_config.default_auto_field,
  392. "django.db.models.BigAutoField",
  393. )
  394. self.assertIs(apps_config._is_default_auto_field_overridden, True)
  395. @override_settings(
  396. INSTALLED_APPS=["apps.apps.PlainAppsConfig"],
  397. DEFAULT_AUTO_FIELD="django.db.models.SmallAutoField",
  398. )
  399. def test_default_auto_field_setting(self):
  400. apps_config = apps.get_app_config("apps")
  401. self.assertEqual(
  402. apps_config.default_auto_field,
  403. "django.db.models.SmallAutoField",
  404. )
  405. self.assertIs(apps_config._is_default_auto_field_overridden, False)
  406. class NamespacePackageAppTests(SimpleTestCase):
  407. # We need nsapp to be top-level so our multiple-paths tests can add another
  408. # location for it (if its inside a normal package with an __init__.py that
  409. # isn't possible). In order to avoid cluttering the already-full tests/ dir
  410. # (which is on sys.path), we add these new entries to sys.path temporarily.
  411. base_location = os.path.join(HERE, "namespace_package_base")
  412. other_location = os.path.join(HERE, "namespace_package_other_base")
  413. app_path = os.path.join(base_location, "nsapp")
  414. def test_single_path(self):
  415. """
  416. A Py3.3+ namespace package can be an app if it has only one path.
  417. """
  418. with extend_sys_path(self.base_location):
  419. with self.settings(INSTALLED_APPS=["nsapp"]):
  420. app_config = apps.get_app_config("nsapp")
  421. self.assertEqual(app_config.path, self.app_path)
  422. def test_multiple_paths(self):
  423. """
  424. A Py3.3+ namespace package with multiple locations cannot be an app.
  425. (Because then we wouldn't know where to load its templates, static
  426. assets, etc. from.)
  427. """
  428. # Temporarily add two directories to sys.path that both contain
  429. # components of the "nsapp" package.
  430. with extend_sys_path(self.base_location, self.other_location):
  431. with self.assertRaises(ImproperlyConfigured):
  432. with self.settings(INSTALLED_APPS=["nsapp"]):
  433. pass
  434. def test_multiple_paths_explicit_path(self):
  435. """
  436. Multiple locations are ok only if app-config has explicit path.
  437. """
  438. # Temporarily add two directories to sys.path that both contain
  439. # components of the "nsapp" package.
  440. with extend_sys_path(self.base_location, self.other_location):
  441. with self.settings(INSTALLED_APPS=["nsapp.apps.NSAppConfig"]):
  442. app_config = apps.get_app_config("nsapp")
  443. self.assertEqual(app_config.path, self.app_path)