Debian Codegraph @

tests/template_tests/tests.py

raw
1 import sys
2 import unittest
3 from typing import TYPE_CHECKING, TypeAlias
4
5 from django.template import Context, Engine, TemplateDoesNotExist, TemplateSyntaxError
6 from django.template.base import UNKNOWN_SOURCE
7 from django.test import SimpleTestCase, override_settings
8 from django.urls import NoReverseMatch
9 from django.utils import translation
10 from django.utils.version import PY314
11
12 if TYPE_CHECKING:
13 AnnotatedKwarg: TypeAlias = str
14
15
16 class TemplateTestMixin:
17 def _engine(self, **kwargs):
18 return Engine(debug=self.debug_engine, **kwargs)
19
20 def test_string_origin(self):
21 template = self._engine().from_string("string template")
22 self.assertEqual(template.origin.name, UNKNOWN_SOURCE)
23 self.assertIsNone(template.origin.loader_name)
24 self.assertEqual(template.source, "string template")
25
26 @override_settings(SETTINGS_MODULE=None)
27 def test_url_reverse_no_settings_module(self):
28 """
29 #9005 -- url tag shouldn't require settings.SETTINGS_MODULE to
30 be set.
31 """
32 t = self._engine().from_string("{% url will_not_match %}")
33 c = Context()
34 with self.assertRaises(NoReverseMatch):
35 t.render(c)
36
37 def test_url_reverse_view_name(self):
38 """
39 #19827 -- url tag should keep original stack trace when reraising
40 exception.
41 """
42 t = self._engine().from_string("{% url will_not_match %}")
43 c = Context()
44 try:
45 t.render(c)
46 except NoReverseMatch:
47 tb = sys.exc_info()[2]
48 depth = 0
49 while tb.tb_next is not None:
50 tb = tb.tb_next
51 depth += 1
52 self.assertGreater(
53 depth, 5, "The traceback context was lost when reraising the traceback."
54 )
55
56 def test_no_wrapped_exception(self):
57 """
58 # 16770 -- The template system doesn't wrap exceptions, but annotates
59 them.
60 """
61 engine = self._engine()
62 c = Context({"coconuts": lambda: 42 / 0})
63 t = engine.from_string("{{ coconuts }}")
64
65 with self.assertRaises(ZeroDivisionError) as e:
66 t.render(c)
67
68 if self.debug_engine:
69 debug = e.exception.template_debug
70 self.assertEqual(debug["start"], 0)
71 self.assertEqual(debug["end"], 14)
72
73 def test_invalid_block_suggestion(self):
74 """
75 Error messages should include the unexpected block name and be in all
76 English.
77 """
78 engine = self._engine()
79 msg = (
80 "Invalid block tag on line 1: 'endblock', expected 'elif', 'else' "
81 "or 'endif'. Did you forget to register or load this tag?"
82 )
83 with self.settings(USE_I18N=True), translation.override("de"):
84 with self.assertRaisesMessage(TemplateSyntaxError, msg):
85 engine.from_string("{% if 1 %}lala{% endblock %}{% endif %}")
86
87 def test_unknown_block_tag(self):
88 engine = self._engine()
89 msg = (
90 "Invalid block tag on line 1: 'foobar'. Did you forget to "
91 "register or load this tag?"
92 )
93 with self.assertRaisesMessage(TemplateSyntaxError, msg):
94 engine.from_string("lala{% foobar %}")
95
96 def test_compile_filter_expression_error(self):
97 """
98 19819 -- Make sure the correct token is highlighted for
99 FilterExpression errors.
100 """
101 engine = self._engine()
102 msg = "Could not parse the remainder: '@bar' from 'foo@bar'"
103
104 with self.assertRaisesMessage(TemplateSyntaxError, msg) as e:
105 engine.from_string("{% if 1 %}{{ foo@bar }}{% endif %}")
106
107 if self.debug_engine:
108 debug = e.exception.template_debug
109 self.assertEqual((debug["start"], debug["end"]), (10, 23))
110 self.assertEqual((debug["during"]), "{{ foo@bar }}")
111
112 def test_compile_tag_error(self):
113 """
114 Errors raised while compiling nodes should include the token
115 information.
116 """
117 engine = self._engine(
118 libraries={"bad_tag": "template_tests.templatetags.bad_tag"},
119 )
120 with self.assertRaises(RuntimeError) as e:
121 engine.from_string("{% load bad_tag %}{% badtag %}")
122 if self.debug_engine:
123 self.assertEqual(e.exception.template_debug["during"], "{% badtag %}")
124
125 def test_compile_tag_error_27584(self):
126 engine = self._engine(
127 app_dirs=True,
128 libraries={"tag_27584": "template_tests.templatetags.tag_27584"},
129 )
130 t = engine.get_template("27584_parent.html")
131 with self.assertRaises(TemplateSyntaxError) as e:
132 t.render(Context())
133 if self.debug_engine:
134 self.assertEqual(e.exception.template_debug["during"], "{% badtag %}")
135
136 def test_compile_tag_error_27956(self):
137 """Errors in a child of {% extends %} are displayed correctly."""
138 engine = self._engine(
139 app_dirs=True,
140 libraries={"tag_27584": "template_tests.templatetags.tag_27584"},
141 )
142 t = engine.get_template("27956_child.html")
143 with self.assertRaises(TemplateSyntaxError) as e:
144 t.render(Context())
145 if self.debug_engine:
146 self.assertEqual(e.exception.template_debug["during"], "{% badtag %}")
147
148 def test_compile_tag_extra_data(self):
149 """Custom tags can pass extra data back to template."""
150 engine = self._engine(
151 app_dirs=True,
152 libraries={"custom": "template_tests.templatetags.custom"},
153 )
154 t = engine.from_string("{% load custom %}{% extra_data %}")
155 self.assertEqual(t.extra_data["extra_data"], "CUSTOM_DATA")
156
157 def test_render_tag_error_in_extended_block(self):
158 """Errors in extended block are displayed correctly."""
159 e = self._engine(app_dirs=True)
160 template = e.get_template("test_extends_block_error.html")
161 context = Context()
162 with self.assertRaises(TemplateDoesNotExist) as cm:
163 template.render(context)
164 if self.debug_engine:
165 self.assertEqual(
166 cm.exception.template_debug["before"],
167 '{% block content %}{% include "index.html" %}',
168 )
169 self.assertEqual(
170 cm.exception.template_debug["during"],
171 '{% include "missing.html" %}',
172 )
173 self.assertEqual(
174 cm.exception.template_debug["after"],
175 '{% include "index.html" %}{% endblock %}\n',
176 )
177 self.assertEqual(
178 cm.exception.template_debug["source_lines"][0],
179 (1, '{% extends "test_extends_block_error_parent.html" %}\n'),
180 )
181 self.assertEqual(
182 cm.exception.template_debug["source_lines"][1],
183 (
184 2,
185 '{% block content %}{% include "index.html" %}'
186 '{% include "missing.html" %}'
187 '{% include "index.html" %}{% endblock %}\n',
188 ),
189 )
190 self.assertEqual(cm.exception.template_debug["source_lines"][2], (3, ""))
191
192 def test_super_errors(self):
193 """
194 #18169 -- NoReverseMatch should not be silence in block.super.
195 """
196 engine = self._engine(app_dirs=True)
197 t = engine.get_template("included_content.html")
198 with self.assertRaises(NoReverseMatch):
199 t.render(Context())
200
201 def test_extends_generic_template(self):
202 """
203 #24338 -- Allow extending django.template.backends.django.Template
204 objects.
205 """
206 engine = self._engine()
207 parent = engine.from_string("{% block content %}parent{% endblock %}")
208 child = engine.from_string(
209 "{% extends parent %}{% block content %}child{% endblock %}"
210 )
211 self.assertEqual(child.render(Context({"parent": parent})), "child")
212
213 def test_node_origin(self):
214 """
215 #25848 -- Set origin on Node so debugging tools can determine which
216 template the node came from even if extending or including templates.
217 """
218 template = self._engine().from_string("content")
219 for node in template.nodelist:
220 self.assertEqual(node.origin, template.origin)
221
222 def test_render_built_in_type_method(self):
223 """
224 Templates should not crash when rendering methods for built-in types
225 without required arguments.
226 """
227 template = self._engine().from_string("{{ description.count }}")
228 self.assertEqual(template.render(Context({"description": "test"})), "")
229
230 @unittest.skipUnless(PY314, "Deferred annotations are Python 3.14+ only")
231 def test_callable_uses_deferred_annotations(self):
232 """
233 Missing required arguments are gracefully handled when a signature uses
234 deferred annotations.
235 """
236
237 class MyObject:
238 @staticmethod
239 def uses_deferred_annotations(value: AnnotatedKwarg):
240 return value
241
242 template = self._engine().from_string("{{ obj.uses_deferred_annotations }}")
243 self.assertEqual(template.render(Context({"obj": MyObject()})), "")
244
245
246 class TemplateTests(TemplateTestMixin, SimpleTestCase):
247 debug_engine = False
248
249
250 class DebugTemplateTests(TemplateTestMixin, SimpleTestCase):
251 debug_engine = True