tests.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. from __future__ import unicode_literals
  2. import os
  3. import warnings
  4. from unittest import skipUnless
  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 models
  10. from django.test import SimpleTestCase, override_settings
  11. from django.test.utils import extend_sys_path
  12. from django.utils import six
  13. from django.utils._os import upath
  14. from .default_config_app.apps import CustomConfig
  15. from .models import SoAlternative, TotallyNormal, new_apps
  16. # Small list with a variety of cases for tests that iterate on installed apps.
  17. # Intentionally not in alphabetical order to check if the order is preserved.
  18. SOME_INSTALLED_APPS = [
  19. 'apps.apps.MyAdmin',
  20. 'apps.apps.MyAuth',
  21. 'django.contrib.contenttypes',
  22. 'django.contrib.sessions',
  23. 'django.contrib.messages',
  24. 'django.contrib.staticfiles',
  25. ]
  26. SOME_INSTALLED_APPS_NAMES = [
  27. 'django.contrib.admin',
  28. 'django.contrib.auth',
  29. ] + SOME_INSTALLED_APPS[2:]
  30. HERE = os.path.dirname(upath(__file__))
  31. class AppsTests(SimpleTestCase):
  32. def test_singleton_master(self):
  33. """
  34. Ensures that only one master registry can exist.
  35. """
  36. with self.assertRaises(RuntimeError):
  37. Apps(installed_apps=None)
  38. def test_ready(self):
  39. """
  40. Tests the ready property of the master registry.
  41. """
  42. # The master app registry is always ready when the tests run.
  43. self.assertTrue(apps.ready)
  44. # Non-master app registries are populated in __init__.
  45. self.assertTrue(Apps().ready)
  46. def test_bad_app_config(self):
  47. """
  48. Tests when INSTALLED_APPS contains an incorrect app config.
  49. """
  50. with self.assertRaises(ImproperlyConfigured):
  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. with self.assertRaises(ImproperlyConfigured):
  58. with self.settings(INSTALLED_APPS=['apps.apps.NotAConfig']):
  59. pass
  60. def test_no_such_app(self):
  61. """
  62. Tests when INSTALLED_APPS contains an app that doesn't exist, either
  63. directly or via an app config.
  64. """
  65. with self.assertRaises(ImportError):
  66. with self.settings(INSTALLED_APPS=['there is no such app']):
  67. pass
  68. with self.assertRaises(ImportError):
  69. with self.settings(INSTALLED_APPS=['apps.apps.NoSuchApp']):
  70. pass
  71. def test_no_such_app_config(self):
  72. """
  73. Tests when INSTALLED_APPS contains an entry that doesn't exist.
  74. """
  75. with self.assertRaises(ImportError):
  76. with self.settings(INSTALLED_APPS=['apps.apps.NoSuchConfig']):
  77. pass
  78. def test_default_app_config(self):
  79. with self.settings(INSTALLED_APPS=['apps.default_config_app']):
  80. config = apps.get_app_config('default_config_app')
  81. self.assertIsInstance(config, CustomConfig)
  82. @override_settings(INSTALLED_APPS=SOME_INSTALLED_APPS)
  83. def test_get_app_configs(self):
  84. """
  85. Tests apps.get_app_configs().
  86. """
  87. app_configs = apps.get_app_configs()
  88. self.assertListEqual(
  89. [app_config.name for app_config in app_configs],
  90. SOME_INSTALLED_APPS_NAMES)
  91. @override_settings(INSTALLED_APPS=SOME_INSTALLED_APPS)
  92. def test_get_app_config(self):
  93. """
  94. Tests apps.get_app_config().
  95. """
  96. app_config = apps.get_app_config('admin')
  97. self.assertEqual(app_config.name, 'django.contrib.admin')
  98. app_config = apps.get_app_config('staticfiles')
  99. self.assertEqual(app_config.name, 'django.contrib.staticfiles')
  100. with self.assertRaises(LookupError):
  101. apps.get_app_config('webdesign')
  102. msg = "No installed app with label 'django.contrib.auth'. Did you mean 'myauth'"
  103. with self.assertRaisesMessage(LookupError, msg):
  104. apps.get_app_config('django.contrib.auth')
  105. @override_settings(INSTALLED_APPS=SOME_INSTALLED_APPS)
  106. def test_is_installed(self):
  107. """
  108. Tests apps.is_installed().
  109. """
  110. self.assertTrue(apps.is_installed('django.contrib.admin'))
  111. self.assertTrue(apps.is_installed('django.contrib.auth'))
  112. self.assertTrue(apps.is_installed('django.contrib.staticfiles'))
  113. self.assertFalse(apps.is_installed('django.contrib.webdesign'))
  114. @override_settings(INSTALLED_APPS=SOME_INSTALLED_APPS)
  115. def test_get_model(self):
  116. """
  117. Tests apps.get_model().
  118. """
  119. self.assertEqual(apps.get_model('admin', 'LogEntry'), LogEntry)
  120. with self.assertRaises(LookupError):
  121. apps.get_model('admin', 'LogExit')
  122. # App label is case-sensitive, Model name is case-insensitive.
  123. self.assertEqual(apps.get_model('admin', 'loGentrY'), LogEntry)
  124. with self.assertRaises(LookupError):
  125. apps.get_model('Admin', 'LogEntry')
  126. # A single argument is accepted.
  127. self.assertEqual(apps.get_model('admin.LogEntry'), LogEntry)
  128. with self.assertRaises(LookupError):
  129. apps.get_model('admin.LogExit')
  130. with self.assertRaises(ValueError):
  131. apps.get_model('admin_LogEntry')
  132. @override_settings(INSTALLED_APPS=['apps.apps.RelabeledAppsConfig'])
  133. def test_relabeling(self):
  134. self.assertEqual(apps.get_app_config('relabeled').name, 'apps')
  135. def test_duplicate_labels(self):
  136. with six.assertRaisesRegex(self, ImproperlyConfigured, "Application labels aren't unique"):
  137. with self.settings(INSTALLED_APPS=['apps.apps.PlainAppsConfig', 'apps']):
  138. pass
  139. def test_duplicate_names(self):
  140. with six.assertRaisesRegex(self, ImproperlyConfigured, "Application names aren't unique"):
  141. with self.settings(INSTALLED_APPS=['apps.apps.RelabeledAppsConfig', 'apps']):
  142. pass
  143. def test_import_exception_is_not_masked(self):
  144. """
  145. App discovery should preserve stack traces. Regression test for #22920.
  146. """
  147. with six.assertRaisesRegex(self, ImportError, "Oops"):
  148. with self.settings(INSTALLED_APPS=['import_error_package']):
  149. pass
  150. def test_models_py(self):
  151. """
  152. Tests that the models in the models.py file were loaded correctly.
  153. """
  154. self.assertEqual(apps.get_model("apps", "TotallyNormal"), TotallyNormal)
  155. with self.assertRaises(LookupError):
  156. apps.get_model("apps", "SoAlternative")
  157. with self.assertRaises(LookupError):
  158. new_apps.get_model("apps", "TotallyNormal")
  159. self.assertEqual(new_apps.get_model("apps", "SoAlternative"), SoAlternative)
  160. def test_dynamic_load(self):
  161. """
  162. Makes a new model at runtime and ensures it goes into the right place.
  163. """
  164. old_models = list(apps.get_app_config("apps").get_models())
  165. # Construct a new model in a new app registry
  166. body = {}
  167. new_apps = Apps(["apps"])
  168. meta_contents = {
  169. 'app_label': "apps",
  170. 'apps': new_apps,
  171. }
  172. meta = type(str("Meta"), tuple(), meta_contents)
  173. body['Meta'] = meta
  174. body['__module__'] = TotallyNormal.__module__
  175. temp_model = type(str("SouthPonies"), (models.Model,), body)
  176. # Make sure it appeared in the right place!
  177. self.assertListEqual(list(apps.get_app_config("apps").get_models()), old_models)
  178. with self.assertRaises(LookupError):
  179. apps.get_model("apps", "SouthPonies")
  180. self.assertEqual(new_apps.get_model("apps", "SouthPonies"), temp_model)
  181. def test_model_clash(self):
  182. """
  183. Test for behavior when two models clash in the app registry.
  184. """
  185. new_apps = Apps(["apps"])
  186. meta_contents = {
  187. 'app_label': "apps",
  188. 'apps': new_apps,
  189. }
  190. body = {}
  191. body['Meta'] = type(str("Meta"), tuple(), meta_contents)
  192. body['__module__'] = TotallyNormal.__module__
  193. type(str("SouthPonies"), (models.Model,), body)
  194. # When __name__ and __module__ match we assume the module
  195. # was reloaded and issue a warning. This use-case is
  196. # useful for REPL. Refs #23621.
  197. body = {}
  198. body['Meta'] = type(str("Meta"), tuple(), meta_contents)
  199. body['__module__'] = TotallyNormal.__module__
  200. with warnings.catch_warnings(record=True) as w:
  201. type(str("SouthPonies"), (models.Model,), body)
  202. self.assertEqual(len(w), 1)
  203. self.assertTrue(issubclass(w[-1].category, RuntimeWarning))
  204. self.assertEqual(str(w[-1].message),
  205. "Model 'southponies.apps' was already registered. "
  206. "Reloading models is not advised as it can lead to inconsistencies, "
  207. "most notably with related models.")
  208. # If it doesn't appear to be a reloaded module then we expect
  209. # a RuntimeError.
  210. body = {}
  211. body['Meta'] = type(str("Meta"), tuple(), meta_contents)
  212. body['__module__'] = TotallyNormal.__module__ + '.whatever'
  213. with six.assertRaisesRegex(self, RuntimeError,
  214. "Conflicting 'southponies' models in application 'apps':.*"):
  215. type(str("SouthPonies"), (models.Model,), body)
  216. def test_get_containing_app_config_apps_not_ready(self):
  217. """
  218. apps.get_containing_app_config() should raise an exception if
  219. apps.apps_ready isn't True.
  220. """
  221. apps.apps_ready = False
  222. try:
  223. with self.assertRaisesMessage(AppRegistryNotReady, "Apps aren't loaded yet"):
  224. apps.get_containing_app_config('foo')
  225. finally:
  226. apps.apps_ready = True
  227. def test_lazy_model_operation(self):
  228. """
  229. Tests apps.lazy_model_operation().
  230. """
  231. model_classes = []
  232. initial_pending = set(apps._pending_operations)
  233. def test_func(*models):
  234. model_classes[:] = models
  235. class LazyA(models.Model):
  236. pass
  237. # Test models appearing twice, and models appearing consecutively
  238. model_keys = [('apps', model_name) for model_name in ['lazya', 'lazyb', 'lazyb', 'lazyc', 'lazya']]
  239. apps.lazy_model_operation(test_func, *model_keys)
  240. # LazyModelA shouldn't be waited on since it's already registered,
  241. # and LazyModelC shouldn't be waited on until LazyModelB exists.
  242. self.assertSetEqual(set(apps._pending_operations) - initial_pending, {('apps', 'lazyb')})
  243. # Test that multiple operations can wait on the same model
  244. apps.lazy_model_operation(test_func, ('apps', 'lazyb'))
  245. class LazyB(models.Model):
  246. pass
  247. self.assertListEqual(model_classes, [LazyB])
  248. # Now we are just waiting on LazyModelC.
  249. self.assertSetEqual(set(apps._pending_operations) - initial_pending, {('apps', 'lazyc')})
  250. class LazyC(models.Model):
  251. pass
  252. # Everything should be loaded - make sure the callback was executed properly.
  253. self.assertListEqual(model_classes, [LazyA, LazyB, LazyB, LazyC, LazyA])
  254. class Stub(object):
  255. def __init__(self, **kwargs):
  256. self.__dict__.update(kwargs)
  257. class AppConfigTests(SimpleTestCase):
  258. """Unit tests for AppConfig class."""
  259. def test_path_set_explicitly(self):
  260. """If subclass sets path as class attr, no module attributes needed."""
  261. class MyAppConfig(AppConfig):
  262. path = 'foo'
  263. ac = MyAppConfig('label', Stub())
  264. self.assertEqual(ac.path, 'foo')
  265. def test_explicit_path_overrides(self):
  266. """If path set as class attr, overrides __path__ and __file__."""
  267. class MyAppConfig(AppConfig):
  268. path = 'foo'
  269. ac = MyAppConfig('label', Stub(__path__=['a'], __file__='b/__init__.py'))
  270. self.assertEqual(ac.path, 'foo')
  271. def test_dunder_path(self):
  272. """If single element in __path__, use it (in preference to __file__)."""
  273. ac = AppConfig('label', Stub(__path__=['a'], __file__='b/__init__.py'))
  274. self.assertEqual(ac.path, 'a')
  275. def test_no_dunder_path_fallback_to_dunder_file(self):
  276. """If there is no __path__ attr, use __file__."""
  277. ac = AppConfig('label', Stub(__file__='b/__init__.py'))
  278. self.assertEqual(ac.path, 'b')
  279. def test_empty_dunder_path_fallback_to_dunder_file(self):
  280. """If the __path__ attr is empty, use __file__ if set."""
  281. ac = AppConfig('label', Stub(__path__=[], __file__='b/__init__.py'))
  282. self.assertEqual(ac.path, 'b')
  283. def test_multiple_dunder_path_fallback_to_dunder_file(self):
  284. """If the __path__ attr is length>1, use __file__ if set."""
  285. ac = AppConfig('label', Stub(__path__=['a', 'b'], __file__='c/__init__.py'))
  286. self.assertEqual(ac.path, 'c')
  287. def test_no_dunder_path_or_dunder_file(self):
  288. """If there is no __path__ or __file__, raise ImproperlyConfigured."""
  289. with self.assertRaises(ImproperlyConfigured):
  290. AppConfig('label', Stub())
  291. def test_empty_dunder_path_no_dunder_file(self):
  292. """If the __path__ attr is empty and there is no __file__, raise."""
  293. with self.assertRaises(ImproperlyConfigured):
  294. AppConfig('label', Stub(__path__=[]))
  295. def test_multiple_dunder_path_no_dunder_file(self):
  296. """If the __path__ attr is length>1 and there is no __file__, raise."""
  297. with self.assertRaises(ImproperlyConfigured):
  298. AppConfig('label', Stub(__path__=['a', 'b']))
  299. @skipUnless(six.PY3, "Namespace packages sans __init__.py were added in Python 3.3")
  300. class NamespacePackageAppTests(SimpleTestCase):
  301. # We need nsapp to be top-level so our multiple-paths tests can add another
  302. # location for it (if its inside a normal package with an __init__.py that
  303. # isn't possible). In order to avoid cluttering the already-full tests/ dir
  304. # (which is on sys.path), we add these new entries to sys.path temporarily.
  305. base_location = os.path.join(HERE, 'namespace_package_base')
  306. other_location = os.path.join(HERE, 'namespace_package_other_base')
  307. app_path = os.path.join(base_location, 'nsapp')
  308. def test_single_path(self):
  309. """
  310. A Py3.3+ namespace package can be an app if it has only one path.
  311. """
  312. with extend_sys_path(self.base_location):
  313. with self.settings(INSTALLED_APPS=['nsapp']):
  314. app_config = apps.get_app_config('nsapp')
  315. self.assertEqual(app_config.path, upath(self.app_path))
  316. def test_multiple_paths(self):
  317. """
  318. A Py3.3+ namespace package with multiple locations cannot be an app.
  319. (Because then we wouldn't know where to load its templates, static
  320. assets, etc from.)
  321. """
  322. # Temporarily add two directories to sys.path that both contain
  323. # components of the "nsapp" package.
  324. with extend_sys_path(self.base_location, self.other_location):
  325. with self.assertRaises(ImproperlyConfigured):
  326. with self.settings(INSTALLED_APPS=['nsapp']):
  327. pass
  328. def test_multiple_paths_explicit_path(self):
  329. """
  330. Multiple locations are ok only if app-config has explicit path.
  331. """
  332. # Temporarily add two directories to sys.path that both contain
  333. # components of the "nsapp" package.
  334. with extend_sys_path(self.base_location, self.other_location):
  335. with self.settings(INSTALLED_APPS=['nsapp.apps.NSAppConfig']):
  336. app_config = apps.get_app_config('nsapp')
  337. self.assertEqual(app_config.path, upath(self.app_path))