tests.py 23 KB

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