test_context.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. # -*- coding: utf-8 -*-
  2. from django.http import HttpRequest
  3. from django.template import (
  4. Context, RequestContext, Template, Variable, VariableDoesNotExist,
  5. )
  6. from django.template.context import RenderContext
  7. from django.test import RequestFactory, SimpleTestCase, override_settings
  8. class ContextTests(SimpleTestCase):
  9. def test_context(self):
  10. c = Context({"a": 1, "b": "xyzzy"})
  11. self.assertEqual(c["a"], 1)
  12. self.assertEqual(c.push(), {})
  13. c["a"] = 2
  14. self.assertEqual(c["a"], 2)
  15. self.assertEqual(c.get("a"), 2)
  16. self.assertEqual(c.pop(), {"a": 2})
  17. self.assertEqual(c["a"], 1)
  18. self.assertEqual(c.get("foo", 42), 42)
  19. with c.push():
  20. c['a'] = 2
  21. self.assertEqual(c['a'], 2)
  22. self.assertEqual(c['a'], 1)
  23. with c.push(a=3):
  24. self.assertEqual(c['a'], 3)
  25. self.assertEqual(c['a'], 1)
  26. def test_resolve_on_context_method(self):
  27. """
  28. #17778 -- Variable shouldn't resolve RequestContext methods
  29. """
  30. empty_context = Context()
  31. with self.assertRaises(VariableDoesNotExist):
  32. Variable('no_such_variable').resolve(empty_context)
  33. with self.assertRaises(VariableDoesNotExist):
  34. Variable('new').resolve(empty_context)
  35. self.assertEqual(
  36. Variable('new').resolve(Context({'new': 'foo'})),
  37. 'foo',
  38. )
  39. def test_render_context(self):
  40. test_context = RenderContext({'fruit': 'papaya'})
  41. # Test that push() limits access to the topmost dict
  42. test_context.push()
  43. test_context['vegetable'] = 'artichoke'
  44. self.assertEqual(list(test_context), ['vegetable'])
  45. self.assertNotIn('fruit', test_context)
  46. with self.assertRaises(KeyError):
  47. test_context['fruit']
  48. self.assertIsNone(test_context.get('fruit'))
  49. def test_flatten_context(self):
  50. a = Context()
  51. a.update({'a': 2})
  52. a.update({'b': 4})
  53. a.update({'c': 8})
  54. self.assertEqual(a.flatten(), {
  55. 'False': False, 'None': None, 'True': True,
  56. 'a': 2, 'b': 4, 'c': 8
  57. })
  58. def test_context_comparable(self):
  59. """
  60. #21765 -- equality comparison should work
  61. """
  62. test_data = {'x': 'y', 'v': 'z', 'd': {'o': object, 'a': 'b'}}
  63. self.assertEqual(Context(test_data), Context(test_data))
  64. a = Context()
  65. b = Context()
  66. self.assertEqual(a, b)
  67. # update only a
  68. a.update({'a': 1})
  69. self.assertNotEqual(a, b)
  70. # update both to check regression
  71. a.update({'c': 3})
  72. b.update({'c': 3})
  73. self.assertNotEqual(a, b)
  74. # make contexts equals again
  75. b.update({'a': 1})
  76. self.assertEqual(a, b)
  77. def test_copy_request_context_twice(self):
  78. """
  79. #24273 -- Copy twice shouldn't raise an exception
  80. """
  81. RequestContext(HttpRequest()).new().new()
  82. class RequestContextTests(SimpleTestCase):
  83. @override_settings(TEMPLATES=[{
  84. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  85. 'OPTIONS': {
  86. 'loaders': [
  87. ('django.template.loaders.locmem.Loader', {
  88. 'child': '{{ var|default:"none" }}',
  89. }),
  90. ],
  91. },
  92. }])
  93. def test_include_only(self):
  94. """
  95. #15721 -- ``{% include %}`` and ``RequestContext`` should work
  96. together.
  97. """
  98. request = RequestFactory().get('/')
  99. ctx = RequestContext(request, {'var': 'parent'})
  100. self.assertEqual(Template('{% include "child" %}').render(ctx), 'parent')
  101. self.assertEqual(Template('{% include "child" only %}').render(ctx), 'none')
  102. def test_stack_size(self):
  103. """
  104. #7116 -- Optimize RequetsContext construction
  105. """
  106. request = RequestFactory().get('/')
  107. ctx = RequestContext(request, {})
  108. # The stack should now contain 3 items:
  109. # [builtins, supplied context, context processor]
  110. self.assertEqual(len(ctx.dicts), 3)
  111. def test_context_comparable(self):
  112. # Create an engine without any context processors.
  113. test_data = {'x': 'y', 'v': 'z', 'd': {'o': object, 'a': 'b'}}
  114. # test comparing RequestContext to prevent problems if somebody
  115. # adds __eq__ in the future
  116. request = RequestFactory().get('/')
  117. self.assertEqual(
  118. RequestContext(request, dict_=test_data),
  119. RequestContext(request, dict_=test_data),
  120. )