Debian Codegraph @

tests/template_tests/test_context.py

raw
1 from copy import copy
2 from unittest import mock
3
4 from django.http import HttpRequest
5 from django.template import (
6 Context,
7 Engine,
8 RequestContext,
9 Template,
10 Variable,
11 VariableDoesNotExist,
12 )
13 from django.template.context import RenderContext
14 from django.test import RequestFactory, SimpleTestCase, override_settings
15
16
17 class ContextTests(SimpleTestCase):
18 def test_context(self):
19 c = Context({"a": 1, "b": "xyzzy"})
20 self.assertEqual(c["a"], 1)
21 self.assertEqual(c.push(), {})
22 c["a"] = 2
23 self.assertEqual(c["a"], 2)
24 self.assertEqual(c.get("a"), 2)
25 self.assertEqual(c.pop(), {"a": 2})
26 self.assertEqual(c["a"], 1)
27 self.assertEqual(c.get("foo", 42), 42)
28 self.assertEqual(c, mock.ANY)
29
30 def test_push_context_manager(self):
31 c = Context({"a": 1})
32 with c.push():
33 c["a"] = 2
34 self.assertEqual(c["a"], 2)
35 self.assertEqual(c["a"], 1)
36
37 with c.push(a=3):
38 self.assertEqual(c["a"], 3)
39 self.assertEqual(c["a"], 1)
40
41 def test_update_context_manager(self):
42 c = Context({"a": 1})
43 with c.update({}):
44 c["a"] = 2
45 self.assertEqual(c["a"], 2)
46 self.assertEqual(c["a"], 1)
47
48 with c.update({"a": 3}):
49 self.assertEqual(c["a"], 3)
50 self.assertEqual(c["a"], 1)
51
52 def test_push_context_manager_with_context_object(self):
53 c = Context({"a": 1})
54 with c.push(Context({"a": 3})):
55 self.assertEqual(c["a"], 3)
56 self.assertEqual(c["a"], 1)
57
58 def test_update_context_manager_with_context_object(self):
59 c = Context({"a": 1})
60 with c.update(Context({"a": 3})):
61 self.assertEqual(c["a"], 3)
62 self.assertEqual(c["a"], 1)
63
64 def test_push_proper_layering(self):
65 c = Context({"a": 1})
66 c.push(Context({"b": 2}))
67 c.push(Context({"c": 3, "d": {"z": "26"}}))
68 self.assertEqual(
69 c.dicts,
70 [
71 {"False": False, "None": None, "True": True},
72 {"a": 1},
73 {"b": 2},
74 {"c": 3, "d": {"z": "26"}},
75 ],
76 )
77
78 def test_update_proper_layering(self):
79 c = Context({"a": 1})
80 c.update(Context({"b": 2}))
81 c.update(Context({"c": 3, "d": {"z": "26"}}))
82 self.assertEqual(
83 c.dicts,
84 [
85 {"False": False, "None": None, "True": True},
86 {"a": 1},
87 {"b": 2},
88 {"c": 3, "d": {"z": "26"}},
89 ],
90 )
91
92 def test_setdefault(self):
93 c = Context()
94
95 x = c.setdefault("x", 42)
96 self.assertEqual(x, 42)
97 self.assertEqual(c["x"], 42)
98
99 x = c.setdefault("x", 100)
100 self.assertEqual(x, 42)
101 self.assertEqual(c["x"], 42)
102
103 def test_resolve_on_context_method(self):
104 """
105 #17778 -- Variable shouldn't resolve RequestContext methods
106 """
107 empty_context = Context()
108
109 with self.assertRaises(VariableDoesNotExist):
110 Variable("no_such_variable").resolve(empty_context)
111
112 with self.assertRaises(VariableDoesNotExist):
113 Variable("new").resolve(empty_context)
114
115 self.assertEqual(
116 Variable("new").resolve(Context({"new": "foo"})),
117 "foo",
118 )
119
120 def test_render_context(self):
121 test_context = RenderContext({"fruit": "papaya"})
122
123 # push() limits access to the topmost dict
124 test_context.push()
125
126 test_context["vegetable"] = "artichoke"
127 self.assertEqual(list(test_context), ["vegetable"])
128
129 self.assertNotIn("fruit", test_context)
130 with self.assertRaises(KeyError):
131 test_context["fruit"]
132 self.assertIsNone(test_context.get("fruit"))
133
134 def test_flatten_context(self):
135 a = Context()
136 a.update({"a": 2})
137 a.update({"b": 4})
138 a.update({"c": 8})
139
140 self.assertEqual(
141 a.flatten(),
142 {"False": False, "None": None, "True": True, "a": 2, "b": 4, "c": 8},
143 )
144
145 def test_flatten_context_with_context(self):
146 """
147 Context.push() with a Context argument should work.
148 """
149 a = Context({"a": 2})
150 a.push(Context({"z": "8"}))
151 self.assertEqual(
152 a.flatten(),
153 {
154 "False": False,
155 "None": None,
156 "True": True,
157 "a": 2,
158 "z": "8",
159 },
160 )
161
162 def test_flatten_context_with_context_copy(self):
163 ctx1 = Context({"a": 2})
164 ctx2 = ctx1.new(Context({"b": 4}))
165 self.assertEqual(
166 ctx2.dicts, [{"True": True, "False": False, "None": None}, {"b": 4}]
167 )
168 self.assertEqual(
169 ctx2.flatten(),
170 {"False": False, "None": None, "True": True, "b": 4},
171 )
172
173 def test_context_comparable(self):
174 """
175 #21765 -- equality comparison should work
176 """
177
178 test_data = {"x": "y", "v": "z", "d": {"o": object, "a": "b"}}
179
180 self.assertEqual(Context(test_data), Context(test_data))
181
182 a = Context()
183 b = Context()
184 self.assertEqual(a, b)
185
186 # update only a
187 a.update({"a": 1})
188 self.assertNotEqual(a, b)
189
190 # update both to check regression
191 a.update({"c": 3})
192 b.update({"c": 3})
193 self.assertNotEqual(a, b)
194
195 # make contexts equals again
196 b.update({"a": 1})
197 self.assertEqual(a, b)
198
199 def test_copy_request_context_twice(self):
200 """
201 #24273 -- Copy twice shouldn't raise an exception
202 """
203 RequestContext(HttpRequest()).new().new()
204
205 def test_set_upward(self):
206 c = Context({"a": 1})
207 c.set_upward("a", 2)
208 self.assertEqual(c.get("a"), 2)
209
210 def test_set_upward_empty_context(self):
211 empty_context = Context()
212 empty_context.set_upward("a", 1)
213 self.assertEqual(empty_context.get("a"), 1)
214
215 def test_set_upward_with_push(self):
216 """
217 The highest context which has the given key is used.
218 """
219 c = Context({"a": 1})
220 c.push({"a": 2})
221 c.set_upward("a", 3)
222 self.assertEqual(c.get("a"), 3)
223 c.pop()
224 self.assertEqual(c.get("a"), 1)
225
226 def test_set_upward_with_push_no_match(self):
227 """
228 The highest context is used if the given key isn't found.
229 """
230 c = Context({"b": 1})
231 c.push({"b": 2})
232 c.set_upward("a", 2)
233 self.assertEqual(len(c.dicts), 3)
234 self.assertEqual(c.dicts[-1]["a"], 2)
235
236
237 def context_process_returning_none(request):
238 return None
239
240
241 class RequestContextTests(SimpleTestCase):
242 request_factory = RequestFactory()
243
244 def test_include_only(self):
245 """
246 #15721 -- ``{% include %}`` and ``RequestContext`` should work
247 together.
248 """
249 engine = Engine(
250 loaders=[
251 (
252 "django.template.loaders.locmem.Loader",
253 {
254 "child": '{{ var|default:"none" }}',
255 },
256 ),
257 ]
258 )
259 request = self.request_factory.get("/")
260 ctx = RequestContext(request, {"var": "parent"})
261 self.assertEqual(
262 engine.from_string('{% include "child" %}').render(ctx), "parent"
263 )
264 self.assertEqual(
265 engine.from_string('{% include "child" only %}').render(ctx), "none"
266 )
267
268 def test_stack_size(self):
269 """Optimized RequestContext construction (#7116)."""
270 request = self.request_factory.get("/")
271 ctx = RequestContext(request, {})
272 # The stack contains 4 items:
273 # [builtins, supplied context, context processor, empty dict]
274 self.assertEqual(len(ctx.dicts), 4)
275
276 def test_context_comparable(self):
277 # Create an engine without any context processors.
278 test_data = {"x": "y", "v": "z", "d": {"o": object, "a": "b"}}
279
280 # test comparing RequestContext to prevent problems if somebody
281 # adds __eq__ in the future
282 request = self.request_factory.get("/")
283
284 self.assertEqual(
285 RequestContext(request, dict_=test_data),
286 RequestContext(request, dict_=test_data),
287 )
288
289 def test_modify_context_and_render(self):
290 template = Template("{{ foo }}")
291 request = self.request_factory.get("/")
292 context = RequestContext(request, {})
293 context["foo"] = "foo"
294 self.assertEqual(template.render(context), "foo")
295
296 @override_settings(
297 TEMPLATES=[
298 {
299 "BACKEND": "django.template.backends.django.DjangoTemplates",
300 "OPTIONS": {
301 "context_processors": [
302 "django.template.context_processors.request",
303 "template_tests.test_context.context_process_returning_none",
304 ],
305 },
306 }
307 ],
308 )
309 def test_template_context_processor_returning_none(self):
310 request_context = RequestContext(HttpRequest())
311 msg = (
312 "Context processor context_process_returning_none didn't return a "
313 "dictionary."
314 )
315 with self.assertRaisesMessage(TypeError, msg):
316 with request_context.bind_template(Template("")):
317 pass
318
319 def test_context_copyable(self):
320 request_context = RequestContext(HttpRequest())
321 request_context_copy = copy(request_context)
322 self.assertIsInstance(request_context_copy, RequestContext)
323 self.assertEqual(request_context_copy.dicts, request_context.dicts)
324 self.assertIsNot(request_context_copy.dicts, request_context.dicts)