tests.py 21 KB

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