tests.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. import os
  2. import sys
  3. from types import ModuleType
  4. import unittest
  5. import warnings
  6. from django.conf import LazySettings, Settings, settings
  7. from django.core.exceptions import ImproperlyConfigured
  8. from django.http import HttpRequest
  9. from django.test import (SimpleTestCase, TransactionTestCase, TestCase,
  10. modify_settings, override_settings, signals)
  11. from django.utils import six
  12. @modify_settings(ITEMS={
  13. 'prepend': ['b'],
  14. 'append': ['d'],
  15. 'remove': ['a', 'e']
  16. })
  17. @override_settings(ITEMS=['a', 'c', 'e'], ITEMS_OUTER=[1, 2, 3],
  18. TEST='override', TEST_OUTER='outer')
  19. class FullyDecoratedTranTestCase(TransactionTestCase):
  20. available_apps = []
  21. def test_override(self):
  22. self.assertListEqual(settings.ITEMS, ['b', 'c', 'd'])
  23. self.assertListEqual(settings.ITEMS_OUTER, [1, 2, 3])
  24. self.assertEqual(settings.TEST, 'override')
  25. self.assertEqual(settings.TEST_OUTER, 'outer')
  26. @modify_settings(ITEMS={
  27. 'append': ['e', 'f'],
  28. 'prepend': ['a'],
  29. 'remove': ['d', 'c'],
  30. })
  31. def test_method_list_override(self):
  32. self.assertListEqual(settings.ITEMS, ['a', 'b', 'e', 'f'])
  33. self.assertListEqual(settings.ITEMS_OUTER, [1, 2, 3])
  34. @modify_settings(ITEMS={
  35. 'append': ['b'],
  36. 'prepend': ['d'],
  37. 'remove': ['a', 'c', 'e'],
  38. })
  39. def test_method_list_override_no_ops(self):
  40. self.assertListEqual(settings.ITEMS, ['b', 'd'])
  41. @modify_settings(ITEMS={
  42. 'append': 'e',
  43. 'prepend': 'a',
  44. 'remove': 'c',
  45. })
  46. def test_method_list_override_strings(self):
  47. self.assertListEqual(settings.ITEMS, ['a', 'b', 'd', 'e'])
  48. @modify_settings(ITEMS={'remove': ['b', 'd']})
  49. @modify_settings(ITEMS={'append': ['b'], 'prepend': ['d']})
  50. def test_method_list_override_nested_order(self):
  51. self.assertListEqual(settings.ITEMS, ['d', 'c', 'b'])
  52. @override_settings(TEST='override2')
  53. def test_method_override(self):
  54. self.assertEqual(settings.TEST, 'override2')
  55. self.assertEqual(settings.TEST_OUTER, 'outer')
  56. def test_decorated_testcase_name(self):
  57. self.assertEqual(FullyDecoratedTranTestCase.__name__, 'FullyDecoratedTranTestCase')
  58. def test_decorated_testcase_module(self):
  59. self.assertEqual(FullyDecoratedTranTestCase.__module__, __name__)
  60. @modify_settings(ITEMS={
  61. 'prepend': ['b'],
  62. 'append': ['d'],
  63. 'remove': ['a', 'e']
  64. })
  65. @override_settings(ITEMS=['a', 'c', 'e'], TEST='override')
  66. class FullyDecoratedTestCase(TestCase):
  67. def test_override(self):
  68. self.assertListEqual(settings.ITEMS, ['b', 'c', 'd'])
  69. self.assertEqual(settings.TEST, 'override')
  70. @modify_settings(ITEMS={
  71. 'append': 'e',
  72. 'prepend': 'a',
  73. 'remove': 'c',
  74. })
  75. @override_settings(TEST='override2')
  76. def test_method_override(self):
  77. self.assertListEqual(settings.ITEMS, ['a', 'b', 'd', 'e'])
  78. self.assertEqual(settings.TEST, 'override2')
  79. class ClassDecoratedTestCaseSuper(TestCase):
  80. """
  81. Dummy class for testing max recursion error in child class call to
  82. super(). Refs #17011.
  83. """
  84. def test_max_recursion_error(self):
  85. pass
  86. @override_settings(TEST='override')
  87. class ClassDecoratedTestCase(ClassDecoratedTestCaseSuper):
  88. def test_override(self):
  89. self.assertEqual(settings.TEST, 'override')
  90. @override_settings(TEST='override2')
  91. def test_method_override(self):
  92. self.assertEqual(settings.TEST, 'override2')
  93. def test_max_recursion_error(self):
  94. """
  95. Overriding a method on a super class and then calling that method on
  96. the super class should not trigger infinite recursion. See #17011.
  97. """
  98. try:
  99. super(ClassDecoratedTestCase, self).test_max_recursion_error()
  100. except RuntimeError:
  101. self.fail()
  102. @modify_settings(ITEMS={'append': 'mother'})
  103. @override_settings(ITEMS=['father'], TEST='override-parent')
  104. class ParentDecoratedTestCase(TestCase):
  105. pass
  106. @modify_settings(ITEMS={'append': ['child']})
  107. @override_settings(TEST='override-child')
  108. class ChildDecoratedTestCase(ParentDecoratedTestCase):
  109. def test_override_settings_inheritance(self):
  110. self.assertEqual(settings.ITEMS, ['father', 'mother', 'child'])
  111. self.assertEqual(settings.TEST, 'override-child')
  112. class SettingsTests(TestCase):
  113. def setUp(self):
  114. self.testvalue = None
  115. signals.setting_changed.connect(self.signal_callback)
  116. def tearDown(self):
  117. signals.setting_changed.disconnect(self.signal_callback)
  118. def signal_callback(self, sender, setting, value, **kwargs):
  119. if setting == 'TEST':
  120. self.testvalue = value
  121. def test_override(self):
  122. settings.TEST = 'test'
  123. self.assertEqual('test', settings.TEST)
  124. with self.settings(TEST='override'):
  125. self.assertEqual('override', settings.TEST)
  126. self.assertEqual('test', settings.TEST)
  127. del settings.TEST
  128. def test_override_change(self):
  129. settings.TEST = 'test'
  130. self.assertEqual('test', settings.TEST)
  131. with self.settings(TEST='override'):
  132. self.assertEqual('override', settings.TEST)
  133. settings.TEST = 'test2'
  134. self.assertEqual('test', settings.TEST)
  135. del settings.TEST
  136. def test_override_doesnt_leak(self):
  137. self.assertRaises(AttributeError, getattr, settings, 'TEST')
  138. with self.settings(TEST='override'):
  139. self.assertEqual('override', settings.TEST)
  140. settings.TEST = 'test'
  141. self.assertRaises(AttributeError, getattr, settings, 'TEST')
  142. @override_settings(TEST='override')
  143. def test_decorator(self):
  144. self.assertEqual('override', settings.TEST)
  145. def test_context_manager(self):
  146. self.assertRaises(AttributeError, getattr, settings, 'TEST')
  147. override = override_settings(TEST='override')
  148. self.assertRaises(AttributeError, getattr, settings, 'TEST')
  149. override.enable()
  150. self.assertEqual('override', settings.TEST)
  151. override.disable()
  152. self.assertRaises(AttributeError, getattr, settings, 'TEST')
  153. def test_class_decorator(self):
  154. # SimpleTestCase can be decorated by override_settings, but not ut.TestCase
  155. class SimpleTestCaseSubclass(SimpleTestCase):
  156. pass
  157. class UnittestTestCaseSubclass(unittest.TestCase):
  158. pass
  159. decorated = override_settings(TEST='override')(SimpleTestCaseSubclass)
  160. self.assertIsInstance(decorated, type)
  161. self.assertTrue(issubclass(decorated, SimpleTestCase))
  162. with six.assertRaisesRegex(self, Exception,
  163. "Only subclasses of Django SimpleTestCase*"):
  164. decorated = override_settings(TEST='override')(UnittestTestCaseSubclass)
  165. def test_signal_callback_context_manager(self):
  166. self.assertRaises(AttributeError, getattr, settings, 'TEST')
  167. with self.settings(TEST='override'):
  168. self.assertEqual(self.testvalue, 'override')
  169. self.assertEqual(self.testvalue, None)
  170. @override_settings(TEST='override')
  171. def test_signal_callback_decorator(self):
  172. self.assertEqual(self.testvalue, 'override')
  173. #
  174. # Regression tests for #10130: deleting settings.
  175. #
  176. def test_settings_delete(self):
  177. settings.TEST = 'test'
  178. self.assertEqual('test', settings.TEST)
  179. del settings.TEST
  180. self.assertRaises(AttributeError, getattr, settings, 'TEST')
  181. def test_settings_delete_wrapped(self):
  182. self.assertRaises(TypeError, delattr, settings, '_wrapped')
  183. def test_override_settings_delete(self):
  184. """
  185. Allow deletion of a setting in an overridden settings set (#18824)
  186. """
  187. previous_i18n = settings.USE_I18N
  188. previous_l10n = settings.USE_L10N
  189. with self.settings(USE_I18N=False):
  190. del settings.USE_I18N
  191. self.assertRaises(AttributeError, getattr, settings, 'USE_I18N')
  192. # Should also work for a non-overridden setting
  193. del settings.USE_L10N
  194. self.assertRaises(AttributeError, getattr, settings, 'USE_L10N')
  195. self.assertEqual(settings.USE_I18N, previous_i18n)
  196. self.assertEqual(settings.USE_L10N, previous_l10n)
  197. def test_override_settings_nested(self):
  198. """
  199. Test that override_settings uses the actual _wrapped attribute at
  200. runtime, not when it was instantiated.
  201. """
  202. self.assertRaises(AttributeError, getattr, settings, 'TEST')
  203. self.assertRaises(AttributeError, getattr, settings, 'TEST2')
  204. inner = override_settings(TEST2='override')
  205. with override_settings(TEST='override'):
  206. self.assertEqual('override', settings.TEST)
  207. with inner:
  208. self.assertEqual('override', settings.TEST)
  209. self.assertEqual('override', settings.TEST2)
  210. # inner's __exit__ should have restored the settings of the outer
  211. # context manager, not those when the class was instantiated
  212. self.assertEqual('override', settings.TEST)
  213. self.assertRaises(AttributeError, getattr, settings, 'TEST2')
  214. self.assertRaises(AttributeError, getattr, settings, 'TEST')
  215. self.assertRaises(AttributeError, getattr, settings, 'TEST2')
  216. def test_allowed_include_roots_string(self):
  217. """
  218. ALLOWED_INCLUDE_ROOTS is not allowed to be incorrectly set to a string
  219. rather than a tuple.
  220. """
  221. self.assertRaises(ValueError, setattr, settings,
  222. 'ALLOWED_INCLUDE_ROOTS', '/var/www/ssi/')
  223. class TestComplexSettingOverride(TestCase):
  224. def setUp(self):
  225. self.old_warn_override_settings = signals.COMPLEX_OVERRIDE_SETTINGS.copy()
  226. signals.COMPLEX_OVERRIDE_SETTINGS.add('TEST_WARN')
  227. def tearDown(self):
  228. signals.COMPLEX_OVERRIDE_SETTINGS = self.old_warn_override_settings
  229. self.assertFalse('TEST_WARN' in signals.COMPLEX_OVERRIDE_SETTINGS)
  230. def test_complex_override_warning(self):
  231. """Regression test for #19031"""
  232. with warnings.catch_warnings(record=True) as w:
  233. warnings.simplefilter("always")
  234. with override_settings(TEST_WARN='override'):
  235. self.assertEqual(settings.TEST_WARN, 'override')
  236. self.assertEqual(len(w), 1)
  237. # File extension may by .py, .pyc, etc. Compare only basename.
  238. self.assertEqual(os.path.splitext(w[0].filename)[0],
  239. os.path.splitext(__file__)[0])
  240. self.assertEqual(str(w[0].message),
  241. 'Overriding setting TEST_WARN can lead to unexpected behavior.')
  242. class TrailingSlashURLTests(TestCase):
  243. """
  244. Tests for the MEDIA_URL and STATIC_URL settings.
  245. They must end with a slash to ensure there's a deterministic way to build
  246. paths in templates.
  247. """
  248. settings_module = settings
  249. def setUp(self):
  250. self._original_media_url = self.settings_module.MEDIA_URL
  251. self._original_static_url = self.settings_module.STATIC_URL
  252. def tearDown(self):
  253. self.settings_module.MEDIA_URL = self._original_media_url
  254. self.settings_module.STATIC_URL = self._original_static_url
  255. def test_blank(self):
  256. """
  257. The empty string is accepted, even though it doesn't end in a slash.
  258. """
  259. self.settings_module.MEDIA_URL = ''
  260. self.assertEqual('', self.settings_module.MEDIA_URL)
  261. self.settings_module.STATIC_URL = ''
  262. self.assertEqual('', self.settings_module.STATIC_URL)
  263. def test_end_slash(self):
  264. """
  265. It works if the value ends in a slash.
  266. """
  267. self.settings_module.MEDIA_URL = '/foo/'
  268. self.assertEqual('/foo/', self.settings_module.MEDIA_URL)
  269. self.settings_module.MEDIA_URL = 'http://media.foo.com/'
  270. self.assertEqual('http://media.foo.com/',
  271. self.settings_module.MEDIA_URL)
  272. self.settings_module.STATIC_URL = '/foo/'
  273. self.assertEqual('/foo/', self.settings_module.STATIC_URL)
  274. self.settings_module.STATIC_URL = 'http://static.foo.com/'
  275. self.assertEqual('http://static.foo.com/',
  276. self.settings_module.STATIC_URL)
  277. def test_no_end_slash(self):
  278. """
  279. An ImproperlyConfigured exception is raised if the value doesn't end
  280. in a slash.
  281. """
  282. with self.assertRaises(ImproperlyConfigured):
  283. self.settings_module.MEDIA_URL = '/foo'
  284. with self.assertRaises(ImproperlyConfigured):
  285. self.settings_module.MEDIA_URL = 'http://media.foo.com'
  286. with self.assertRaises(ImproperlyConfigured):
  287. self.settings_module.STATIC_URL = '/foo'
  288. with self.assertRaises(ImproperlyConfigured):
  289. self.settings_module.STATIC_URL = 'http://static.foo.com'
  290. def test_double_slash(self):
  291. """
  292. If the value ends in more than one slash, presume they know what
  293. they're doing.
  294. """
  295. self.settings_module.MEDIA_URL = '/stupid//'
  296. self.assertEqual('/stupid//', self.settings_module.MEDIA_URL)
  297. self.settings_module.MEDIA_URL = 'http://media.foo.com/stupid//'
  298. self.assertEqual('http://media.foo.com/stupid//',
  299. self.settings_module.MEDIA_URL)
  300. self.settings_module.STATIC_URL = '/stupid//'
  301. self.assertEqual('/stupid//', self.settings_module.STATIC_URL)
  302. self.settings_module.STATIC_URL = 'http://static.foo.com/stupid//'
  303. self.assertEqual('http://static.foo.com/stupid//',
  304. self.settings_module.STATIC_URL)
  305. class SecureProxySslHeaderTest(TestCase):
  306. settings_module = settings
  307. def setUp(self):
  308. self._original_setting = self.settings_module.SECURE_PROXY_SSL_HEADER
  309. def tearDown(self):
  310. self.settings_module.SECURE_PROXY_SSL_HEADER = self._original_setting
  311. def test_none(self):
  312. self.settings_module.SECURE_PROXY_SSL_HEADER = None
  313. req = HttpRequest()
  314. self.assertEqual(req.is_secure(), False)
  315. def test_set_without_xheader(self):
  316. self.settings_module.SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https')
  317. req = HttpRequest()
  318. self.assertEqual(req.is_secure(), False)
  319. def test_set_with_xheader_wrong(self):
  320. self.settings_module.SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https')
  321. req = HttpRequest()
  322. req.META['HTTP_X_FORWARDED_PROTOCOL'] = 'wrongvalue'
  323. self.assertEqual(req.is_secure(), False)
  324. def test_set_with_xheader_right(self):
  325. self.settings_module.SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https')
  326. req = HttpRequest()
  327. req.META['HTTP_X_FORWARDED_PROTOCOL'] = 'https'
  328. self.assertEqual(req.is_secure(), True)
  329. class IsOverriddenTest(TestCase):
  330. def test_configure(self):
  331. s = LazySettings()
  332. s.configure(SECRET_KEY='foo')
  333. self.assertTrue(s.is_overridden('SECRET_KEY'))
  334. def test_module(self):
  335. settings_module = ModuleType('fake_settings_module')
  336. settings_module.SECRET_KEY = 'foo'
  337. sys.modules['fake_settings_module'] = settings_module
  338. try:
  339. s = Settings('fake_settings_module')
  340. self.assertTrue(s.is_overridden('SECRET_KEY'))
  341. self.assertFalse(s.is_overridden('TEMPLATE_LOADERS'))
  342. finally:
  343. del sys.modules['fake_settings_module']
  344. def test_override(self):
  345. self.assertFalse(settings.is_overridden('TEMPLATE_LOADERS'))
  346. with override_settings(TEMPLATE_LOADERS=[]):
  347. self.assertTrue(settings.is_overridden('TEMPLATE_LOADERS'))
  348. class TestTupleSettings(unittest.TestCase):
  349. """
  350. Make sure settings that should be tuples throw ImproperlyConfigured if they
  351. are set to a string instead of a tuple.
  352. """
  353. tuple_settings = ("INSTALLED_APPS", "TEMPLATE_DIRS", "LOCALE_PATHS")
  354. def test_tuple_settings(self):
  355. settings_module = ModuleType('fake_settings_module')
  356. settings_module.SECRET_KEY = 'foo'
  357. for setting in self.tuple_settings:
  358. setattr(settings_module, setting, ('non_tuple_value'))
  359. sys.modules['fake_settings_module'] = settings_module
  360. try:
  361. with self.assertRaises(ImproperlyConfigured):
  362. Settings('fake_settings_module')
  363. finally:
  364. del sys.modules['fake_settings_module']
  365. delattr(settings_module, setting)