tests.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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=SOME_INSTALLED_APPS)
  172. def test_clear_cache(self):
  173. # Set cache.
  174. self.assertIsNone(apps.get_swappable_settings_name("admin.LogEntry"))
  175. apps.get_models()
  176. apps.clear_cache()
  177. self.assertEqual(apps.get_swappable_settings_name.cache_info().currsize, 0)
  178. self.assertEqual(apps.get_models.cache_info().currsize, 0)
  179. @override_settings(INSTALLED_APPS=["apps.apps.RelabeledAppsConfig"])
  180. def test_relabeling(self):
  181. self.assertEqual(apps.get_app_config("relabeled").name, "apps")
  182. def test_duplicate_labels(self):
  183. with self.assertRaisesMessage(
  184. ImproperlyConfigured, "Application labels aren't unique"
  185. ):
  186. with self.settings(INSTALLED_APPS=["apps.apps.PlainAppsConfig", "apps"]):
  187. pass
  188. def test_duplicate_names(self):
  189. with self.assertRaisesMessage(
  190. ImproperlyConfigured, "Application names aren't unique"
  191. ):
  192. with self.settings(
  193. INSTALLED_APPS=["apps.apps.RelabeledAppsConfig", "apps"]
  194. ):
  195. pass
  196. def test_import_exception_is_not_masked(self):
  197. """
  198. App discovery should preserve stack traces. Regression test for #22920.
  199. """
  200. with self.assertRaisesMessage(ImportError, "Oops"):
  201. with self.settings(INSTALLED_APPS=["import_error_package"]):
  202. pass
  203. def test_models_py(self):
  204. """
  205. The models in the models.py file were loaded correctly.
  206. """
  207. self.assertEqual(apps.get_model("apps", "TotallyNormal"), TotallyNormal)
  208. with self.assertRaises(LookupError):
  209. apps.get_model("apps", "SoAlternative")
  210. with self.assertRaises(LookupError):
  211. new_apps.get_model("apps", "TotallyNormal")
  212. self.assertEqual(new_apps.get_model("apps", "SoAlternative"), SoAlternative)
  213. def test_models_not_loaded(self):
  214. """
  215. apps.get_models() raises an exception if apps.models_ready isn't True.
  216. """
  217. apps.models_ready = False
  218. try:
  219. # The cache must be cleared to trigger the exception.
  220. apps.get_models.cache_clear()
  221. with self.assertRaisesMessage(
  222. AppRegistryNotReady, "Models aren't loaded yet."
  223. ):
  224. apps.get_models()
  225. finally:
  226. apps.models_ready = True
  227. def test_dynamic_load(self):
  228. """
  229. Makes a new model at runtime and ensures it goes into the right place.
  230. """
  231. old_models = list(apps.get_app_config("apps").get_models())
  232. # Construct a new model in a new app registry
  233. body = {}
  234. new_apps = Apps(["apps"])
  235. meta_contents = {
  236. "app_label": "apps",
  237. "apps": new_apps,
  238. }
  239. meta = type("Meta", (), meta_contents)
  240. body["Meta"] = meta
  241. body["__module__"] = TotallyNormal.__module__
  242. temp_model = type("SouthPonies", (models.Model,), body)
  243. # Make sure it appeared in the right place!
  244. self.assertEqual(list(apps.get_app_config("apps").get_models()), old_models)
  245. with self.assertRaises(LookupError):
  246. apps.get_model("apps", "SouthPonies")
  247. self.assertEqual(new_apps.get_model("apps", "SouthPonies"), temp_model)
  248. def test_model_clash(self):
  249. """
  250. Test for behavior when two models clash in the app registry.
  251. """
  252. new_apps = Apps(["apps"])
  253. meta_contents = {
  254. "app_label": "apps",
  255. "apps": new_apps,
  256. }
  257. body = {}
  258. body["Meta"] = type("Meta", (), meta_contents)
  259. body["__module__"] = TotallyNormal.__module__
  260. type("SouthPonies", (models.Model,), body)
  261. # When __name__ and __module__ match we assume the module
  262. # was reloaded and issue a warning. This use-case is
  263. # useful for REPL. Refs #23621.
  264. body = {}
  265. body["Meta"] = type("Meta", (), meta_contents)
  266. body["__module__"] = TotallyNormal.__module__
  267. msg = (
  268. "Model 'apps.southponies' was already registered. "
  269. "Reloading models is not advised as it can lead to inconsistencies, "
  270. "most notably with related models."
  271. )
  272. with self.assertRaisesMessage(RuntimeWarning, msg):
  273. type("SouthPonies", (models.Model,), body)
  274. # If it doesn't appear to be a reloaded module then we expect
  275. # a RuntimeError.
  276. body = {}
  277. body["Meta"] = type("Meta", (), meta_contents)
  278. body["__module__"] = TotallyNormal.__module__ + ".whatever"
  279. with self.assertRaisesMessage(
  280. RuntimeError, "Conflicting 'southponies' models in application 'apps':"
  281. ):
  282. type("SouthPonies", (models.Model,), body)
  283. def test_get_containing_app_config_apps_not_ready(self):
  284. """
  285. apps.get_containing_app_config() should raise an exception if
  286. apps.apps_ready isn't True.
  287. """
  288. apps.apps_ready = False
  289. try:
  290. with self.assertRaisesMessage(
  291. AppRegistryNotReady, "Apps aren't loaded yet"
  292. ):
  293. apps.get_containing_app_config("foo")
  294. finally:
  295. apps.apps_ready = True
  296. @isolate_apps("apps", kwarg_name="apps")
  297. def test_lazy_model_operation(self, apps):
  298. """
  299. Tests apps.lazy_model_operation().
  300. """
  301. model_classes = []
  302. initial_pending = set(apps._pending_operations)
  303. def test_func(*models):
  304. model_classes[:] = models
  305. class LazyA(models.Model):
  306. pass
  307. # Test models appearing twice, and models appearing consecutively
  308. model_keys = [
  309. ("apps", model_name)
  310. for model_name in ["lazya", "lazyb", "lazyb", "lazyc", "lazya"]
  311. ]
  312. apps.lazy_model_operation(test_func, *model_keys)
  313. # LazyModelA shouldn't be waited on since it's already registered,
  314. # and LazyModelC shouldn't be waited on until LazyModelB exists.
  315. self.assertEqual(
  316. set(apps._pending_operations) - initial_pending, {("apps", "lazyb")}
  317. )
  318. # Multiple operations can wait on the same model
  319. apps.lazy_model_operation(test_func, ("apps", "lazyb"))
  320. class LazyB(models.Model):
  321. pass
  322. self.assertEqual(model_classes, [LazyB])
  323. # Now we are just waiting on LazyModelC.
  324. self.assertEqual(
  325. set(apps._pending_operations) - initial_pending, {("apps", "lazyc")}
  326. )
  327. class LazyC(models.Model):
  328. pass
  329. # Everything should be loaded - make sure the callback was executed properly.
  330. self.assertEqual(model_classes, [LazyA, LazyB, LazyB, LazyC, LazyA])
  331. class Stub:
  332. def __init__(self, **kwargs):
  333. self.__dict__.update(kwargs)
  334. class AppConfigTests(SimpleTestCase):
  335. """Unit tests for AppConfig class."""
  336. def test_path_set_explicitly(self):
  337. """If subclass sets path as class attr, no module attributes needed."""
  338. class MyAppConfig(AppConfig):
  339. path = "foo"
  340. ac = MyAppConfig("label", Stub())
  341. self.assertEqual(ac.path, "foo")
  342. def test_explicit_path_overrides(self):
  343. """If path set as class attr, overrides __path__ and __file__."""
  344. class MyAppConfig(AppConfig):
  345. path = "foo"
  346. ac = MyAppConfig("label", Stub(__path__=["a"], __file__="b/__init__.py"))
  347. self.assertEqual(ac.path, "foo")
  348. def test_dunder_path(self):
  349. """If single element in __path__, use it (in preference to __file__)."""
  350. ac = AppConfig("label", Stub(__path__=["a"], __file__="b/__init__.py"))
  351. self.assertEqual(ac.path, "a")
  352. def test_no_dunder_path_fallback_to_dunder_file(self):
  353. """If there is no __path__ attr, use __file__."""
  354. ac = AppConfig("label", Stub(__file__="b/__init__.py"))
  355. self.assertEqual(ac.path, "b")
  356. def test_empty_dunder_path_fallback_to_dunder_file(self):
  357. """If the __path__ attr is empty, use __file__ if set."""
  358. ac = AppConfig("label", Stub(__path__=[], __file__="b/__init__.py"))
  359. self.assertEqual(ac.path, "b")
  360. def test_multiple_dunder_path_fallback_to_dunder_file(self):
  361. """If the __path__ attr is length>1, use __file__ if set."""
  362. ac = AppConfig("label", Stub(__path__=["a", "b"], __file__="c/__init__.py"))
  363. self.assertEqual(ac.path, "c")
  364. def test_no_dunder_path_or_dunder_file(self):
  365. """If there is no __path__ or __file__, raise ImproperlyConfigured."""
  366. with self.assertRaises(ImproperlyConfigured):
  367. AppConfig("label", Stub())
  368. def test_empty_dunder_path_no_dunder_file(self):
  369. """If the __path__ attr is empty and there is no __file__, raise."""
  370. with self.assertRaises(ImproperlyConfigured):
  371. AppConfig("label", Stub(__path__=[]))
  372. def test_multiple_dunder_path_no_dunder_file(self):
  373. """If the __path__ attr is length>1 and there is no __file__, raise."""
  374. with self.assertRaises(ImproperlyConfigured):
  375. AppConfig("label", Stub(__path__=["a", "b"]))
  376. def test_duplicate_dunder_path_no_dunder_file(self):
  377. """
  378. If the __path__ attr contains duplicate paths and there is no
  379. __file__, they duplicates should be deduplicated (#25246).
  380. """
  381. ac = AppConfig("label", Stub(__path__=["a", "a"]))
  382. self.assertEqual(ac.path, "a")
  383. def test_repr(self):
  384. ac = AppConfig("label", Stub(__path__=["a"]))
  385. self.assertEqual(repr(ac), "<AppConfig: label>")
  386. def test_invalid_label(self):
  387. class MyAppConfig(AppConfig):
  388. label = "invalid.label"
  389. msg = "The app label 'invalid.label' is not a valid Python identifier."
  390. with self.assertRaisesMessage(ImproperlyConfigured, msg):
  391. MyAppConfig("test_app", Stub())
  392. @override_settings(
  393. INSTALLED_APPS=["apps.apps.ModelPKAppsConfig"],
  394. DEFAULT_AUTO_FIELD="django.db.models.SmallAutoField",
  395. )
  396. def test_app_default_auto_field(self):
  397. apps_config = apps.get_app_config("apps")
  398. self.assertEqual(
  399. apps_config.default_auto_field,
  400. "django.db.models.BigAutoField",
  401. )
  402. self.assertIs(apps_config._is_default_auto_field_overridden, True)
  403. @override_settings(
  404. INSTALLED_APPS=["apps.apps.PlainAppsConfig"],
  405. DEFAULT_AUTO_FIELD="django.db.models.SmallAutoField",
  406. )
  407. def test_default_auto_field_setting(self):
  408. apps_config = apps.get_app_config("apps")
  409. self.assertEqual(
  410. apps_config.default_auto_field,
  411. "django.db.models.SmallAutoField",
  412. )
  413. self.assertIs(apps_config._is_default_auto_field_overridden, False)
  414. class NamespacePackageAppTests(SimpleTestCase):
  415. # We need nsapp to be top-level so our multiple-paths tests can add another
  416. # location for it (if its inside a normal package with an __init__.py that
  417. # isn't possible). In order to avoid cluttering the already-full tests/ dir
  418. # (which is on sys.path), we add these new entries to sys.path temporarily.
  419. base_location = os.path.join(HERE, "namespace_package_base")
  420. other_location = os.path.join(HERE, "namespace_package_other_base")
  421. app_path = os.path.join(base_location, "nsapp")
  422. def test_single_path(self):
  423. """
  424. A Py3.3+ namespace package can be an app if it has only one path.
  425. """
  426. with extend_sys_path(self.base_location):
  427. with self.settings(INSTALLED_APPS=["nsapp"]):
  428. app_config = apps.get_app_config("nsapp")
  429. self.assertEqual(app_config.path, self.app_path)
  430. def test_multiple_paths(self):
  431. """
  432. A Py3.3+ namespace package with multiple locations cannot be an app.
  433. (Because then we wouldn't know where to load its templates, static
  434. assets, etc. from.)
  435. """
  436. # Temporarily add two directories to sys.path that both contain
  437. # components of the "nsapp" package.
  438. with extend_sys_path(self.base_location, self.other_location):
  439. with self.assertRaises(ImproperlyConfigured):
  440. with self.settings(INSTALLED_APPS=["nsapp"]):
  441. pass
  442. def test_multiple_paths_explicit_path(self):
  443. """
  444. Multiple locations are ok only if app-config has explicit path.
  445. """
  446. # Temporarily add two directories to sys.path that both contain
  447. # components of the "nsapp" package.
  448. with extend_sys_path(self.base_location, self.other_location):
  449. with self.settings(INSTALLED_APPS=["nsapp.apps.NSAppConfig"]):
  450. app_config = apps.get_app_config("nsapp")
  451. self.assertEqual(app_config.path, self.app_path)