diff options
| author | django-bot <ops@djangoproject.com> | 2022-02-03 20:24:19 +0100 |
|---|---|---|
| committer | Mariusz Felisiak <felisiak.mariusz@gmail.com> | 2022-02-07 20:37:05 +0100 |
| commit | 9c19aff7c7561e3a82978a272ecdaad40dda5c00 (patch) | |
| tree | f0506b668a013d0063e5fba3dbf4863b466713ba /tests/template_tests | |
| parent | f68fa8b45dfac545cfc4111d4e52804c86db68d3 (diff) | |
Refs #33476 -- Reformatted code with Black.
Diffstat (limited to 'tests/template_tests')
130 files changed, 6707 insertions, 4861 deletions
diff --git a/tests/template_tests/alternate_urls.py b/tests/template_tests/alternate_urls.py index 181e5c50a5..236f393dd0 100644 --- a/tests/template_tests/alternate_urls.py +++ b/tests/template_tests/alternate_urls.py @@ -4,8 +4,7 @@ from . import views urlpatterns = [ # View returning a template response - path('template_response_view/', views.template_response_view), - + path("template_response_view/", views.template_response_view), # A view that can be hard to find... - path('snark/', views.snark, name='snark'), + path("snark/", views.snark, name="snark"), ] diff --git a/tests/template_tests/filter_tests/test_add.py b/tests/template_tests/filter_tests/test_add.py index b5786ca136..9b798f4aa7 100644 --- a/tests/template_tests/filter_tests/test_add.py +++ b/tests/template_tests/filter_tests/test_add.py @@ -12,59 +12,60 @@ class AddTests(SimpleTestCase): Tests for #11687 and #16676 """ - @setup({'add01': '{{ i|add:"5" }}'}) + @setup({"add01": '{{ i|add:"5" }}'}) def test_add01(self): - output = self.engine.render_to_string('add01', {'i': 2000}) - self.assertEqual(output, '2005') + output = self.engine.render_to_string("add01", {"i": 2000}) + self.assertEqual(output, "2005") - @setup({'add02': '{{ i|add:"napis" }}'}) + @setup({"add02": '{{ i|add:"napis" }}'}) def test_add02(self): - output = self.engine.render_to_string('add02', {'i': 2000}) - self.assertEqual(output, '') + output = self.engine.render_to_string("add02", {"i": 2000}) + self.assertEqual(output, "") - @setup({'add03': '{{ i|add:16 }}'}) + @setup({"add03": "{{ i|add:16 }}"}) def test_add03(self): - output = self.engine.render_to_string('add03', {'i': 'not_an_int'}) - self.assertEqual(output, '') + output = self.engine.render_to_string("add03", {"i": "not_an_int"}) + self.assertEqual(output, "") - @setup({'add04': '{{ i|add:"16" }}'}) + @setup({"add04": '{{ i|add:"16" }}'}) def test_add04(self): - output = self.engine.render_to_string('add04', {'i': 'not_an_int'}) - self.assertEqual(output, 'not_an_int16') + output = self.engine.render_to_string("add04", {"i": "not_an_int"}) + self.assertEqual(output, "not_an_int16") - @setup({'add05': '{{ l1|add:l2 }}'}) + @setup({"add05": "{{ l1|add:l2 }}"}) def test_add05(self): - output = self.engine.render_to_string('add05', {'l1': [1, 2], 'l2': [3, 4]}) - self.assertEqual(output, '[1, 2, 3, 4]') + output = self.engine.render_to_string("add05", {"l1": [1, 2], "l2": [3, 4]}) + self.assertEqual(output, "[1, 2, 3, 4]") - @setup({'add06': '{{ t1|add:t2 }}'}) + @setup({"add06": "{{ t1|add:t2 }}"}) def test_add06(self): - output = self.engine.render_to_string('add06', {'t1': (3, 4), 't2': (1, 2)}) - self.assertEqual(output, '(3, 4, 1, 2)') + output = self.engine.render_to_string("add06", {"t1": (3, 4), "t2": (1, 2)}) + self.assertEqual(output, "(3, 4, 1, 2)") - @setup({'add07': '{{ d|add:t }}'}) + @setup({"add07": "{{ d|add:t }}"}) def test_add07(self): - output = self.engine.render_to_string('add07', {'d': date(2000, 1, 1), 't': timedelta(10)}) - self.assertEqual(output, 'Jan. 11, 2000') + output = self.engine.render_to_string( + "add07", {"d": date(2000, 1, 1), "t": timedelta(10)} + ) + self.assertEqual(output, "Jan. 11, 2000") - @setup({'add08': '{{ s1|add:lazy_s2 }}'}) + @setup({"add08": "{{ s1|add:lazy_s2 }}"}) def test_add08(self): output = self.engine.render_to_string( - 'add08', - {'s1': 'string', 'lazy_s2': gettext_lazy('lazy')}, + "add08", + {"s1": "string", "lazy_s2": gettext_lazy("lazy")}, ) - self.assertEqual(output, 'stringlazy') + self.assertEqual(output, "stringlazy") - @setup({'add09': '{{ lazy_s1|add:lazy_s2 }}'}) + @setup({"add09": "{{ lazy_s1|add:lazy_s2 }}"}) def test_add09(self): output = self.engine.render_to_string( - 'add09', - {'lazy_s1': gettext_lazy('string'), 'lazy_s2': gettext_lazy('lazy')}, + "add09", + {"lazy_s1": gettext_lazy("string"), "lazy_s2": gettext_lazy("lazy")}, ) - self.assertEqual(output, 'stringlazy') + self.assertEqual(output, "stringlazy") class FunctionTests(SimpleTestCase): - def test_add(self): - self.assertEqual(add('1', '2'), 3) + self.assertEqual(add("1", "2"), 3) diff --git a/tests/template_tests/filter_tests/test_addslashes.py b/tests/template_tests/filter_tests/test_addslashes.py index ede25cfb14..2626918f3d 100644 --- a/tests/template_tests/filter_tests/test_addslashes.py +++ b/tests/template_tests/filter_tests/test_addslashes.py @@ -6,28 +6,34 @@ from ..utils import setup class AddslashesTests(SimpleTestCase): - - @setup({'addslashes01': '{% autoescape off %}{{ a|addslashes }} {{ b|addslashes }}{% endautoescape %}'}) + @setup( + { + "addslashes01": "{% autoescape off %}{{ a|addslashes }} {{ b|addslashes }}{% endautoescape %}" + } + ) def test_addslashes01(self): - output = self.engine.render_to_string('addslashes01', {"a": "<a>'", "b": mark_safe("<a>'")}) + output = self.engine.render_to_string( + "addslashes01", {"a": "<a>'", "b": mark_safe("<a>'")} + ) self.assertEqual(output, r"<a>\' <a>\'") - @setup({'addslashes02': '{{ a|addslashes }} {{ b|addslashes }}'}) + @setup({"addslashes02": "{{ a|addslashes }} {{ b|addslashes }}"}) def test_addslashes02(self): - output = self.engine.render_to_string('addslashes02', {"a": "<a>'", "b": mark_safe("<a>'")}) + output = self.engine.render_to_string( + "addslashes02", {"a": "<a>'", "b": mark_safe("<a>'")} + ) self.assertEqual(output, r"<a>\' <a>\'") class FunctionTests(SimpleTestCase): - def test_quotes(self): self.assertEqual( - addslashes('"double quotes" and \'single quotes\''), - '\\"double quotes\\" and \\\'single quotes\\\'', + addslashes("\"double quotes\" and 'single quotes'"), + "\\\"double quotes\\\" and \\'single quotes\\'", ) def test_backslashes(self): - self.assertEqual(addslashes(r'\ : backslashes, too'), '\\\\ : backslashes, too') + self.assertEqual(addslashes(r"\ : backslashes, too"), "\\\\ : backslashes, too") def test_non_string_input(self): - self.assertEqual(addslashes(123), '123') + self.assertEqual(addslashes(123), "123") diff --git a/tests/template_tests/filter_tests/test_autoescape.py b/tests/template_tests/filter_tests/test_autoescape.py index 35faada9c6..de58956f2c 100644 --- a/tests/template_tests/filter_tests/test_autoescape.py +++ b/tests/template_tests/filter_tests/test_autoescape.py @@ -8,22 +8,38 @@ class AutoescapeStringfilterTests(SimpleTestCase): Filters decorated with stringfilter still respect is_safe. """ - @setup({'autoescape-stringfilter01': '{{ unsafe|capfirst }}'}) + @setup({"autoescape-stringfilter01": "{{ unsafe|capfirst }}"}) def test_autoescape_stringfilter01(self): - output = self.engine.render_to_string('autoescape-stringfilter01', {'unsafe': UnsafeClass()}) - self.assertEqual(output, 'You & me') + output = self.engine.render_to_string( + "autoescape-stringfilter01", {"unsafe": UnsafeClass()} + ) + self.assertEqual(output, "You & me") - @setup({'autoescape-stringfilter02': '{% autoescape off %}{{ unsafe|capfirst }}{% endautoescape %}'}) + @setup( + { + "autoescape-stringfilter02": "{% autoescape off %}{{ unsafe|capfirst }}{% endautoescape %}" + } + ) def test_autoescape_stringfilter02(self): - output = self.engine.render_to_string('autoescape-stringfilter02', {'unsafe': UnsafeClass()}) - self.assertEqual(output, 'You & me') + output = self.engine.render_to_string( + "autoescape-stringfilter02", {"unsafe": UnsafeClass()} + ) + self.assertEqual(output, "You & me") - @setup({'autoescape-stringfilter03': '{{ safe|capfirst }}'}) + @setup({"autoescape-stringfilter03": "{{ safe|capfirst }}"}) def test_autoescape_stringfilter03(self): - output = self.engine.render_to_string('autoescape-stringfilter03', {'safe': SafeClass()}) - self.assertEqual(output, 'You > me') + output = self.engine.render_to_string( + "autoescape-stringfilter03", {"safe": SafeClass()} + ) + self.assertEqual(output, "You > me") - @setup({'autoescape-stringfilter04': '{% autoescape off %}{{ safe|capfirst }}{% endautoescape %}'}) + @setup( + { + "autoescape-stringfilter04": "{% autoescape off %}{{ safe|capfirst }}{% endautoescape %}" + } + ) def test_autoescape_stringfilter04(self): - output = self.engine.render_to_string('autoescape-stringfilter04', {'safe': SafeClass()}) - self.assertEqual(output, 'You > me') + output = self.engine.render_to_string( + "autoescape-stringfilter04", {"safe": SafeClass()} + ) + self.assertEqual(output, "You > me") diff --git a/tests/template_tests/filter_tests/test_capfirst.py b/tests/template_tests/filter_tests/test_capfirst.py index bcdf1e0203..3c489e6a1f 100644 --- a/tests/template_tests/filter_tests/test_capfirst.py +++ b/tests/template_tests/filter_tests/test_capfirst.py @@ -6,19 +6,25 @@ from ..utils import setup class CapfirstTests(SimpleTestCase): - - @setup({'capfirst01': '{% autoescape off %}{{ a|capfirst }} {{ b|capfirst }}{% endautoescape %}'}) + @setup( + { + "capfirst01": "{% autoescape off %}{{ a|capfirst }} {{ b|capfirst }}{% endautoescape %}" + } + ) def test_capfirst01(self): - output = self.engine.render_to_string('capfirst01', {'a': 'fred>', 'b': mark_safe('fred>')}) - self.assertEqual(output, 'Fred> Fred>') + output = self.engine.render_to_string( + "capfirst01", {"a": "fred>", "b": mark_safe("fred>")} + ) + self.assertEqual(output, "Fred> Fred>") - @setup({'capfirst02': '{{ a|capfirst }} {{ b|capfirst }}'}) + @setup({"capfirst02": "{{ a|capfirst }} {{ b|capfirst }}"}) def test_capfirst02(self): - output = self.engine.render_to_string('capfirst02', {'a': 'fred>', 'b': mark_safe('fred>')}) - self.assertEqual(output, 'Fred> Fred>') + output = self.engine.render_to_string( + "capfirst02", {"a": "fred>", "b": mark_safe("fred>")} + ) + self.assertEqual(output, "Fred> Fred>") class FunctionTests(SimpleTestCase): - def test_capfirst(self): - self.assertEqual(capfirst('hello world'), 'Hello world') + self.assertEqual(capfirst("hello world"), "Hello world") diff --git a/tests/template_tests/filter_tests/test_center.py b/tests/template_tests/filter_tests/test_center.py index c37b7f80c0..0a18294d88 100644 --- a/tests/template_tests/filter_tests/test_center.py +++ b/tests/template_tests/filter_tests/test_center.py @@ -6,22 +6,28 @@ from ..utils import setup class CenterTests(SimpleTestCase): - - @setup({'center01': '{% autoescape off %}.{{ a|center:"5" }}. .{{ b|center:"5" }}.{% endautoescape %}'}) + @setup( + { + "center01": '{% autoescape off %}.{{ a|center:"5" }}. .{{ b|center:"5" }}.{% endautoescape %}' + } + ) def test_center01(self): - output = self.engine.render_to_string('center01', {"a": "a&b", "b": mark_safe("a&b")}) + output = self.engine.render_to_string( + "center01", {"a": "a&b", "b": mark_safe("a&b")} + ) self.assertEqual(output, ". a&b . . a&b .") - @setup({'center02': '.{{ a|center:"5" }}. .{{ b|center:"5" }}.'}) + @setup({"center02": '.{{ a|center:"5" }}. .{{ b|center:"5" }}.'}) def test_center02(self): - output = self.engine.render_to_string('center02', {"a": "a&b", "b": mark_safe("a&b")}) + output = self.engine.render_to_string( + "center02", {"a": "a&b", "b": mark_safe("a&b")} + ) self.assertEqual(output, ". a&b . . a&b .") class FunctionTests(SimpleTestCase): - def test_center(self): - self.assertEqual(center('test', 6), ' test ') + self.assertEqual(center("test", 6), " test ") def test_non_string_input(self): - self.assertEqual(center(123, 5), ' 123 ') + self.assertEqual(center(123, 5), " 123 ") diff --git a/tests/template_tests/filter_tests/test_chaining.py b/tests/template_tests/filter_tests/test_chaining.py index 9bc3976f37..942707820f 100644 --- a/tests/template_tests/filter_tests/test_chaining.py +++ b/tests/template_tests/filter_tests/test_chaining.py @@ -9,81 +9,108 @@ class ChainingTests(SimpleTestCase): Chaining safeness-preserving filters should not alter the safe status. """ - @setup({'chaining01': '{{ a|capfirst|center:"7" }}.{{ b|capfirst|center:"7" }}'}) + @setup({"chaining01": '{{ a|capfirst|center:"7" }}.{{ b|capfirst|center:"7" }}'}) def test_chaining01(self): - output = self.engine.render_to_string('chaining01', {'a': 'a < b', 'b': mark_safe('a < b')}) - self.assertEqual(output, ' A < b . A < b ') + output = self.engine.render_to_string( + "chaining01", {"a": "a < b", "b": mark_safe("a < b")} + ) + self.assertEqual(output, " A < b . A < b ") - @setup({ - 'chaining02': - '{% autoescape off %}{{ a|capfirst|center:"7" }}.{{ b|capfirst|center:"7" }}{% endautoescape %}' - }) + @setup( + { + "chaining02": '{% autoescape off %}{{ a|capfirst|center:"7" }}.{{ b|capfirst|center:"7" }}{% endautoescape %}' + } + ) def test_chaining02(self): - output = self.engine.render_to_string('chaining02', {'a': 'a < b', 'b': mark_safe('a < b')}) - self.assertEqual(output, ' A < b . A < b ') + output = self.engine.render_to_string( + "chaining02", {"a": "a < b", "b": mark_safe("a < b")} + ) + self.assertEqual(output, " A < b . A < b ") # Using a filter that forces a string back to unsafe: - @setup({'chaining03': '{{ a|cut:"b"|capfirst }}.{{ b|cut:"b"|capfirst }}'}) + @setup({"chaining03": '{{ a|cut:"b"|capfirst }}.{{ b|cut:"b"|capfirst }}'}) def test_chaining03(self): - output = self.engine.render_to_string('chaining03', {'a': 'a < b', 'b': mark_safe('a < b')}) - self.assertEqual(output, 'A < .A < ') + output = self.engine.render_to_string( + "chaining03", {"a": "a < b", "b": mark_safe("a < b")} + ) + self.assertEqual(output, "A < .A < ") - @setup({ - 'chaining04': '{% autoescape off %}{{ a|cut:"b"|capfirst }}.{{ b|cut:"b"|capfirst }}{% endautoescape %}' - }) + @setup( + { + "chaining04": '{% autoescape off %}{{ a|cut:"b"|capfirst }}.{{ b|cut:"b"|capfirst }}{% endautoescape %}' + } + ) def test_chaining04(self): - output = self.engine.render_to_string('chaining04', {'a': 'a < b', 'b': mark_safe('a < b')}) - self.assertEqual(output, 'A < .A < ') + output = self.engine.render_to_string( + "chaining04", {"a": "a < b", "b": mark_safe("a < b")} + ) + self.assertEqual(output, "A < .A < ") # Using a filter that forces safeness does not lead to double-escaping - @setup({'chaining05': '{{ a|escape|capfirst }}'}) + @setup({"chaining05": "{{ a|escape|capfirst }}"}) def test_chaining05(self): - output = self.engine.render_to_string('chaining05', {'a': 'a < b'}) - self.assertEqual(output, 'A < b') + output = self.engine.render_to_string("chaining05", {"a": "a < b"}) + self.assertEqual(output, "A < b") - @setup({'chaining06': '{% autoescape off %}{{ a|escape|capfirst }}{% endautoescape %}'}) + @setup( + {"chaining06": "{% autoescape off %}{{ a|escape|capfirst }}{% endautoescape %}"} + ) def test_chaining06(self): - output = self.engine.render_to_string('chaining06', {'a': 'a < b'}) - self.assertEqual(output, 'A < b') + output = self.engine.render_to_string("chaining06", {"a": "a < b"}) + self.assertEqual(output, "A < b") # Force to safe, then back (also showing why using force_escape too # early in a chain can lead to unexpected results). - @setup({'chaining07': '{{ a|force_escape|cut:";" }}'}) + @setup({"chaining07": '{{ a|force_escape|cut:";" }}'}) def test_chaining07(self): - output = self.engine.render_to_string('chaining07', {'a': 'a < b'}) - self.assertEqual(output, 'a &lt b') + output = self.engine.render_to_string("chaining07", {"a": "a < b"}) + self.assertEqual(output, "a &lt b") - @setup({'chaining08': '{% autoescape off %}{{ a|force_escape|cut:";" }}{% endautoescape %}'}) + @setup( + { + "chaining08": '{% autoescape off %}{{ a|force_escape|cut:";" }}{% endautoescape %}' + } + ) def test_chaining08(self): - output = self.engine.render_to_string('chaining08', {'a': 'a < b'}) - self.assertEqual(output, 'a < b') + output = self.engine.render_to_string("chaining08", {"a": "a < b"}) + self.assertEqual(output, "a < b") - @setup({'chaining09': '{{ a|cut:";"|force_escape }}'}) + @setup({"chaining09": '{{ a|cut:";"|force_escape }}'}) def test_chaining09(self): - output = self.engine.render_to_string('chaining09', {'a': 'a < b'}) - self.assertEqual(output, 'a < b') + output = self.engine.render_to_string("chaining09", {"a": "a < b"}) + self.assertEqual(output, "a < b") - @setup({'chaining10': '{% autoescape off %}{{ a|cut:";"|force_escape }}{% endautoescape %}'}) + @setup( + { + "chaining10": '{% autoescape off %}{{ a|cut:";"|force_escape }}{% endautoescape %}' + } + ) def test_chaining10(self): - output = self.engine.render_to_string('chaining10', {'a': 'a < b'}) - self.assertEqual(output, 'a < b') + output = self.engine.render_to_string("chaining10", {"a": "a < b"}) + self.assertEqual(output, "a < b") - @setup({'chaining11': '{{ a|cut:"b"|safe }}'}) + @setup({"chaining11": '{{ a|cut:"b"|safe }}'}) def test_chaining11(self): - output = self.engine.render_to_string('chaining11', {'a': 'a < b'}) - self.assertEqual(output, 'a < ') + output = self.engine.render_to_string("chaining11", {"a": "a < b"}) + self.assertEqual(output, "a < ") - @setup({'chaining12': '{% autoescape off %}{{ a|cut:"b"|safe }}{% endautoescape %}'}) + @setup( + {"chaining12": '{% autoescape off %}{{ a|cut:"b"|safe }}{% endautoescape %}'} + ) def test_chaining12(self): - output = self.engine.render_to_string('chaining12', {'a': 'a < b'}) - self.assertEqual(output, 'a < ') + output = self.engine.render_to_string("chaining12", {"a": "a < b"}) + self.assertEqual(output, "a < ") - @setup({'chaining13': '{{ a|safe|force_escape }}'}) + @setup({"chaining13": "{{ a|safe|force_escape }}"}) def test_chaining13(self): - output = self.engine.render_to_string('chaining13', {"a": "a < b"}) - self.assertEqual(output, 'a < b') + output = self.engine.render_to_string("chaining13", {"a": "a < b"}) + self.assertEqual(output, "a < b") - @setup({'chaining14': '{% autoescape off %}{{ a|safe|force_escape }}{% endautoescape %}'}) + @setup( + { + "chaining14": "{% autoescape off %}{{ a|safe|force_escape }}{% endautoescape %}" + } + ) def test_chaining14(self): - output = self.engine.render_to_string('chaining14', {"a": "a < b"}) - self.assertEqual(output, 'a < b') + output = self.engine.render_to_string("chaining14", {"a": "a < b"}) + self.assertEqual(output, "a < b") diff --git a/tests/template_tests/filter_tests/test_cut.py b/tests/template_tests/filter_tests/test_cut.py index 6b4baa2645..adf1468709 100644 --- a/tests/template_tests/filter_tests/test_cut.py +++ b/tests/template_tests/filter_tests/test_cut.py @@ -6,50 +6,74 @@ from ..utils import setup class CutTests(SimpleTestCase): - - @setup({'cut01': '{% autoescape off %}{{ a|cut:"x" }} {{ b|cut:"x" }}{% endautoescape %}'}) + @setup( + { + "cut01": '{% autoescape off %}{{ a|cut:"x" }} {{ b|cut:"x" }}{% endautoescape %}' + } + ) def test_cut01(self): - output = self.engine.render_to_string('cut01', {"a": "x&y", "b": mark_safe("x&y")}) + output = self.engine.render_to_string( + "cut01", {"a": "x&y", "b": mark_safe("x&y")} + ) self.assertEqual(output, "&y &y") - @setup({'cut02': '{{ a|cut:"x" }} {{ b|cut:"x" }}'}) + @setup({"cut02": '{{ a|cut:"x" }} {{ b|cut:"x" }}'}) def test_cut02(self): - output = self.engine.render_to_string('cut02', {"a": "x&y", "b": mark_safe("x&y")}) + output = self.engine.render_to_string( + "cut02", {"a": "x&y", "b": mark_safe("x&y")} + ) self.assertEqual(output, "&y &y") - @setup({'cut03': '{% autoescape off %}{{ a|cut:"&" }} {{ b|cut:"&" }}{% endautoescape %}'}) + @setup( + { + "cut03": '{% autoescape off %}{{ a|cut:"&" }} {{ b|cut:"&" }}{% endautoescape %}' + } + ) def test_cut03(self): - output = self.engine.render_to_string('cut03', {"a": "x&y", "b": mark_safe("x&y")}) + output = self.engine.render_to_string( + "cut03", {"a": "x&y", "b": mark_safe("x&y")} + ) self.assertEqual(output, "xy xamp;y") - @setup({'cut04': '{{ a|cut:"&" }} {{ b|cut:"&" }}'}) + @setup({"cut04": '{{ a|cut:"&" }} {{ b|cut:"&" }}'}) def test_cut04(self): - output = self.engine.render_to_string('cut04', {"a": "x&y", "b": mark_safe("x&y")}) + output = self.engine.render_to_string( + "cut04", {"a": "x&y", "b": mark_safe("x&y")} + ) self.assertEqual(output, "xy xamp;y") # Passing ';' to cut can break existing HTML entities, so those strings # are auto-escaped. - @setup({'cut05': '{% autoescape off %}{{ a|cut:";" }} {{ b|cut:";" }}{% endautoescape %}'}) + @setup( + { + "cut05": '{% autoescape off %}{{ a|cut:";" }} {{ b|cut:";" }}{% endautoescape %}' + } + ) def test_cut05(self): - output = self.engine.render_to_string('cut05', {"a": "x&y", "b": mark_safe("x&y")}) + output = self.engine.render_to_string( + "cut05", {"a": "x&y", "b": mark_safe("x&y")} + ) self.assertEqual(output, "x&y x&y") - @setup({'cut06': '{{ a|cut:";" }} {{ b|cut:";" }}'}) + @setup({"cut06": '{{ a|cut:";" }} {{ b|cut:";" }}'}) def test_cut06(self): - output = self.engine.render_to_string('cut06', {"a": "x&y", "b": mark_safe("x&y")}) + output = self.engine.render_to_string( + "cut06", {"a": "x&y", "b": mark_safe("x&y")} + ) self.assertEqual(output, "x&y x&ampy") class FunctionTests(SimpleTestCase): - def test_character(self): - self.assertEqual(cut('a string to be mangled', 'a'), ' string to be mngled') + self.assertEqual(cut("a string to be mangled", "a"), " string to be mngled") def test_characters(self): - self.assertEqual(cut('a string to be mangled', 'ng'), 'a stri to be maled') + self.assertEqual(cut("a string to be mangled", "ng"), "a stri to be maled") def test_non_matching_string(self): - self.assertEqual(cut('a string to be mangled', 'strings'), 'a string to be mangled') + self.assertEqual( + cut("a string to be mangled", "strings"), "a string to be mangled" + ) def test_non_string_input(self): - self.assertEqual(cut(123, '2'), '13') + self.assertEqual(cut(123, "2"), "13") diff --git a/tests/template_tests/filter_tests/test_date.py b/tests/template_tests/filter_tests/test_date.py index b2bdfa2bbb..a7c694d50e 100644 --- a/tests/template_tests/filter_tests/test_date.py +++ b/tests/template_tests/filter_tests/test_date.py @@ -9,76 +9,77 @@ from .timezone_utils import TimezoneTestCase class DateTests(TimezoneTestCase): - - @setup({'date01': '{{ d|date:"m" }}'}) + @setup({"date01": '{{ d|date:"m" }}'}) def test_date01(self): - output = self.engine.render_to_string('date01', {'d': datetime(2008, 1, 1)}) - self.assertEqual(output, '01') + output = self.engine.render_to_string("date01", {"d": datetime(2008, 1, 1)}) + self.assertEqual(output, "01") - @setup({'date02': '{{ d|date }}'}) + @setup({"date02": "{{ d|date }}"}) def test_date02(self): - output = self.engine.render_to_string('date02', {'d': datetime(2008, 1, 1)}) - self.assertEqual(output, 'Jan. 1, 2008') + output = self.engine.render_to_string("date02", {"d": datetime(2008, 1, 1)}) + self.assertEqual(output, "Jan. 1, 2008") - @setup({'date02_l10n': '{{ d|date }}'}) + @setup({"date02_l10n": "{{ d|date }}"}) def test_date02_l10n(self): """Without arg, the active language's DATE_FORMAT is used.""" - with translation.override('fr'): - output = self.engine.render_to_string('date02_l10n', {'d': datetime(2008, 1, 1)}) - self.assertEqual(output, '1 janvier 2008') + with translation.override("fr"): + output = self.engine.render_to_string( + "date02_l10n", {"d": datetime(2008, 1, 1)} + ) + self.assertEqual(output, "1 janvier 2008") - @setup({'date03': '{{ d|date:"m" }}'}) + @setup({"date03": '{{ d|date:"m" }}'}) def test_date03(self): """ #9520: Make sure |date doesn't blow up on non-dates """ - output = self.engine.render_to_string('date03', {'d': 'fail_string'}) - self.assertEqual(output, '') + output = self.engine.render_to_string("date03", {"d": "fail_string"}) + self.assertEqual(output, "") # ISO date formats - @setup({'date04': '{{ d|date:"o" }}'}) + @setup({"date04": '{{ d|date:"o" }}'}) def test_date04(self): - output = self.engine.render_to_string('date04', {'d': datetime(2008, 12, 29)}) - self.assertEqual(output, '2009') + output = self.engine.render_to_string("date04", {"d": datetime(2008, 12, 29)}) + self.assertEqual(output, "2009") - @setup({'date05': '{{ d|date:"o" }}'}) + @setup({"date05": '{{ d|date:"o" }}'}) def test_date05(self): - output = self.engine.render_to_string('date05', {'d': datetime(2010, 1, 3)}) - self.assertEqual(output, '2009') + output = self.engine.render_to_string("date05", {"d": datetime(2010, 1, 3)}) + self.assertEqual(output, "2009") # Timezone name - @setup({'date06': '{{ d|date:"e" }}'}) + @setup({"date06": '{{ d|date:"e" }}'}) def test_date06(self): output = self.engine.render_to_string( - 'date06', {'d': datetime(2009, 3, 12, tzinfo=timezone.get_fixed_timezone(30))} + "date06", + {"d": datetime(2009, 3, 12, tzinfo=timezone.get_fixed_timezone(30))}, ) - self.assertEqual(output, '+0030') + self.assertEqual(output, "+0030") - @setup({'date07': '{{ d|date:"e" }}'}) + @setup({"date07": '{{ d|date:"e" }}'}) def test_date07(self): - output = self.engine.render_to_string('date07', {'d': datetime(2009, 3, 12)}) - self.assertEqual(output, '') + output = self.engine.render_to_string("date07", {"d": datetime(2009, 3, 12)}) + self.assertEqual(output, "") # #19370: Make sure |date doesn't blow up on a midnight time object - @setup({'date08': '{{ t|date:"H:i" }}'}) + @setup({"date08": '{{ t|date:"H:i" }}'}) def test_date08(self): - output = self.engine.render_to_string('date08', {'t': time(0, 1)}) - self.assertEqual(output, '00:01') + output = self.engine.render_to_string("date08", {"t": time(0, 1)}) + self.assertEqual(output, "00:01") - @setup({'date09': '{{ t|date:"H:i" }}'}) + @setup({"date09": '{{ t|date:"H:i" }}'}) def test_date09(self): - output = self.engine.render_to_string('date09', {'t': time(0, 0)}) - self.assertEqual(output, '00:00') + output = self.engine.render_to_string("date09", {"t": time(0, 0)}) + self.assertEqual(output, "00:00") class FunctionTests(SimpleTestCase): - def test_date(self): - self.assertEqual(date(datetime(2005, 12, 29), "d F Y"), '29 December 2005') + self.assertEqual(date(datetime(2005, 12, 29), "d F Y"), "29 December 2005") def test_no_args(self): - self.assertEqual(date(''), '') - self.assertEqual(date(None), '') + self.assertEqual(date(""), "") + self.assertEqual(date(None), "") def test_escape_characters(self): - self.assertEqual(date(datetime(2005, 12, 29), r'jS \o\f F'), '29th of December') + self.assertEqual(date(datetime(2005, 12, 29), r"jS \o\f F"), "29th of December") diff --git a/tests/template_tests/filter_tests/test_default.py b/tests/template_tests/filter_tests/test_default.py index 4b6b9dd684..20621f610f 100644 --- a/tests/template_tests/filter_tests/test_default.py +++ b/tests/template_tests/filter_tests/test_default.py @@ -14,47 +14,49 @@ class DefaultTests(SimpleTestCase): variable string interferes with the test result. """ - @setup({'default01': '{{ a|default:"x<" }}'}) + @setup({"default01": '{{ a|default:"x<" }}'}) def test_default01(self): - output = self.engine.render_to_string('default01', {"a": ""}) + output = self.engine.render_to_string("default01", {"a": ""}) self.assertEqual(output, "x<") - @setup({'default02': '{% autoescape off %}{{ a|default:"x<" }}{% endautoescape %}'}) + @setup({"default02": '{% autoescape off %}{{ a|default:"x<" }}{% endautoescape %}'}) def test_default02(self): - output = self.engine.render_to_string('default02', {"a": ""}) + output = self.engine.render_to_string("default02", {"a": ""}) self.assertEqual(output, "x<") - @setup({'default03': '{{ a|default:"x<" }}'}) + @setup({"default03": '{{ a|default:"x<" }}'}) def test_default03(self): - output = self.engine.render_to_string('default03', {"a": mark_safe("x>")}) + output = self.engine.render_to_string("default03", {"a": mark_safe("x>")}) self.assertEqual(output, "x>") - @setup({'default04': '{% autoescape off %}{{ a|default:"x<" }}{% endautoescape %}'}) + @setup({"default04": '{% autoescape off %}{{ a|default:"x<" }}{% endautoescape %}'}) def test_default04(self): - output = self.engine.render_to_string('default04', {"a": mark_safe("x>")}) + output = self.engine.render_to_string("default04", {"a": mark_safe("x>")}) self.assertEqual(output, "x>") class DefaultIfNoneTests(SimpleTestCase): - - @setup({'default_if_none01': '{{ a|default:"x<" }}'}) + @setup({"default_if_none01": '{{ a|default:"x<" }}'}) def test_default_if_none01(self): - output = self.engine.render_to_string('default_if_none01', {"a": None}) + output = self.engine.render_to_string("default_if_none01", {"a": None}) self.assertEqual(output, "x<") - @setup({'default_if_none02': '{% autoescape off %}{{ a|default:"x<" }}{% endautoescape %}'}) + @setup( + { + "default_if_none02": '{% autoescape off %}{{ a|default:"x<" }}{% endautoescape %}' + } + ) def test_default_if_none02(self): - output = self.engine.render_to_string('default_if_none02', {"a": None}) + output = self.engine.render_to_string("default_if_none02", {"a": None}) self.assertEqual(output, "x<") class FunctionTests(SimpleTestCase): - def test_value(self): - self.assertEqual(default('val', 'default'), 'val') + self.assertEqual(default("val", "default"), "val") def test_none(self): - self.assertEqual(default(None, 'default'), 'default') + self.assertEqual(default(None, "default"), "default") def test_empty_string(self): - self.assertEqual(default('', 'default'), 'default') + self.assertEqual(default("", "default"), "default") diff --git a/tests/template_tests/filter_tests/test_default_if_none.py b/tests/template_tests/filter_tests/test_default_if_none.py index 45bd666913..a805f4cea4 100644 --- a/tests/template_tests/filter_tests/test_default_if_none.py +++ b/tests/template_tests/filter_tests/test_default_if_none.py @@ -3,12 +3,11 @@ from django.test import SimpleTestCase class FunctionTests(SimpleTestCase): - def test_value(self): - self.assertEqual(default_if_none("val", 'default'), 'val') + self.assertEqual(default_if_none("val", "default"), "val") def test_none(self): - self.assertEqual(default_if_none(None, 'default'), 'default') + self.assertEqual(default_if_none(None, "default"), "default") def test_empty_string(self): - self.assertEqual(default_if_none('', 'default'), '') + self.assertEqual(default_if_none("", "default"), "") diff --git a/tests/template_tests/filter_tests/test_dictsort.py b/tests/template_tests/filter_tests/test_dictsort.py index 3de247fd86..9f0cd8a0f0 100644 --- a/tests/template_tests/filter_tests/test_dictsort.py +++ b/tests/template_tests/filter_tests/test_dictsort.py @@ -3,49 +3,50 @@ from django.test import SimpleTestCase class User: - password = 'abc' + password = "abc" - _private = 'private' + _private = "private" @property def test_property(self): - return 'cde' + return "cde" def test_method(self): """This is just a test method.""" class FunctionTests(SimpleTestCase): - def test_property_resolver(self): user = User() - dict_data = {'a': { - 'b1': {'c': 'result1'}, - 'b2': user, - 'b3': {'0': 'result2'}, - 'b4': [0, 1, 2], - }} - list_data = ['a', 'b', 'c'] + dict_data = { + "a": { + "b1": {"c": "result1"}, + "b2": user, + "b3": {"0": "result2"}, + "b4": [0, 1, 2], + } + } + list_data = ["a", "b", "c"] tests = [ - ('a.b1.c', dict_data, 'result1'), - ('a.b2.password', dict_data, 'abc'), - ('a.b2.test_property', dict_data, 'cde'), + ("a.b1.c", dict_data, "result1"), + ("a.b2.password", dict_data, "abc"), + ("a.b2.test_property", dict_data, "cde"), # The method should not get called. - ('a.b2.test_method', dict_data, user.test_method), - ('a.b3.0', dict_data, 'result2'), - (0, list_data, 'a'), + ("a.b2.test_method", dict_data, user.test_method), + ("a.b3.0", dict_data, "result2"), + (0, list_data, "a"), ] for arg, data, expected_value in tests: with self.subTest(arg=arg): self.assertEqual(_property_resolver(arg)(data), expected_value) # Invalid lookups. fail_tests = [ - ('a.b1.d', dict_data, AttributeError), - ('a.b2.password.0', dict_data, AttributeError), - ('a.b2._private', dict_data, AttributeError), - ('a.b4.0', dict_data, AttributeError), - ('a', list_data, AttributeError), - ('0', list_data, TypeError), + ("a.b1.d", dict_data, AttributeError), + ("a.b2.password.0", dict_data, AttributeError), + ("a.b2._private", dict_data, AttributeError), + ("a.b4.0", dict_data, AttributeError), + ("a", list_data, AttributeError), + ("0", list_data, TypeError), (4, list_data, IndexError), ] for arg, data, expected_exception in fail_tests: @@ -55,17 +56,21 @@ class FunctionTests(SimpleTestCase): def test_sort(self): sorted_dicts = dictsort( - [{'age': 23, 'name': 'Barbara-Ann'}, - {'age': 63, 'name': 'Ra Ra Rasputin'}, - {'name': 'Jonny B Goode', 'age': 18}], - 'age', + [ + {"age": 23, "name": "Barbara-Ann"}, + {"age": 63, "name": "Ra Ra Rasputin"}, + {"name": "Jonny B Goode", "age": 18}, + ], + "age", ) self.assertEqual( [sorted(dict.items()) for dict in sorted_dicts], - [[('age', 18), ('name', 'Jonny B Goode')], - [('age', 23), ('name', 'Barbara-Ann')], - [('age', 63), ('name', 'Ra Ra Rasputin')]], + [ + [("age", 18), ("name", "Jonny B Goode")], + [("age", 23), ("name", "Barbara-Ann")], + [("age", 63), ("name", "Ra Ra Rasputin")], + ], ) def test_dictsort_complex_sorting_key(self): @@ -74,44 +79,46 @@ class FunctionTests(SimpleTestCase): on keys like 'foo.bar'. """ data = [ - {'foo': {'bar': 1, 'baz': 'c'}}, - {'foo': {'bar': 2, 'baz': 'b'}}, - {'foo': {'bar': 3, 'baz': 'a'}}, + {"foo": {"bar": 1, "baz": "c"}}, + {"foo": {"bar": 2, "baz": "b"}}, + {"foo": {"bar": 3, "baz": "a"}}, ] - sorted_data = dictsort(data, 'foo.baz') + sorted_data = dictsort(data, "foo.baz") - self.assertEqual([d['foo']['bar'] for d in sorted_data], [3, 2, 1]) + self.assertEqual([d["foo"]["bar"] for d in sorted_data], [3, 2, 1]) def test_sort_list_of_tuples(self): - data = [('a', '42'), ('c', 'string'), ('b', 'foo')] - expected = [('a', '42'), ('b', 'foo'), ('c', 'string')] + data = [("a", "42"), ("c", "string"), ("b", "foo")] + expected = [("a", "42"), ("b", "foo"), ("c", "string")] self.assertEqual(dictsort(data, 0), expected) def test_sort_list_of_tuple_like_dicts(self): data = [ - {'0': 'a', '1': '42'}, - {'0': 'c', '1': 'string'}, - {'0': 'b', '1': 'foo'}, + {"0": "a", "1": "42"}, + {"0": "c", "1": "string"}, + {"0": "b", "1": "foo"}, ] expected = [ - {'0': 'a', '1': '42'}, - {'0': 'b', '1': 'foo'}, - {'0': 'c', '1': 'string'}, + {"0": "a", "1": "42"}, + {"0": "b", "1": "foo"}, + {"0": "c", "1": "string"}, ] - self.assertEqual(dictsort(data, '0'), expected) + self.assertEqual(dictsort(data, "0"), expected) def test_invalid_values(self): """ If dictsort is passed something other than a list of dictionaries, fail silently. """ - self.assertEqual(dictsort([1, 2, 3], 'age'), '') - self.assertEqual(dictsort('Hello!', 'age'), '') - self.assertEqual(dictsort({'a': 1}, 'age'), '') - self.assertEqual(dictsort(1, 'age'), '') + self.assertEqual(dictsort([1, 2, 3], "age"), "") + self.assertEqual(dictsort("Hello!", "age"), "") + self.assertEqual(dictsort({"a": 1}, "age"), "") + self.assertEqual(dictsort(1, "age"), "") def test_invalid_args(self): """Fail silently if invalid lookups are passed.""" - self.assertEqual(dictsort([{}], '._private'), '') - self.assertEqual(dictsort([{'_private': 'test'}], '_private'), '') - self.assertEqual(dictsort([{'nested': {'_private': 'test'}}], 'nested._private'), '') + self.assertEqual(dictsort([{}], "._private"), "") + self.assertEqual(dictsort([{"_private": "test"}], "_private"), "") + self.assertEqual( + dictsort([{"nested": {"_private": "test"}}], "nested._private"), "" + ) diff --git a/tests/template_tests/filter_tests/test_dictsortreversed.py b/tests/template_tests/filter_tests/test_dictsortreversed.py index e2e24e3128..c7cf40d1b4 100644 --- a/tests/template_tests/filter_tests/test_dictsortreversed.py +++ b/tests/template_tests/filter_tests/test_dictsortreversed.py @@ -3,52 +3,57 @@ from django.test import SimpleTestCase class FunctionTests(SimpleTestCase): - def test_sort(self): sorted_dicts = dictsortreversed( - [{'age': 23, 'name': 'Barbara-Ann'}, - {'age': 63, 'name': 'Ra Ra Rasputin'}, - {'name': 'Jonny B Goode', 'age': 18}], - 'age', + [ + {"age": 23, "name": "Barbara-Ann"}, + {"age": 63, "name": "Ra Ra Rasputin"}, + {"name": "Jonny B Goode", "age": 18}, + ], + "age", ) self.assertEqual( [sorted(dict.items()) for dict in sorted_dicts], - [[('age', 63), ('name', 'Ra Ra Rasputin')], - [('age', 23), ('name', 'Barbara-Ann')], - [('age', 18), ('name', 'Jonny B Goode')]], + [ + [("age", 63), ("name", "Ra Ra Rasputin")], + [("age", 23), ("name", "Barbara-Ann")], + [("age", 18), ("name", "Jonny B Goode")], + ], ) def test_sort_list_of_tuples(self): - data = [('a', '42'), ('c', 'string'), ('b', 'foo')] - expected = [('c', 'string'), ('b', 'foo'), ('a', '42')] + data = [("a", "42"), ("c", "string"), ("b", "foo")] + expected = [("c", "string"), ("b", "foo"), ("a", "42")] self.assertEqual(dictsortreversed(data, 0), expected) def test_sort_list_of_tuple_like_dicts(self): data = [ - {'0': 'a', '1': '42'}, - {'0': 'c', '1': 'string'}, - {'0': 'b', '1': 'foo'}, + {"0": "a", "1": "42"}, + {"0": "c", "1": "string"}, + {"0": "b", "1": "foo"}, ] expected = [ - {'0': 'c', '1': 'string'}, - {'0': 'b', '1': 'foo'}, - {'0': 'a', '1': '42'}, + {"0": "c", "1": "string"}, + {"0": "b", "1": "foo"}, + {"0": "a", "1": "42"}, ] - self.assertEqual(dictsortreversed(data, '0'), expected) + self.assertEqual(dictsortreversed(data, "0"), expected) def test_invalid_values(self): """ If dictsortreversed is passed something other than a list of dictionaries, fail silently. """ - self.assertEqual(dictsortreversed([1, 2, 3], 'age'), '') - self.assertEqual(dictsortreversed('Hello!', 'age'), '') - self.assertEqual(dictsortreversed({'a': 1}, 'age'), '') - self.assertEqual(dictsortreversed(1, 'age'), '') + self.assertEqual(dictsortreversed([1, 2, 3], "age"), "") + self.assertEqual(dictsortreversed("Hello!", "age"), "") + self.assertEqual(dictsortreversed({"a": 1}, "age"), "") + self.assertEqual(dictsortreversed(1, "age"), "") def test_invalid_args(self): """Fail silently if invalid lookups are passed.""" - self.assertEqual(dictsortreversed([{}], '._private'), '') - self.assertEqual(dictsortreversed([{'_private': 'test'}], '_private'), '') - self.assertEqual(dictsortreversed([{'nested': {'_private': 'test'}}], 'nested._private'), '') + self.assertEqual(dictsortreversed([{}], "._private"), "") + self.assertEqual(dictsortreversed([{"_private": "test"}], "_private"), "") + self.assertEqual( + dictsortreversed([{"nested": {"_private": "test"}}], "nested._private"), "" + ) diff --git a/tests/template_tests/filter_tests/test_divisibleby.py b/tests/template_tests/filter_tests/test_divisibleby.py index f0dda1f0b6..27807de213 100644 --- a/tests/template_tests/filter_tests/test_divisibleby.py +++ b/tests/template_tests/filter_tests/test_divisibleby.py @@ -3,7 +3,6 @@ from django.test import SimpleTestCase class FunctionTests(SimpleTestCase): - def test_true(self): self.assertIs(divisibleby(4, 2), True) diff --git a/tests/template_tests/filter_tests/test_escape.py b/tests/template_tests/filter_tests/test_escape.py index 22d5ca7d55..16471ad53f 100644 --- a/tests/template_tests/filter_tests/test_escape.py +++ b/tests/template_tests/filter_tests/test_escape.py @@ -12,34 +12,41 @@ class EscapeTests(SimpleTestCase): but it has no effect on strings already marked as safe. """ - @setup({'escape01': '{{ a|escape }} {{ b|escape }}'}) + @setup({"escape01": "{{ a|escape }} {{ b|escape }}"}) def test_escape01(self): - output = self.engine.render_to_string('escape01', {"a": "x&y", "b": mark_safe("x&y")}) + output = self.engine.render_to_string( + "escape01", {"a": "x&y", "b": mark_safe("x&y")} + ) self.assertEqual(output, "x&y x&y") - @setup({'escape02': '{% autoescape off %}{{ a|escape }} {{ b|escape }}{% endautoescape %}'}) + @setup( + { + "escape02": "{% autoescape off %}{{ a|escape }} {{ b|escape }}{% endautoescape %}" + } + ) def test_escape02(self): - output = self.engine.render_to_string('escape02', {"a": "x&y", "b": mark_safe("x&y")}) + output = self.engine.render_to_string( + "escape02", {"a": "x&y", "b": mark_safe("x&y")} + ) self.assertEqual(output, "x&y x&y") - @setup({'escape03': '{% autoescape off %}{{ a|escape|escape }}{% endautoescape %}'}) + @setup({"escape03": "{% autoescape off %}{{ a|escape|escape }}{% endautoescape %}"}) def test_escape03(self): - output = self.engine.render_to_string('escape03', {"a": "x&y"}) + output = self.engine.render_to_string("escape03", {"a": "x&y"}) self.assertEqual(output, "x&y") - @setup({'escape04': '{{ a|escape|escape }}'}) + @setup({"escape04": "{{ a|escape|escape }}"}) def test_escape04(self): - output = self.engine.render_to_string('escape04', {"a": "x&y"}) + output = self.engine.render_to_string("escape04", {"a": "x&y"}) self.assertEqual(output, "x&y") def test_escape_lazy_string(self): - add_html = lazy(lambda string: string + 'special characters > here', str) - escaped = escape(add_html('<some html & ')) + add_html = lazy(lambda string: string + "special characters > here", str) + escaped = escape(add_html("<some html & ")) self.assertIsInstance(escaped, Promise) - self.assertEqual(escaped, '<some html & special characters > here') + self.assertEqual(escaped, "<some html & special characters > here") class FunctionTests(SimpleTestCase): - def test_non_string_input(self): - self.assertEqual(escape(123), '123') + self.assertEqual(escape(123), "123") diff --git a/tests/template_tests/filter_tests/test_escapejs.py b/tests/template_tests/filter_tests/test_escapejs.py index 9aa98819e1..7a5c3879b0 100644 --- a/tests/template_tests/filter_tests/test_escapejs.py +++ b/tests/template_tests/filter_tests/test_escapejs.py @@ -6,55 +6,65 @@ from ..utils import setup class EscapejsTests(SimpleTestCase): - - @setup({'escapejs01': '{{ a|escapejs }}'}) + @setup({"escapejs01": "{{ a|escapejs }}"}) def test_escapejs01(self): - output = self.engine.render_to_string('escapejs01', {'a': 'testing\r\njavascript \'string" <b>escaping</b>'}) - self.assertEqual(output, 'testing\\u000D\\u000Ajavascript ' - '\\u0027string\\u0022 \\u003Cb\\u003E' - 'escaping\\u003C/b\\u003E') + output = self.engine.render_to_string( + "escapejs01", {"a": "testing\r\njavascript 'string\" <b>escaping</b>"} + ) + self.assertEqual( + output, + "testing\\u000D\\u000Ajavascript " + "\\u0027string\\u0022 \\u003Cb\\u003E" + "escaping\\u003C/b\\u003E", + ) - @setup({'escapejs02': '{% autoescape off %}{{ a|escapejs }}{% endautoescape %}'}) + @setup({"escapejs02": "{% autoescape off %}{{ a|escapejs }}{% endautoescape %}"}) def test_escapejs02(self): - output = self.engine.render_to_string('escapejs02', {'a': 'testing\r\njavascript \'string" <b>escaping</b>'}) - self.assertEqual(output, 'testing\\u000D\\u000Ajavascript ' - '\\u0027string\\u0022 \\u003Cb\\u003E' - 'escaping\\u003C/b\\u003E') + output = self.engine.render_to_string( + "escapejs02", {"a": "testing\r\njavascript 'string\" <b>escaping</b>"} + ) + self.assertEqual( + output, + "testing\\u000D\\u000Ajavascript " + "\\u0027string\\u0022 \\u003Cb\\u003E" + "escaping\\u003C/b\\u003E", + ) class FunctionTests(SimpleTestCase): - def test_quotes(self): self.assertEqual( - escapejs_filter('"double quotes" and \'single quotes\''), - '\\u0022double quotes\\u0022 and \\u0027single quotes\\u0027', + escapejs_filter("\"double quotes\" and 'single quotes'"), + "\\u0022double quotes\\u0022 and \\u0027single quotes\\u0027", ) def test_backslashes(self): - self.assertEqual(escapejs_filter(r'\ : backslashes, too'), '\\u005C : backslashes, too') + self.assertEqual( + escapejs_filter(r"\ : backslashes, too"), "\\u005C : backslashes, too" + ) def test_whitespace(self): self.assertEqual( - escapejs_filter('and lots of whitespace: \r\n\t\v\f\b'), - 'and lots of whitespace: \\u000D\\u000A\\u0009\\u000B\\u000C\\u0008', + escapejs_filter("and lots of whitespace: \r\n\t\v\f\b"), + "and lots of whitespace: \\u000D\\u000A\\u0009\\u000B\\u000C\\u0008", ) def test_script(self): self.assertEqual( - escapejs_filter(r'<script>and this</script>'), - '\\u003Cscript\\u003Eand this\\u003C/script\\u003E', + escapejs_filter(r"<script>and this</script>"), + "\\u003Cscript\\u003Eand this\\u003C/script\\u003E", ) def test_paragraph_separator(self): self.assertEqual( - escapejs_filter('paragraph separator:\u2029and line separator:\u2028'), - 'paragraph separator:\\u2029and line separator:\\u2028', + escapejs_filter("paragraph separator:\u2029and line separator:\u2028"), + "paragraph separator:\\u2029and line separator:\\u2028", ) def test_lazy_string(self): - append_script = lazy(lambda string: r'<script>this</script>' + string, str) + append_script = lazy(lambda string: r"<script>this</script>" + string, str) self.assertEqual( - escapejs_filter(append_script('whitespace: \r\n\t\v\f\b')), - '\\u003Cscript\\u003Ethis\\u003C/script\\u003E' - 'whitespace: \\u000D\\u000A\\u0009\\u000B\\u000C\\u0008' + escapejs_filter(append_script("whitespace: \r\n\t\v\f\b")), + "\\u003Cscript\\u003Ethis\\u003C/script\\u003E" + "whitespace: \\u000D\\u000A\\u0009\\u000B\\u000C\\u0008", ) diff --git a/tests/template_tests/filter_tests/test_filesizeformat.py b/tests/template_tests/filter_tests/test_filesizeformat.py index 3b3e02eadb..fee742f9d5 100644 --- a/tests/template_tests/filter_tests/test_filesizeformat.py +++ b/tests/template_tests/filter_tests/test_filesizeformat.py @@ -4,25 +4,24 @@ from django.utils import translation class FunctionTests(SimpleTestCase): - def test_formats(self): tests = [ - (0, '0\xa0bytes'), - (1, '1\xa0byte'), - (1023, '1023\xa0bytes'), - (1024, '1.0\xa0KB'), - (10 * 1024, '10.0\xa0KB'), - (1024 * 1024 - 1, '1024.0\xa0KB'), - (1024 * 1024, '1.0\xa0MB'), - (1024 * 1024 * 50, '50.0\xa0MB'), - (1024 * 1024 * 1024 - 1, '1024.0\xa0MB'), - (1024 * 1024 * 1024, '1.0\xa0GB'), - (1024 * 1024 * 1024 * 1024, '1.0\xa0TB'), - (1024 * 1024 * 1024 * 1024 * 1024, '1.0\xa0PB'), - (1024 * 1024 * 1024 * 1024 * 1024 * 2000, '2000.0\xa0PB'), - (complex(1, -1), '0\xa0bytes'), - ('', '0\xa0bytes'), - ('\N{GREEK SMALL LETTER ALPHA}', '0\xa0bytes'), + (0, "0\xa0bytes"), + (1, "1\xa0byte"), + (1023, "1023\xa0bytes"), + (1024, "1.0\xa0KB"), + (10 * 1024, "10.0\xa0KB"), + (1024 * 1024 - 1, "1024.0\xa0KB"), + (1024 * 1024, "1.0\xa0MB"), + (1024 * 1024 * 50, "50.0\xa0MB"), + (1024 * 1024 * 1024 - 1, "1024.0\xa0MB"), + (1024 * 1024 * 1024, "1.0\xa0GB"), + (1024 * 1024 * 1024 * 1024, "1.0\xa0TB"), + (1024 * 1024 * 1024 * 1024 * 1024, "1.0\xa0PB"), + (1024 * 1024 * 1024 * 1024 * 1024 * 2000, "2000.0\xa0PB"), + (complex(1, -1), "0\xa0bytes"), + ("", "0\xa0bytes"), + ("\N{GREEK SMALL LETTER ALPHA}", "0\xa0bytes"), ] for value, expected in tests: with self.subTest(value=value): @@ -30,33 +29,33 @@ class FunctionTests(SimpleTestCase): def test_localized_formats(self): tests = [ - (0, '0\xa0Bytes'), - (1, '1\xa0Byte'), - (1023, '1023\xa0Bytes'), - (1024, '1,0\xa0KB'), - (10 * 1024, '10,0\xa0KB'), - (1024 * 1024 - 1, '1024,0\xa0KB'), - (1024 * 1024, '1,0\xa0MB'), - (1024 * 1024 * 50, '50,0\xa0MB'), - (1024 * 1024 * 1024 - 1, '1024,0\xa0MB'), - (1024 * 1024 * 1024, '1,0\xa0GB'), - (1024 * 1024 * 1024 * 1024, '1,0\xa0TB'), - (1024 * 1024 * 1024 * 1024 * 1024, '1,0\xa0PB'), - (1024 * 1024 * 1024 * 1024 * 1024 * 2000, '2000,0\xa0PB'), - (complex(1, -1), '0\xa0Bytes'), - ('', '0\xa0Bytes'), - ('\N{GREEK SMALL LETTER ALPHA}', '0\xa0Bytes'), + (0, "0\xa0Bytes"), + (1, "1\xa0Byte"), + (1023, "1023\xa0Bytes"), + (1024, "1,0\xa0KB"), + (10 * 1024, "10,0\xa0KB"), + (1024 * 1024 - 1, "1024,0\xa0KB"), + (1024 * 1024, "1,0\xa0MB"), + (1024 * 1024 * 50, "50,0\xa0MB"), + (1024 * 1024 * 1024 - 1, "1024,0\xa0MB"), + (1024 * 1024 * 1024, "1,0\xa0GB"), + (1024 * 1024 * 1024 * 1024, "1,0\xa0TB"), + (1024 * 1024 * 1024 * 1024 * 1024, "1,0\xa0PB"), + (1024 * 1024 * 1024 * 1024 * 1024 * 2000, "2000,0\xa0PB"), + (complex(1, -1), "0\xa0Bytes"), + ("", "0\xa0Bytes"), + ("\N{GREEK SMALL LETTER ALPHA}", "0\xa0Bytes"), ] - with translation.override('de'): + with translation.override("de"): for value, expected in tests: with self.subTest(value=value): self.assertEqual(filesizeformat(value), expected) def test_negative_numbers(self): tests = [ - (-1, '-1\xa0byte'), - (-100, '-100\xa0bytes'), - (-1024 * 1024 * 50, '-50.0\xa0MB'), + (-1, "-1\xa0byte"), + (-100, "-100\xa0bytes"), + (-1024 * 1024 * 50, "-50.0\xa0MB"), ] for value, expected in tests: with self.subTest(value=value): diff --git a/tests/template_tests/filter_tests/test_first.py b/tests/template_tests/filter_tests/test_first.py index efba48f870..7a1849cd88 100644 --- a/tests/template_tests/filter_tests/test_first.py +++ b/tests/template_tests/filter_tests/test_first.py @@ -6,25 +6,31 @@ from ..utils import setup class FirstTests(SimpleTestCase): - - @setup({'first01': '{{ a|first }} {{ b|first }}'}) + @setup({"first01": "{{ a|first }} {{ b|first }}"}) def test_first01(self): - output = self.engine.render_to_string('first01', {"a": ["a&b", "x"], "b": [mark_safe("a&b"), "x"]}) + output = self.engine.render_to_string( + "first01", {"a": ["a&b", "x"], "b": [mark_safe("a&b"), "x"]} + ) self.assertEqual(output, "a&b a&b") - @setup({'first02': '{% autoescape off %}{{ a|first }} {{ b|first }}{% endautoescape %}'}) + @setup( + { + "first02": "{% autoescape off %}{{ a|first }} {{ b|first }}{% endautoescape %}" + } + ) def test_first02(self): - output = self.engine.render_to_string('first02', {"a": ["a&b", "x"], "b": [mark_safe("a&b"), "x"]}) + output = self.engine.render_to_string( + "first02", {"a": ["a&b", "x"], "b": [mark_safe("a&b"), "x"]} + ) self.assertEqual(output, "a&b a&b") class FunctionTests(SimpleTestCase): - def test_list(self): self.assertEqual(first([0, 1, 2]), 0) def test_empty_string(self): - self.assertEqual(first(''), '') + self.assertEqual(first(""), "") def test_string(self): - self.assertEqual(first('test'), 't') + self.assertEqual(first("test"), "t") diff --git a/tests/template_tests/filter_tests/test_floatformat.py b/tests/template_tests/filter_tests/test_floatformat.py index 1035fb96da..d7eb5f2076 100644 --- a/tests/template_tests/filter_tests/test_floatformat.py +++ b/tests/template_tests/filter_tests/test_floatformat.py @@ -9,93 +9,107 @@ from ..utils import setup class FloatformatTests(SimpleTestCase): - - @setup({'floatformat01': '{% autoescape off %}{{ a|floatformat }} {{ b|floatformat }}{% endautoescape %}'}) + @setup( + { + "floatformat01": "{% autoescape off %}{{ a|floatformat }} {{ b|floatformat }}{% endautoescape %}" + } + ) def test_floatformat01(self): - output = self.engine.render_to_string('floatformat01', {"a": "1.42", "b": mark_safe("1.42")}) + output = self.engine.render_to_string( + "floatformat01", {"a": "1.42", "b": mark_safe("1.42")} + ) self.assertEqual(output, "1.4 1.4") - @setup({'floatformat02': '{{ a|floatformat }} {{ b|floatformat }}'}) + @setup({"floatformat02": "{{ a|floatformat }} {{ b|floatformat }}"}) def test_floatformat02(self): - output = self.engine.render_to_string('floatformat02', {"a": "1.42", "b": mark_safe("1.42")}) + output = self.engine.render_to_string( + "floatformat02", {"a": "1.42", "b": mark_safe("1.42")} + ) self.assertEqual(output, "1.4 1.4") class FunctionTests(SimpleTestCase): - def test_inputs(self): - self.assertEqual(floatformat(7.7), '7.7') - self.assertEqual(floatformat(7.0), '7') - self.assertEqual(floatformat(0.7), '0.7') - self.assertEqual(floatformat(-0.7), '-0.7') - self.assertEqual(floatformat(0.07), '0.1') - self.assertEqual(floatformat(-0.07), '-0.1') - self.assertEqual(floatformat(0.007), '0.0') - self.assertEqual(floatformat(0.0), '0') - self.assertEqual(floatformat(7.7, 0), '8') - self.assertEqual(floatformat(7.7, 3), '7.700') - self.assertEqual(floatformat(6.000000, 3), '6.000') - self.assertEqual(floatformat(6.200000, 3), '6.200') - self.assertEqual(floatformat(6.200000, -3), '6.200') - self.assertEqual(floatformat(13.1031, -3), '13.103') - self.assertEqual(floatformat(11.1197, -2), '11.12') - self.assertEqual(floatformat(11.0000, -2), '11') - self.assertEqual(floatformat(11.000001, -2), '11.00') - self.assertEqual(floatformat(8.2798, 3), '8.280') - self.assertEqual(floatformat(5555.555, 2), '5555.56') - self.assertEqual(floatformat(001.3000, 2), '1.30') - self.assertEqual(floatformat(0.12345, 2), '0.12') - self.assertEqual(floatformat(Decimal('555.555'), 2), '555.56') - self.assertEqual(floatformat(Decimal('09.000')), '9') - self.assertEqual(floatformat('foo'), '') - self.assertEqual(floatformat(13.1031, 'bar'), '13.1031') - self.assertEqual(floatformat(18.125, 2), '18.13') - self.assertEqual(floatformat('foo', 'bar'), '') - self.assertEqual(floatformat('¿Cómo esta usted?'), '') - self.assertEqual(floatformat(None), '') - self.assertEqual(floatformat(-1.323297138040798e+35, 2), '-132329713804079800000000000000000000.00') - self.assertEqual(floatformat(-1.323297138040798e+35, -2), '-132329713804079800000000000000000000') - self.assertEqual(floatformat(1.5e-15, 20), '0.00000000000000150000') - self.assertEqual(floatformat(1.5e-15, -20), '0.00000000000000150000') - self.assertEqual(floatformat(1.00000000000000015, 16), '1.0000000000000002') + self.assertEqual(floatformat(7.7), "7.7") + self.assertEqual(floatformat(7.0), "7") + self.assertEqual(floatformat(0.7), "0.7") + self.assertEqual(floatformat(-0.7), "-0.7") + self.assertEqual(floatformat(0.07), "0.1") + self.assertEqual(floatformat(-0.07), "-0.1") + self.assertEqual(floatformat(0.007), "0.0") + self.assertEqual(floatformat(0.0), "0") + self.assertEqual(floatformat(7.7, 0), "8") + self.assertEqual(floatformat(7.7, 3), "7.700") + self.assertEqual(floatformat(6.000000, 3), "6.000") + self.assertEqual(floatformat(6.200000, 3), "6.200") + self.assertEqual(floatformat(6.200000, -3), "6.200") + self.assertEqual(floatformat(13.1031, -3), "13.103") + self.assertEqual(floatformat(11.1197, -2), "11.12") + self.assertEqual(floatformat(11.0000, -2), "11") + self.assertEqual(floatformat(11.000001, -2), "11.00") + self.assertEqual(floatformat(8.2798, 3), "8.280") + self.assertEqual(floatformat(5555.555, 2), "5555.56") + self.assertEqual(floatformat(001.3000, 2), "1.30") + self.assertEqual(floatformat(0.12345, 2), "0.12") + self.assertEqual(floatformat(Decimal("555.555"), 2), "555.56") + self.assertEqual(floatformat(Decimal("09.000")), "9") + self.assertEqual(floatformat("foo"), "") + self.assertEqual(floatformat(13.1031, "bar"), "13.1031") + self.assertEqual(floatformat(18.125, 2), "18.13") + self.assertEqual(floatformat("foo", "bar"), "") + self.assertEqual(floatformat("¿Cómo esta usted?"), "") + self.assertEqual(floatformat(None), "") + self.assertEqual( + floatformat(-1.323297138040798e35, 2), + "-132329713804079800000000000000000000.00", + ) + self.assertEqual( + floatformat(-1.323297138040798e35, -2), + "-132329713804079800000000000000000000", + ) + self.assertEqual(floatformat(1.5e-15, 20), "0.00000000000000150000") + self.assertEqual(floatformat(1.5e-15, -20), "0.00000000000000150000") + self.assertEqual(floatformat(1.00000000000000015, 16), "1.0000000000000002") def test_force_grouping(self): - with translation.override('en'): - self.assertEqual(floatformat(10000, 'g'), '10,000') - self.assertEqual(floatformat(66666.666, '1g'), '66,666.7') + with translation.override("en"): + self.assertEqual(floatformat(10000, "g"), "10,000") + self.assertEqual(floatformat(66666.666, "1g"), "66,666.7") # Invalid suffix. - self.assertEqual(floatformat(10000, 'g2'), '10000') - with translation.override('de', deactivate=True): - self.assertEqual(floatformat(10000, 'g'), '10.000') - self.assertEqual(floatformat(66666.666, '1g'), '66.666,7') + self.assertEqual(floatformat(10000, "g2"), "10000") + with translation.override("de", deactivate=True): + self.assertEqual(floatformat(10000, "g"), "10.000") + self.assertEqual(floatformat(66666.666, "1g"), "66.666,7") # Invalid suffix. - self.assertEqual(floatformat(10000, 'g2'), '10000') + self.assertEqual(floatformat(10000, "g2"), "10000") def test_unlocalize(self): - with translation.override('de', deactivate=True): - self.assertEqual(floatformat(66666.666, '2'), '66666,67') - self.assertEqual(floatformat(66666.666, '2u'), '66666.67') + with translation.override("de", deactivate=True): + self.assertEqual(floatformat(66666.666, "2"), "66666,67") + self.assertEqual(floatformat(66666.666, "2u"), "66666.67") with self.settings( USE_THOUSAND_SEPARATOR=True, NUMBER_GROUPING=3, - THOUSAND_SEPARATOR='!', + THOUSAND_SEPARATOR="!", ): - self.assertEqual(floatformat(66666.666, '2gu'), '66!666.67') - self.assertEqual(floatformat(66666.666, '2ug'), '66!666.67') + self.assertEqual(floatformat(66666.666, "2gu"), "66!666.67") + self.assertEqual(floatformat(66666.666, "2ug"), "66!666.67") # Invalid suffix. - self.assertEqual(floatformat(66666.666, 'u2'), '66666.666') + self.assertEqual(floatformat(66666.666, "u2"), "66666.666") def test_zero_values(self): - self.assertEqual(floatformat(0, 6), '0.000000') - self.assertEqual(floatformat(0, 7), '0.0000000') - self.assertEqual(floatformat(0, 10), '0.0000000000') - self.assertEqual(floatformat(0.000000000000000000015, 20), '0.00000000000000000002') + self.assertEqual(floatformat(0, 6), "0.000000") + self.assertEqual(floatformat(0, 7), "0.0000000") + self.assertEqual(floatformat(0, 10), "0.0000000000") + self.assertEqual( + floatformat(0.000000000000000000015, 20), "0.00000000000000000002" + ) def test_negative_zero_values(self): tests = [ - (-0.01, -1, '0.0'), - (-0.001, 2, '0.00'), - (-0.499, 0, '0'), + (-0.01, -1, "0.0"), + (-0.001, 2, "0.00"), + (-0.499, 0, "0"), ] for num, decimal_places, expected in tests: with self.subTest(num=num, decimal_places=decimal_places): @@ -104,9 +118,9 @@ class FunctionTests(SimpleTestCase): def test_infinity(self): pos_inf = float(1e30000) neg_inf = float(-1e30000) - self.assertEqual(floatformat(pos_inf), 'inf') - self.assertEqual(floatformat(neg_inf), '-inf') - self.assertEqual(floatformat(pos_inf / pos_inf), 'nan') + self.assertEqual(floatformat(pos_inf), "inf") + self.assertEqual(floatformat(neg_inf), "-inf") + self.assertEqual(floatformat(pos_inf / pos_inf), "nan") def test_float_dunder_method(self): class FloatWrapper: @@ -116,7 +130,7 @@ class FunctionTests(SimpleTestCase): def __float__(self): return self.value - self.assertEqual(floatformat(FloatWrapper(11.000001), -2), '11.00') + self.assertEqual(floatformat(FloatWrapper(11.000001), -2), "11.00") def test_low_decimal_precision(self): """ @@ -124,9 +138,9 @@ class FunctionTests(SimpleTestCase): """ with localcontext() as ctx: ctx.prec = 2 - self.assertEqual(floatformat(1.2345, 2), '1.23') - self.assertEqual(floatformat(15.2042, -3), '15.204') - self.assertEqual(floatformat(1.2345, '2'), '1.23') - self.assertEqual(floatformat(15.2042, '-3'), '15.204') - self.assertEqual(floatformat(Decimal('1.2345'), 2), '1.23') - self.assertEqual(floatformat(Decimal('15.2042'), -3), '15.204') + self.assertEqual(floatformat(1.2345, 2), "1.23") + self.assertEqual(floatformat(15.2042, -3), "15.204") + self.assertEqual(floatformat(1.2345, "2"), "1.23") + self.assertEqual(floatformat(15.2042, "-3"), "15.204") + self.assertEqual(floatformat(Decimal("1.2345"), 2), "1.23") + self.assertEqual(floatformat(Decimal("15.2042"), -3), "15.204") diff --git a/tests/template_tests/filter_tests/test_force_escape.py b/tests/template_tests/filter_tests/test_force_escape.py index 776dc8042d..7a34caee2b 100644 --- a/tests/template_tests/filter_tests/test_force_escape.py +++ b/tests/template_tests/filter_tests/test_force_escape.py @@ -11,58 +11,73 @@ class ForceEscapeTests(SimpleTestCase): double-escaping, for example. """ - @setup({'force-escape01': '{% autoescape off %}{{ a|force_escape }}{% endautoescape %}'}) + @setup( + { + "force-escape01": "{% autoescape off %}{{ a|force_escape }}{% endautoescape %}" + } + ) def test_force_escape01(self): - output = self.engine.render_to_string('force-escape01', {"a": "x&y"}) + output = self.engine.render_to_string("force-escape01", {"a": "x&y"}) self.assertEqual(output, "x&y") - @setup({'force-escape02': '{{ a|force_escape }}'}) + @setup({"force-escape02": "{{ a|force_escape }}"}) def test_force_escape02(self): - output = self.engine.render_to_string('force-escape02', {"a": "x&y"}) + output = self.engine.render_to_string("force-escape02", {"a": "x&y"}) self.assertEqual(output, "x&y") - @setup({'force-escape03': '{% autoescape off %}{{ a|force_escape|force_escape }}{% endautoescape %}'}) + @setup( + { + "force-escape03": "{% autoescape off %}{{ a|force_escape|force_escape }}{% endautoescape %}" + } + ) def test_force_escape03(self): - output = self.engine.render_to_string('force-escape03', {"a": "x&y"}) + output = self.engine.render_to_string("force-escape03", {"a": "x&y"}) self.assertEqual(output, "x&amp;y") - @setup({'force-escape04': '{{ a|force_escape|force_escape }}'}) + @setup({"force-escape04": "{{ a|force_escape|force_escape }}"}) def test_force_escape04(self): - output = self.engine.render_to_string('force-escape04', {"a": "x&y"}) + output = self.engine.render_to_string("force-escape04", {"a": "x&y"}) self.assertEqual(output, "x&amp;y") # Because the result of force_escape is "safe", an additional # escape filter has no effect. - @setup({'force-escape05': '{% autoescape off %}{{ a|force_escape|escape }}{% endautoescape %}'}) + @setup( + { + "force-escape05": "{% autoescape off %}{{ a|force_escape|escape }}{% endautoescape %}" + } + ) def test_force_escape05(self): - output = self.engine.render_to_string('force-escape05', {"a": "x&y"}) + output = self.engine.render_to_string("force-escape05", {"a": "x&y"}) self.assertEqual(output, "x&y") - @setup({'force-escape06': '{{ a|force_escape|escape }}'}) + @setup({"force-escape06": "{{ a|force_escape|escape }}"}) def test_force_escape06(self): - output = self.engine.render_to_string('force-escape06', {"a": "x&y"}) + output = self.engine.render_to_string("force-escape06", {"a": "x&y"}) self.assertEqual(output, "x&y") - @setup({'force-escape07': '{% autoescape off %}{{ a|escape|force_escape }}{% endautoescape %}'}) + @setup( + { + "force-escape07": "{% autoescape off %}{{ a|escape|force_escape }}{% endautoescape %}" + } + ) def test_force_escape07(self): - output = self.engine.render_to_string('force-escape07', {"a": "x&y"}) + output = self.engine.render_to_string("force-escape07", {"a": "x&y"}) self.assertEqual(output, "x&amp;y") - @setup({'force-escape08': '{{ a|escape|force_escape }}'}) + @setup({"force-escape08": "{{ a|escape|force_escape }}"}) def test_force_escape08(self): - output = self.engine.render_to_string('force-escape08', {"a": "x&y"}) + output = self.engine.render_to_string("force-escape08", {"a": "x&y"}) self.assertEqual(output, "x&amp;y") class FunctionTests(SimpleTestCase): - def test_escape(self): - escaped = force_escape('<some html & special characters > here') - self.assertEqual(escaped, '<some html & special characters > here') + escaped = force_escape("<some html & special characters > here") + self.assertEqual(escaped, "<some html & special characters > here") self.assertIsInstance(escaped, SafeData) def test_unicode(self): self.assertEqual( - force_escape('<some html & special characters > here ĐÅ€£'), - '<some html & special characters > here \u0110\xc5\u20ac\xa3', + force_escape("<some html & special characters > here ĐÅ€£"), + "<some html & special characters > here \u0110\xc5\u20ac\xa3", ) diff --git a/tests/template_tests/filter_tests/test_get_digit.py b/tests/template_tests/filter_tests/test_get_digit.py index 1382408715..4b10ca93ed 100644 --- a/tests/template_tests/filter_tests/test_get_digit.py +++ b/tests/template_tests/filter_tests/test_get_digit.py @@ -3,7 +3,6 @@ from django.test import SimpleTestCase class FunctionTests(SimpleTestCase): - def test_values(self): self.assertEqual(get_digit(123, 1), 3) self.assertEqual(get_digit(123, 2), 2) @@ -12,4 +11,4 @@ class FunctionTests(SimpleTestCase): self.assertEqual(get_digit(123, 0), 123) def test_string(self): - self.assertEqual(get_digit('xyz', 0), 'xyz') + self.assertEqual(get_digit("xyz", 0), "xyz") diff --git a/tests/template_tests/filter_tests/test_iriencode.py b/tests/template_tests/filter_tests/test_iriencode.py index 7d83b67f9d..31fce93949 100644 --- a/tests/template_tests/filter_tests/test_iriencode.py +++ b/tests/template_tests/filter_tests/test_iriencode.py @@ -10,31 +10,40 @@ class IriencodeTests(SimpleTestCase): Ensure iriencode keeps safe strings. """ - @setup({'iriencode01': '{{ url|iriencode }}'}) + @setup({"iriencode01": "{{ url|iriencode }}"}) def test_iriencode01(self): - output = self.engine.render_to_string('iriencode01', {'url': '?test=1&me=2'}) - self.assertEqual(output, '?test=1&me=2') + output = self.engine.render_to_string("iriencode01", {"url": "?test=1&me=2"}) + self.assertEqual(output, "?test=1&me=2") - @setup({'iriencode02': '{% autoescape off %}{{ url|iriencode }}{% endautoescape %}'}) + @setup( + {"iriencode02": "{% autoescape off %}{{ url|iriencode }}{% endautoescape %}"} + ) def test_iriencode02(self): - output = self.engine.render_to_string('iriencode02', {'url': '?test=1&me=2'}) - self.assertEqual(output, '?test=1&me=2') + output = self.engine.render_to_string("iriencode02", {"url": "?test=1&me=2"}) + self.assertEqual(output, "?test=1&me=2") - @setup({'iriencode03': '{{ url|iriencode }}'}) + @setup({"iriencode03": "{{ url|iriencode }}"}) def test_iriencode03(self): - output = self.engine.render_to_string('iriencode03', {'url': mark_safe('?test=1&me=2')}) - self.assertEqual(output, '?test=1&me=2') + output = self.engine.render_to_string( + "iriencode03", {"url": mark_safe("?test=1&me=2")} + ) + self.assertEqual(output, "?test=1&me=2") - @setup({'iriencode04': '{% autoescape off %}{{ url|iriencode }}{% endautoescape %}'}) + @setup( + {"iriencode04": "{% autoescape off %}{{ url|iriencode }}{% endautoescape %}"} + ) def test_iriencode04(self): - output = self.engine.render_to_string('iriencode04', {'url': mark_safe('?test=1&me=2')}) - self.assertEqual(output, '?test=1&me=2') + output = self.engine.render_to_string( + "iriencode04", {"url": mark_safe("?test=1&me=2")} + ) + self.assertEqual(output, "?test=1&me=2") class FunctionTests(SimpleTestCase): - def test_unicode(self): - self.assertEqual(iriencode('S\xf8r-Tr\xf8ndelag'), 'S%C3%B8r-Tr%C3%B8ndelag') + self.assertEqual(iriencode("S\xf8r-Tr\xf8ndelag"), "S%C3%B8r-Tr%C3%B8ndelag") def test_urlencoded(self): - self.assertEqual(iriencode(urlencode('fran\xe7ois & jill')), 'fran%C3%A7ois%20%26%20jill') + self.assertEqual( + iriencode(urlencode("fran\xe7ois & jill")), "fran%C3%A7ois%20%26%20jill" + ) diff --git a/tests/template_tests/filter_tests/test_join.py b/tests/template_tests/filter_tests/test_join.py index 43ac0da7c2..08f68537ee 100644 --- a/tests/template_tests/filter_tests/test_join.py +++ b/tests/template_tests/filter_tests/test_join.py @@ -6,70 +6,76 @@ from ..utils import setup class JoinTests(SimpleTestCase): - - @setup({'join01': '{{ a|join:", " }}'}) + @setup({"join01": '{{ a|join:", " }}'}) def test_join01(self): - output = self.engine.render_to_string('join01', {'a': ['alpha', 'beta & me']}) - self.assertEqual(output, 'alpha, beta & me') + output = self.engine.render_to_string("join01", {"a": ["alpha", "beta & me"]}) + self.assertEqual(output, "alpha, beta & me") - @setup({'join02': '{% autoescape off %}{{ a|join:", " }}{% endautoescape %}'}) + @setup({"join02": '{% autoescape off %}{{ a|join:", " }}{% endautoescape %}'}) def test_join02(self): - output = self.engine.render_to_string('join02', {'a': ['alpha', 'beta & me']}) - self.assertEqual(output, 'alpha, beta & me') + output = self.engine.render_to_string("join02", {"a": ["alpha", "beta & me"]}) + self.assertEqual(output, "alpha, beta & me") - @setup({'join03': '{{ a|join:" & " }}'}) + @setup({"join03": '{{ a|join:" & " }}'}) def test_join03(self): - output = self.engine.render_to_string('join03', {'a': ['alpha', 'beta & me']}) - self.assertEqual(output, 'alpha & beta & me') + output = self.engine.render_to_string("join03", {"a": ["alpha", "beta & me"]}) + self.assertEqual(output, "alpha & beta & me") - @setup({'join04': '{% autoescape off %}{{ a|join:" & " }}{% endautoescape %}'}) + @setup({"join04": '{% autoescape off %}{{ a|join:" & " }}{% endautoescape %}'}) def test_join04(self): - output = self.engine.render_to_string('join04', {'a': ['alpha', 'beta & me']}) - self.assertEqual(output, 'alpha & beta & me') + output = self.engine.render_to_string("join04", {"a": ["alpha", "beta & me"]}) + self.assertEqual(output, "alpha & beta & me") # Joining with unsafe joiners doesn't result in unsafe strings. - @setup({'join05': '{{ a|join:var }}'}) + @setup({"join05": "{{ a|join:var }}"}) def test_join05(self): - output = self.engine.render_to_string('join05', {'a': ['alpha', 'beta & me'], 'var': ' & '}) - self.assertEqual(output, 'alpha & beta & me') + output = self.engine.render_to_string( + "join05", {"a": ["alpha", "beta & me"], "var": " & "} + ) + self.assertEqual(output, "alpha & beta & me") - @setup({'join06': '{{ a|join:var }}'}) + @setup({"join06": "{{ a|join:var }}"}) def test_join06(self): - output = self.engine.render_to_string('join06', {'a': ['alpha', 'beta & me'], 'var': mark_safe(' & ')}) - self.assertEqual(output, 'alpha & beta & me') + output = self.engine.render_to_string( + "join06", {"a": ["alpha", "beta & me"], "var": mark_safe(" & ")} + ) + self.assertEqual(output, "alpha & beta & me") - @setup({'join07': '{{ a|join:var|lower }}'}) + @setup({"join07": "{{ a|join:var|lower }}"}) def test_join07(self): - output = self.engine.render_to_string('join07', {'a': ['Alpha', 'Beta & me'], 'var': ' & '}) - self.assertEqual(output, 'alpha & beta & me') + output = self.engine.render_to_string( + "join07", {"a": ["Alpha", "Beta & me"], "var": " & "} + ) + self.assertEqual(output, "alpha & beta & me") - @setup({'join08': '{{ a|join:var|lower }}'}) + @setup({"join08": "{{ a|join:var|lower }}"}) def test_join08(self): - output = self.engine.render_to_string('join08', {'a': ['Alpha', 'Beta & me'], 'var': mark_safe(' & ')}) - self.assertEqual(output, 'alpha & beta & me') + output = self.engine.render_to_string( + "join08", {"a": ["Alpha", "Beta & me"], "var": mark_safe(" & ")} + ) + self.assertEqual(output, "alpha & beta & me") class FunctionTests(SimpleTestCase): - def test_list(self): - self.assertEqual(join([0, 1, 2], 'glue'), '0glue1glue2') + self.assertEqual(join([0, 1, 2], "glue"), "0glue1glue2") def test_autoescape(self): self.assertEqual( - join(['<a>', '<img>', '</a>'], '<br>'), - '<a><br><img><br></a>', + join(["<a>", "<img>", "</a>"], "<br>"), + "<a><br><img><br></a>", ) def test_autoescape_off(self): self.assertEqual( - join(['<a>', '<img>', '</a>'], '<br>', autoescape=False), - '<a><br><img><br></a>', + join(["<a>", "<img>", "</a>"], "<br>", autoescape=False), + "<a><br><img><br></a>", ) def test_noniterable_arg(self): obj = object() - self.assertEqual(join(obj, '<br>'), obj) + self.assertEqual(join(obj, "<br>"), obj) def test_noniterable_arg_autoescape_off(self): obj = object() - self.assertEqual(join(obj, '<br>', autoescape=False), obj) + self.assertEqual(join(obj, "<br>", autoescape=False), obj) diff --git a/tests/template_tests/filter_tests/test_json_script.py b/tests/template_tests/filter_tests/test_json_script.py index 1d38f678e0..28a078effb 100644 --- a/tests/template_tests/filter_tests/test_json_script.py +++ b/tests/template_tests/filter_tests/test_json_script.py @@ -4,21 +4,19 @@ from ..utils import setup class JsonScriptTests(SimpleTestCase): - - @setup({'json-tag01': '{{ value|json_script:"test_id" }}'}) + @setup({"json-tag01": '{{ value|json_script:"test_id" }}'}) def test_basic(self): output = self.engine.render_to_string( - 'json-tag01', - {'value': {'a': 'testing\r\njson \'string" <b>escaping</b>'}} + "json-tag01", {"value": {"a": "testing\r\njson 'string\" <b>escaping</b>"}} ) self.assertEqual( output, '<script id="test_id" type="application/json">' '{"a": "testing\\r\\njson \'string\\" \\u003Cb\\u003Eescaping\\u003C/b\\u003E"}' - '</script>' + "</script>", ) - @setup({'json-tag02': '{{ value|json_script }}'}) + @setup({"json-tag02": "{{ value|json_script }}"}) def test_without_id(self): - output = self.engine.render_to_string('json-tag02', {'value': {}}) + output = self.engine.render_to_string("json-tag02", {"value": {}}) self.assertEqual(output, '<script type="application/json">{}</script>') diff --git a/tests/template_tests/filter_tests/test_last.py b/tests/template_tests/filter_tests/test_last.py index e03caa2382..6b8b8fcbbc 100644 --- a/tests/template_tests/filter_tests/test_last.py +++ b/tests/template_tests/filter_tests/test_last.py @@ -5,18 +5,23 @@ from ..utils import setup class LastTests(SimpleTestCase): - - @setup({'last01': '{{ a|last }} {{ b|last }}'}) + @setup({"last01": "{{ a|last }} {{ b|last }}"}) def test_last01(self): - output = self.engine.render_to_string('last01', {"a": ["x", "a&b"], "b": ["x", mark_safe("a&b")]}) + output = self.engine.render_to_string( + "last01", {"a": ["x", "a&b"], "b": ["x", mark_safe("a&b")]} + ) self.assertEqual(output, "a&b a&b") - @setup({'last02': '{% autoescape off %}{{ a|last }} {{ b|last }}{% endautoescape %}'}) + @setup( + {"last02": "{% autoescape off %}{{ a|last }} {{ b|last }}{% endautoescape %}"} + ) def test_last02(self): - output = self.engine.render_to_string('last02', {"a": ["x", "a&b"], "b": ["x", mark_safe("a&b")]}) + output = self.engine.render_to_string( + "last02", {"a": ["x", "a&b"], "b": ["x", mark_safe("a&b")]} + ) self.assertEqual(output, "a&b a&b") - @setup({'empty_list': '{% autoescape off %}{{ a|last }}{% endautoescape %}'}) + @setup({"empty_list": "{% autoescape off %}{{ a|last }}{% endautoescape %}"}) def test_empty_list(self): - output = self.engine.render_to_string('empty_list', {"a": []}) - self.assertEqual(output, '') + output = self.engine.render_to_string("empty_list", {"a": []}) + self.assertEqual(output, "") diff --git a/tests/template_tests/filter_tests/test_length.py b/tests/template_tests/filter_tests/test_length.py index 9ea90a1234..507cff124b 100644 --- a/tests/template_tests/filter_tests/test_length.py +++ b/tests/template_tests/filter_tests/test_length.py @@ -6,51 +6,53 @@ from ..utils import setup class LengthTests(SimpleTestCase): - - @setup({'length01': '{{ list|length }}'}) + @setup({"length01": "{{ list|length }}"}) def test_length01(self): - output = self.engine.render_to_string('length01', {'list': ['4', None, True, {}]}) - self.assertEqual(output, '4') + output = self.engine.render_to_string( + "length01", {"list": ["4", None, True, {}]} + ) + self.assertEqual(output, "4") - @setup({'length02': '{{ list|length }}'}) + @setup({"length02": "{{ list|length }}"}) def test_length02(self): - output = self.engine.render_to_string('length02', {'list': []}) - self.assertEqual(output, '0') + output = self.engine.render_to_string("length02", {"list": []}) + self.assertEqual(output, "0") - @setup({'length03': '{{ string|length }}'}) + @setup({"length03": "{{ string|length }}"}) def test_length03(self): - output = self.engine.render_to_string('length03', {'string': ''}) - self.assertEqual(output, '0') + output = self.engine.render_to_string("length03", {"string": ""}) + self.assertEqual(output, "0") - @setup({'length04': '{{ string|length }}'}) + @setup({"length04": "{{ string|length }}"}) def test_length04(self): - output = self.engine.render_to_string('length04', {'string': 'django'}) - self.assertEqual(output, '6') + output = self.engine.render_to_string("length04", {"string": "django"}) + self.assertEqual(output, "6") - @setup({'length05': '{% if string|length == 6 %}Pass{% endif %}'}) + @setup({"length05": "{% if string|length == 6 %}Pass{% endif %}"}) def test_length05(self): - output = self.engine.render_to_string('length05', {'string': mark_safe('django')}) - self.assertEqual(output, 'Pass') + output = self.engine.render_to_string( + "length05", {"string": mark_safe("django")} + ) + self.assertEqual(output, "Pass") # Invalid uses that should fail silently. - @setup({'length06': '{{ int|length }}'}) + @setup({"length06": "{{ int|length }}"}) def test_length06(self): - output = self.engine.render_to_string('length06', {'int': 7}) - self.assertEqual(output, '0') + output = self.engine.render_to_string("length06", {"int": 7}) + self.assertEqual(output, "0") - @setup({'length07': '{{ None|length }}'}) + @setup({"length07": "{{ None|length }}"}) def test_length07(self): - output = self.engine.render_to_string('length07', {'None': None}) - self.assertEqual(output, '0') + output = self.engine.render_to_string("length07", {"None": None}) + self.assertEqual(output, "0") class FunctionTests(SimpleTestCase): - def test_string(self): - self.assertEqual(length('1234'), 4) + self.assertEqual(length("1234"), 4) def test_safestring(self): - self.assertEqual(length(mark_safe('1234')), 4) + self.assertEqual(length(mark_safe("1234")), 4) def test_list(self): self.assertEqual(length([1, 2, 3, 4]), 4) diff --git a/tests/template_tests/filter_tests/test_length_is.py b/tests/template_tests/filter_tests/test_length_is.py index 471ef312e9..1cc760c8a2 100644 --- a/tests/template_tests/filter_tests/test_length_is.py +++ b/tests/template_tests/filter_tests/test_length_is.py @@ -5,71 +5,97 @@ from ..utils import setup class LengthIsTests(SimpleTestCase): - - @setup({'length_is01': '{% if some_list|length_is:"4" %}Four{% endif %}'}) + @setup({"length_is01": '{% if some_list|length_is:"4" %}Four{% endif %}'}) def test_length_is01(self): - output = self.engine.render_to_string('length_is01', {'some_list': ['4', None, True, {}]}) - self.assertEqual(output, 'Four') + output = self.engine.render_to_string( + "length_is01", {"some_list": ["4", None, True, {}]} + ) + self.assertEqual(output, "Four") - @setup({'length_is02': '{% if some_list|length_is:"4" %}Four{% else %}Not Four{% endif %}'}) + @setup( + { + "length_is02": '{% if some_list|length_is:"4" %}Four{% else %}Not Four{% endif %}' + } + ) def test_length_is02(self): - output = self.engine.render_to_string('length_is02', {'some_list': ['4', None, True, {}, 17]}) - self.assertEqual(output, 'Not Four') + output = self.engine.render_to_string( + "length_is02", {"some_list": ["4", None, True, {}, 17]} + ) + self.assertEqual(output, "Not Four") - @setup({'length_is03': '{% if mystring|length_is:"4" %}Four{% endif %}'}) + @setup({"length_is03": '{% if mystring|length_is:"4" %}Four{% endif %}'}) def test_length_is03(self): - output = self.engine.render_to_string('length_is03', {'mystring': 'word'}) - self.assertEqual(output, 'Four') + output = self.engine.render_to_string("length_is03", {"mystring": "word"}) + self.assertEqual(output, "Four") - @setup({'length_is04': '{% if mystring|length_is:"4" %}Four{% else %}Not Four{% endif %}'}) + @setup( + { + "length_is04": '{% if mystring|length_is:"4" %}Four{% else %}Not Four{% endif %}' + } + ) def test_length_is04(self): - output = self.engine.render_to_string('length_is04', {'mystring': 'Python'}) - self.assertEqual(output, 'Not Four') + output = self.engine.render_to_string("length_is04", {"mystring": "Python"}) + self.assertEqual(output, "Not Four") - @setup({'length_is05': '{% if mystring|length_is:"4" %}Four{% else %}Not Four{% endif %}'}) + @setup( + { + "length_is05": '{% if mystring|length_is:"4" %}Four{% else %}Not Four{% endif %}' + } + ) def test_length_is05(self): - output = self.engine.render_to_string('length_is05', {'mystring': ''}) - self.assertEqual(output, 'Not Four') + output = self.engine.render_to_string("length_is05", {"mystring": ""}) + self.assertEqual(output, "Not Four") - @setup({'length_is06': '{% with var|length as my_length %}{{ my_length }}{% endwith %}'}) + @setup( + { + "length_is06": "{% with var|length as my_length %}{{ my_length }}{% endwith %}" + } + ) def test_length_is06(self): - output = self.engine.render_to_string('length_is06', {'var': 'django'}) - self.assertEqual(output, '6') + output = self.engine.render_to_string("length_is06", {"var": "django"}) + self.assertEqual(output, "6") # Boolean return value from length_is should not be coerced to a string - @setup({'length_is07': '{% if "X"|length_is:0 %}Length is 0{% else %}Length not 0{% endif %}'}) + @setup( + { + "length_is07": '{% if "X"|length_is:0 %}Length is 0{% else %}Length not 0{% endif %}' + } + ) def test_length_is07(self): - output = self.engine.render_to_string('length_is07', {}) - self.assertEqual(output, 'Length not 0') + output = self.engine.render_to_string("length_is07", {}) + self.assertEqual(output, "Length not 0") - @setup({'length_is08': '{% if "X"|length_is:1 %}Length is 1{% else %}Length not 1{% endif %}'}) + @setup( + { + "length_is08": '{% if "X"|length_is:1 %}Length is 1{% else %}Length not 1{% endif %}' + } + ) def test_length_is08(self): - output = self.engine.render_to_string('length_is08', {}) - self.assertEqual(output, 'Length is 1') + output = self.engine.render_to_string("length_is08", {}) + self.assertEqual(output, "Length is 1") # Invalid uses that should fail silently. - @setup({'length_is09': '{{ var|length_is:"fish" }}'}) + @setup({"length_is09": '{{ var|length_is:"fish" }}'}) def test_length_is09(self): - output = self.engine.render_to_string('length_is09', {'var': 'django'}) - self.assertEqual(output, '') + output = self.engine.render_to_string("length_is09", {"var": "django"}) + self.assertEqual(output, "") - @setup({'length_is10': '{{ int|length_is:"1" }}'}) + @setup({"length_is10": '{{ int|length_is:"1" }}'}) def test_length_is10(self): - output = self.engine.render_to_string('length_is10', {'int': 7}) - self.assertEqual(output, '') + output = self.engine.render_to_string("length_is10", {"int": 7}) + self.assertEqual(output, "") - @setup({'length_is11': '{{ none|length_is:"1" }}'}) + @setup({"length_is11": '{{ none|length_is:"1" }}'}) def test_length_is11(self): - output = self.engine.render_to_string('length_is11', {'none': None}) - self.assertEqual(output, '') + output = self.engine.render_to_string("length_is11", {"none": None}) + self.assertEqual(output, "") class FunctionTests(SimpleTestCase): - def test_empty_list(self): self.assertIs(length_is([], 0), True) self.assertIs(length_is([], 1), False) def test_string(self): - self.assertIs(length_is('a', 1), True) - self.assertIs(length_is('a', 10), False) + self.assertIs(length_is("a", 1), True) + self.assertIs(length_is("a", 10), False) diff --git a/tests/template_tests/filter_tests/test_linebreaks.py b/tests/template_tests/filter_tests/test_linebreaks.py index 8fdb91f377..ce0f082466 100644 --- a/tests/template_tests/filter_tests/test_linebreaks.py +++ b/tests/template_tests/filter_tests/test_linebreaks.py @@ -12,49 +12,58 @@ class LinebreaksTests(SimpleTestCase): autoescape setting. """ - @setup({'linebreaks01': '{{ a|linebreaks }} {{ b|linebreaks }}'}) + @setup({"linebreaks01": "{{ a|linebreaks }} {{ b|linebreaks }}"}) def test_linebreaks01(self): - output = self.engine.render_to_string('linebreaks01', {"a": "x&\ny", "b": mark_safe("x&\ny")}) + output = self.engine.render_to_string( + "linebreaks01", {"a": "x&\ny", "b": mark_safe("x&\ny")} + ) self.assertEqual(output, "<p>x&<br>y</p> <p>x&<br>y</p>") - @setup({'linebreaks02': '{% autoescape off %}{{ a|linebreaks }} {{ b|linebreaks }}{% endautoescape %}'}) + @setup( + { + "linebreaks02": "{% autoescape off %}{{ a|linebreaks }} {{ b|linebreaks }}{% endautoescape %}" + } + ) def test_linebreaks02(self): - output = self.engine.render_to_string('linebreaks02', {"a": "x&\ny", "b": mark_safe("x&\ny")}) + output = self.engine.render_to_string( + "linebreaks02", {"a": "x&\ny", "b": mark_safe("x&\ny")} + ) self.assertEqual(output, "<p>x&<br>y</p> <p>x&<br>y</p>") class FunctionTests(SimpleTestCase): - def test_line(self): - self.assertEqual(linebreaks_filter('line 1'), '<p>line 1</p>') + self.assertEqual(linebreaks_filter("line 1"), "<p>line 1</p>") def test_newline(self): - self.assertEqual(linebreaks_filter('line 1\nline 2'), '<p>line 1<br>line 2</p>') + self.assertEqual(linebreaks_filter("line 1\nline 2"), "<p>line 1<br>line 2</p>") def test_carriage(self): - self.assertEqual(linebreaks_filter('line 1\rline 2'), '<p>line 1<br>line 2</p>') + self.assertEqual(linebreaks_filter("line 1\rline 2"), "<p>line 1<br>line 2</p>") def test_carriage_newline(self): - self.assertEqual(linebreaks_filter('line 1\r\nline 2'), '<p>line 1<br>line 2</p>') + self.assertEqual( + linebreaks_filter("line 1\r\nline 2"), "<p>line 1<br>line 2</p>" + ) def test_non_string_input(self): - self.assertEqual(linebreaks_filter(123), '<p>123</p>') + self.assertEqual(linebreaks_filter(123), "<p>123</p>") def test_autoescape(self): self.assertEqual( - linebreaks_filter('foo\n<a>bar</a>\nbuz'), - '<p>foo<br><a>bar</a><br>buz</p>', + linebreaks_filter("foo\n<a>bar</a>\nbuz"), + "<p>foo<br><a>bar</a><br>buz</p>", ) def test_autoescape_off(self): self.assertEqual( - linebreaks_filter('foo\n<a>bar</a>\nbuz', autoescape=False), - '<p>foo<br><a>bar</a><br>buz</p>', + linebreaks_filter("foo\n<a>bar</a>\nbuz", autoescape=False), + "<p>foo<br><a>bar</a><br>buz</p>", ) def test_lazy_string_input(self): - add_header = lazy(lambda string: 'Header\n\n' + string, str) + add_header = lazy(lambda string: "Header\n\n" + string, str) self.assertEqual( - linebreaks_filter(add_header('line 1\r\nline2')), - '<p>Header</p>\n\n<p>line 1<br>line2</p>' + linebreaks_filter(add_header("line 1\r\nline2")), + "<p>Header</p>\n\n<p>line 1<br>line2</p>", ) diff --git a/tests/template_tests/filter_tests/test_linebreaksbr.py b/tests/template_tests/filter_tests/test_linebreaksbr.py index f2583f0aaf..fa4cff209b 100644 --- a/tests/template_tests/filter_tests/test_linebreaksbr.py +++ b/tests/template_tests/filter_tests/test_linebreaksbr.py @@ -11,39 +11,46 @@ class LinebreaksbrTests(SimpleTestCase): autoescape setting. """ - @setup({'linebreaksbr01': '{{ a|linebreaksbr }} {{ b|linebreaksbr }}'}) + @setup({"linebreaksbr01": "{{ a|linebreaksbr }} {{ b|linebreaksbr }}"}) def test_linebreaksbr01(self): - output = self.engine.render_to_string('linebreaksbr01', {"a": "x&\ny", "b": mark_safe("x&\ny")}) + output = self.engine.render_to_string( + "linebreaksbr01", {"a": "x&\ny", "b": mark_safe("x&\ny")} + ) self.assertEqual(output, "x&<br>y x&<br>y") - @setup({'linebreaksbr02': '{% autoescape off %}{{ a|linebreaksbr }} {{ b|linebreaksbr }}{% endautoescape %}'}) + @setup( + { + "linebreaksbr02": "{% autoescape off %}{{ a|linebreaksbr }} {{ b|linebreaksbr }}{% endautoescape %}" + } + ) def test_linebreaksbr02(self): - output = self.engine.render_to_string('linebreaksbr02', {"a": "x&\ny", "b": mark_safe("x&\ny")}) + output = self.engine.render_to_string( + "linebreaksbr02", {"a": "x&\ny", "b": mark_safe("x&\ny")} + ) self.assertEqual(output, "x&<br>y x&<br>y") class FunctionTests(SimpleTestCase): - def test_newline(self): - self.assertEqual(linebreaksbr('line 1\nline 2'), 'line 1<br>line 2') + self.assertEqual(linebreaksbr("line 1\nline 2"), "line 1<br>line 2") def test_carriage(self): - self.assertEqual(linebreaksbr('line 1\rline 2'), 'line 1<br>line 2') + self.assertEqual(linebreaksbr("line 1\rline 2"), "line 1<br>line 2") def test_carriage_newline(self): - self.assertEqual(linebreaksbr('line 1\r\nline 2'), 'line 1<br>line 2') + self.assertEqual(linebreaksbr("line 1\r\nline 2"), "line 1<br>line 2") def test_non_string_input(self): - self.assertEqual(linebreaksbr(123), '123') + self.assertEqual(linebreaksbr(123), "123") def test_autoescape(self): self.assertEqual( - linebreaksbr('foo\n<a>bar</a>\nbuz'), - 'foo<br><a>bar</a><br>buz', + linebreaksbr("foo\n<a>bar</a>\nbuz"), + "foo<br><a>bar</a><br>buz", ) def test_autoescape_off(self): self.assertEqual( - linebreaksbr('foo\n<a>bar</a>\nbuz', autoescape=False), - 'foo<br><a>bar</a><br>buz', + linebreaksbr("foo\n<a>bar</a>\nbuz", autoescape=False), + "foo<br><a>bar</a><br>buz", ) diff --git a/tests/template_tests/filter_tests/test_linenumbers.py b/tests/template_tests/filter_tests/test_linenumbers.py index 2ded01f421..82fae4f889 100644 --- a/tests/template_tests/filter_tests/test_linenumbers.py +++ b/tests/template_tests/filter_tests/test_linenumbers.py @@ -11,45 +11,52 @@ class LinenumbersTests(SimpleTestCase): autoescape setting. """ - @setup({'linenumbers01': '{{ a|linenumbers }} {{ b|linenumbers }}'}) + @setup({"linenumbers01": "{{ a|linenumbers }} {{ b|linenumbers }}"}) def test_linenumbers01(self): output = self.engine.render_to_string( - 'linenumbers01', - {'a': 'one\n<two>\nthree', 'b': mark_safe('one\n<two>\nthree')}, + "linenumbers01", + {"a": "one\n<two>\nthree", "b": mark_safe("one\n<two>\nthree")}, + ) + self.assertEqual( + output, "1. one\n2. <two>\n3. three 1. one\n2. <two>\n3. three" ) - self.assertEqual(output, '1. one\n2. <two>\n3. three 1. one\n2. <two>\n3. three') - @setup({'linenumbers02': '{% autoescape off %}{{ a|linenumbers }} {{ b|linenumbers }}{% endautoescape %}'}) + @setup( + { + "linenumbers02": "{% autoescape off %}{{ a|linenumbers }} {{ b|linenumbers }}{% endautoescape %}" + } + ) def test_linenumbers02(self): output = self.engine.render_to_string( - 'linenumbers02', - {'a': 'one\n<two>\nthree', 'b': mark_safe('one\n<two>\nthree')}, + "linenumbers02", + {"a": "one\n<two>\nthree", "b": mark_safe("one\n<two>\nthree")}, + ) + self.assertEqual( + output, "1. one\n2. <two>\n3. three 1. one\n2. <two>\n3. three" ) - self.assertEqual(output, '1. one\n2. <two>\n3. three 1. one\n2. <two>\n3. three') class FunctionTests(SimpleTestCase): - def test_linenumbers(self): - self.assertEqual(linenumbers('line 1\nline 2'), '1. line 1\n2. line 2') + self.assertEqual(linenumbers("line 1\nline 2"), "1. line 1\n2. line 2") def test_linenumbers2(self): self.assertEqual( - linenumbers('\n'.join(['x'] * 10)), - '01. x\n02. x\n03. x\n04. x\n05. x\n06. x\n07. x\n08. x\n09. x\n10. x', + linenumbers("\n".join(["x"] * 10)), + "01. x\n02. x\n03. x\n04. x\n05. x\n06. x\n07. x\n08. x\n09. x\n10. x", ) def test_non_string_input(self): - self.assertEqual(linenumbers(123), '1. 123') + self.assertEqual(linenumbers(123), "1. 123") def test_autoescape(self): self.assertEqual( - linenumbers('foo\n<a>bar</a>\nbuz'), - '1. foo\n2. <a>bar</a>\n3. buz', + linenumbers("foo\n<a>bar</a>\nbuz"), + "1. foo\n2. <a>bar</a>\n3. buz", ) def test_autoescape_off(self): self.assertEqual( - linenumbers('foo\n<a>bar</a>\nbuz', autoescape=False), - '1. foo\n2. <a>bar</a>\n3. buz' + linenumbers("foo\n<a>bar</a>\nbuz", autoescape=False), + "1. foo\n2. <a>bar</a>\n3. buz", ) diff --git a/tests/template_tests/filter_tests/test_ljust.py b/tests/template_tests/filter_tests/test_ljust.py index 19f35f78f4..9ea5b23862 100644 --- a/tests/template_tests/filter_tests/test_ljust.py +++ b/tests/template_tests/filter_tests/test_ljust.py @@ -6,26 +6,32 @@ from ..utils import setup class LjustTests(SimpleTestCase): - - @setup({'ljust01': '{% autoescape off %}.{{ a|ljust:"5" }}. .{{ b|ljust:"5" }}.{% endautoescape %}'}) + @setup( + { + "ljust01": '{% autoescape off %}.{{ a|ljust:"5" }}. .{{ b|ljust:"5" }}.{% endautoescape %}' + } + ) def test_ljust01(self): - output = self.engine.render_to_string('ljust01', {"a": "a&b", "b": mark_safe("a&b")}) + output = self.engine.render_to_string( + "ljust01", {"a": "a&b", "b": mark_safe("a&b")} + ) self.assertEqual(output, ".a&b . .a&b .") - @setup({'ljust02': '.{{ a|ljust:"5" }}. .{{ b|ljust:"5" }}.'}) + @setup({"ljust02": '.{{ a|ljust:"5" }}. .{{ b|ljust:"5" }}.'}) def test_ljust02(self): - output = self.engine.render_to_string('ljust02', {"a": "a&b", "b": mark_safe("a&b")}) + output = self.engine.render_to_string( + "ljust02", {"a": "a&b", "b": mark_safe("a&b")} + ) self.assertEqual(output, ".a&b . .a&b .") class FunctionTests(SimpleTestCase): - def test_ljust(self): - self.assertEqual(ljust('test', 10), 'test ') - self.assertEqual(ljust('test', 3), 'test') + self.assertEqual(ljust("test", 10), "test ") + self.assertEqual(ljust("test", 3), "test") def test_less_than_string_length(self): - self.assertEqual(ljust('test', 3), 'test') + self.assertEqual(ljust("test", 3), "test") def test_non_string_input(self): - self.assertEqual(ljust(123, 4), '123 ') + self.assertEqual(ljust(123, 4), "123 ") diff --git a/tests/template_tests/filter_tests/test_lower.py b/tests/template_tests/filter_tests/test_lower.py index 1db934c5fa..29845663dd 100644 --- a/tests/template_tests/filter_tests/test_lower.py +++ b/tests/template_tests/filter_tests/test_lower.py @@ -6,26 +6,32 @@ from ..utils import setup class LowerTests(SimpleTestCase): - - @setup({'lower01': '{% autoescape off %}{{ a|lower }} {{ b|lower }}{% endautoescape %}'}) + @setup( + { + "lower01": "{% autoescape off %}{{ a|lower }} {{ b|lower }}{% endautoescape %}" + } + ) def test_lower01(self): - output = self.engine.render_to_string('lower01', {"a": "Apple & banana", "b": mark_safe("Apple & banana")}) + output = self.engine.render_to_string( + "lower01", {"a": "Apple & banana", "b": mark_safe("Apple & banana")} + ) self.assertEqual(output, "apple & banana apple & banana") - @setup({'lower02': '{{ a|lower }} {{ b|lower }}'}) + @setup({"lower02": "{{ a|lower }} {{ b|lower }}"}) def test_lower02(self): - output = self.engine.render_to_string('lower02', {"a": "Apple & banana", "b": mark_safe("Apple & banana")}) + output = self.engine.render_to_string( + "lower02", {"a": "Apple & banana", "b": mark_safe("Apple & banana")} + ) self.assertEqual(output, "apple & banana apple & banana") class FunctionTests(SimpleTestCase): - def test_lower(self): - self.assertEqual(lower('TEST'), 'test') + self.assertEqual(lower("TEST"), "test") def test_unicode(self): # uppercase E umlaut - self.assertEqual(lower('\xcb'), '\xeb') + self.assertEqual(lower("\xcb"), "\xeb") def test_non_string_input(self): - self.assertEqual(lower(123), '123') + self.assertEqual(lower(123), "123") diff --git a/tests/template_tests/filter_tests/test_make_list.py b/tests/template_tests/filter_tests/test_make_list.py index a3e8535ecb..34901d2ff2 100644 --- a/tests/template_tests/filter_tests/test_make_list.py +++ b/tests/template_tests/filter_tests/test_make_list.py @@ -11,31 +11,34 @@ class MakeListTests(SimpleTestCase): escaped. """ - @setup({'make_list01': '{% autoescape off %}{{ a|make_list }}{% endautoescape %}'}) + @setup({"make_list01": "{% autoescape off %}{{ a|make_list }}{% endautoescape %}"}) def test_make_list01(self): - output = self.engine.render_to_string('make_list01', {"a": mark_safe("&")}) + output = self.engine.render_to_string("make_list01", {"a": mark_safe("&")}) self.assertEqual(output, "['&']") - @setup({'make_list02': '{{ a|make_list }}'}) + @setup({"make_list02": "{{ a|make_list }}"}) def test_make_list02(self): - output = self.engine.render_to_string('make_list02', {"a": mark_safe("&")}) - self.assertEqual(output, '['&']') + output = self.engine.render_to_string("make_list02", {"a": mark_safe("&")}) + self.assertEqual(output, "['&']") - @setup({'make_list03': '{% autoescape off %}{{ a|make_list|stringformat:"s"|safe }}{% endautoescape %}'}) + @setup( + { + "make_list03": '{% autoescape off %}{{ a|make_list|stringformat:"s"|safe }}{% endautoescape %}' + } + ) def test_make_list03(self): - output = self.engine.render_to_string('make_list03', {"a": mark_safe("&")}) + output = self.engine.render_to_string("make_list03", {"a": mark_safe("&")}) self.assertEqual(output, "['&']") - @setup({'make_list04': '{{ a|make_list|stringformat:"s"|safe }}'}) + @setup({"make_list04": '{{ a|make_list|stringformat:"s"|safe }}'}) def test_make_list04(self): - output = self.engine.render_to_string('make_list04', {"a": mark_safe("&")}) + output = self.engine.render_to_string("make_list04", {"a": mark_safe("&")}) self.assertEqual(output, "['&']") class FunctionTests(SimpleTestCase): - def test_string(self): - self.assertEqual(make_list('abc'), ['a', 'b', 'c']) + self.assertEqual(make_list("abc"), ["a", "b", "c"]) def test_integer(self): - self.assertEqual(make_list(1234), ['1', '2', '3', '4']) + self.assertEqual(make_list(1234), ["1", "2", "3", "4"]) diff --git a/tests/template_tests/filter_tests/test_phone2numeric.py b/tests/template_tests/filter_tests/test_phone2numeric.py index 0c81a904ea..8165fba9da 100644 --- a/tests/template_tests/filter_tests/test_phone2numeric.py +++ b/tests/template_tests/filter_tests/test_phone2numeric.py @@ -6,36 +6,37 @@ from ..utils import setup class Phone2numericTests(SimpleTestCase): - - @setup({'phone2numeric01': '{{ a|phone2numeric }} {{ b|phone2numeric }}'}) + @setup({"phone2numeric01": "{{ a|phone2numeric }} {{ b|phone2numeric }}"}) def test_phone2numeric01(self): output = self.engine.render_to_string( - 'phone2numeric01', - {'a': '<1-800-call-me>', 'b': mark_safe('<1-800-call-me>')}, + "phone2numeric01", + {"a": "<1-800-call-me>", "b": mark_safe("<1-800-call-me>")}, ) - self.assertEqual(output, '<1-800-2255-63> <1-800-2255-63>') + self.assertEqual(output, "<1-800-2255-63> <1-800-2255-63>") - @setup({'phone2numeric02': '{% autoescape off %}{{ a|phone2numeric }} {{ b|phone2numeric }}{% endautoescape %}'}) + @setup( + { + "phone2numeric02": "{% autoescape off %}{{ a|phone2numeric }} {{ b|phone2numeric }}{% endautoescape %}" + } + ) def test_phone2numeric02(self): output = self.engine.render_to_string( - 'phone2numeric02', - {'a': '<1-800-call-me>', 'b': mark_safe('<1-800-call-me>')}, + "phone2numeric02", + {"a": "<1-800-call-me>", "b": mark_safe("<1-800-call-me>")}, ) - self.assertEqual(output, '<1-800-2255-63> <1-800-2255-63>') + self.assertEqual(output, "<1-800-2255-63> <1-800-2255-63>") - @setup({'phone2numeric03': '{{ a|phone2numeric }}'}) + @setup({"phone2numeric03": "{{ a|phone2numeric }}"}) def test_phone2numeric03(self): output = self.engine.render_to_string( - 'phone2numeric03', - {'a': 'How razorback-jumping frogs can level six piqued gymnasts!'}, + "phone2numeric03", + {"a": "How razorback-jumping frogs can level six piqued gymnasts!"}, ) self.assertEqual( - output, - '469 729672225-5867464 37647 226 53835 749 747833 49662787!' + output, "469 729672225-5867464 37647 226 53835 749 747833 49662787!" ) class FunctionTests(SimpleTestCase): - def test_phone2numeric(self): - self.assertEqual(phone2numeric_filter('0800 flowers'), '0800 3569377') + self.assertEqual(phone2numeric_filter("0800 flowers"), "0800 3569377") diff --git a/tests/template_tests/filter_tests/test_pluralize.py b/tests/template_tests/filter_tests/test_pluralize.py index 313981c6a8..c28718e101 100644 --- a/tests/template_tests/filter_tests/test_pluralize.py +++ b/tests/template_tests/filter_tests/test_pluralize.py @@ -7,60 +7,58 @@ from ..utils import setup class PluralizeTests(SimpleTestCase): - def check_values(self, *tests): for value, expected in tests: with self.subTest(value=value): - output = self.engine.render_to_string('t', {'value': value}) + output = self.engine.render_to_string("t", {"value": value}) self.assertEqual(output, expected) - @setup({'t': 'vote{{ value|pluralize }}'}) + @setup({"t": "vote{{ value|pluralize }}"}) def test_no_arguments(self): - self.check_values(('0', 'votes'), ('1', 'vote'), ('2', 'votes')) + self.check_values(("0", "votes"), ("1", "vote"), ("2", "votes")) - @setup({'t': 'class{{ value|pluralize:"es" }}'}) + @setup({"t": 'class{{ value|pluralize:"es" }}'}) def test_suffix(self): - self.check_values(('0', 'classes'), ('1', 'class'), ('2', 'classes')) + self.check_values(("0", "classes"), ("1", "class"), ("2", "classes")) - @setup({'t': 'cand{{ value|pluralize:"y,ies" }}'}) + @setup({"t": 'cand{{ value|pluralize:"y,ies" }}'}) def test_singular_and_plural_suffix(self): - self.check_values(('0', 'candies'), ('1', 'candy'), ('2', 'candies')) + self.check_values(("0", "candies"), ("1", "candy"), ("2", "candies")) class FunctionTests(SimpleTestCase): - def test_integers(self): - self.assertEqual(pluralize(1), '') - self.assertEqual(pluralize(0), 's') - self.assertEqual(pluralize(2), 's') + self.assertEqual(pluralize(1), "") + self.assertEqual(pluralize(0), "s") + self.assertEqual(pluralize(2), "s") def test_floats(self): - self.assertEqual(pluralize(0.5), 's') - self.assertEqual(pluralize(1.5), 's') + self.assertEqual(pluralize(0.5), "s") + self.assertEqual(pluralize(1.5), "s") def test_decimals(self): - self.assertEqual(pluralize(Decimal(1)), '') - self.assertEqual(pluralize(Decimal(0)), 's') - self.assertEqual(pluralize(Decimal(2)), 's') + self.assertEqual(pluralize(Decimal(1)), "") + self.assertEqual(pluralize(Decimal(0)), "s") + self.assertEqual(pluralize(Decimal(2)), "s") def test_lists(self): - self.assertEqual(pluralize([1]), '') - self.assertEqual(pluralize([]), 's') - self.assertEqual(pluralize([1, 2, 3]), 's') + self.assertEqual(pluralize([1]), "") + self.assertEqual(pluralize([]), "s") + self.assertEqual(pluralize([1, 2, 3]), "s") def test_suffixes(self): - self.assertEqual(pluralize(1, 'es'), '') - self.assertEqual(pluralize(0, 'es'), 'es') - self.assertEqual(pluralize(2, 'es'), 'es') - self.assertEqual(pluralize(1, 'y,ies'), 'y') - self.assertEqual(pluralize(0, 'y,ies'), 'ies') - self.assertEqual(pluralize(2, 'y,ies'), 'ies') - self.assertEqual(pluralize(0, 'y,ies,error'), '') + self.assertEqual(pluralize(1, "es"), "") + self.assertEqual(pluralize(0, "es"), "es") + self.assertEqual(pluralize(2, "es"), "es") + self.assertEqual(pluralize(1, "y,ies"), "y") + self.assertEqual(pluralize(0, "y,ies"), "ies") + self.assertEqual(pluralize(2, "y,ies"), "ies") + self.assertEqual(pluralize(0, "y,ies,error"), "") def test_no_len_type(self): - self.assertEqual(pluralize(object(), 'y,es'), '') - self.assertEqual(pluralize(object(), 'es'), '') + self.assertEqual(pluralize(object(), "y,es"), "") + self.assertEqual(pluralize(object(), "es"), "") def test_value_error(self): - self.assertEqual(pluralize('', 'y,es'), '') - self.assertEqual(pluralize('', 'es'), '') + self.assertEqual(pluralize("", "y,es"), "") + self.assertEqual(pluralize("", "es"), "") diff --git a/tests/template_tests/filter_tests/test_random.py b/tests/template_tests/filter_tests/test_random.py index acb8a82f1d..a419128971 100644 --- a/tests/template_tests/filter_tests/test_random.py +++ b/tests/template_tests/filter_tests/test_random.py @@ -5,17 +5,20 @@ from ..utils import setup class RandomTests(SimpleTestCase): - - @setup({'random01': '{{ a|random }} {{ b|random }}'}) + @setup({"random01": "{{ a|random }} {{ b|random }}"}) def test_random01(self): output = self.engine.render_to_string( - 'random01', {'a': ['a&b', 'a&b'], 'b': [mark_safe('a&b'), mark_safe('a&b')]} + "random01", {"a": ["a&b", "a&b"], "b": [mark_safe("a&b"), mark_safe("a&b")]} ) - self.assertEqual(output, 'a&b a&b') + self.assertEqual(output, "a&b a&b") - @setup({'random02': '{% autoescape off %}{{ a|random }} {{ b|random }}{% endautoescape %}'}) + @setup( + { + "random02": "{% autoescape off %}{{ a|random }} {{ b|random }}{% endautoescape %}" + } + ) def test_random02(self): output = self.engine.render_to_string( - 'random02', {'a': ['a&b', 'a&b'], 'b': [mark_safe('a&b'), mark_safe('a&b')]} + "random02", {"a": ["a&b", "a&b"], "b": [mark_safe("a&b"), mark_safe("a&b")]} ) - self.assertEqual(output, 'a&b a&b') + self.assertEqual(output, "a&b a&b") diff --git a/tests/template_tests/filter_tests/test_rjust.py b/tests/template_tests/filter_tests/test_rjust.py index 1926b49e38..b7dde7514a 100644 --- a/tests/template_tests/filter_tests/test_rjust.py +++ b/tests/template_tests/filter_tests/test_rjust.py @@ -6,25 +6,31 @@ from ..utils import setup class RjustTests(SimpleTestCase): - - @setup({'rjust01': '{% autoescape off %}.{{ a|rjust:"5" }}. .{{ b|rjust:"5" }}.{% endautoescape %}'}) + @setup( + { + "rjust01": '{% autoescape off %}.{{ a|rjust:"5" }}. .{{ b|rjust:"5" }}.{% endautoescape %}' + } + ) def test_rjust01(self): - output = self.engine.render_to_string('rjust01', {"a": "a&b", "b": mark_safe("a&b")}) + output = self.engine.render_to_string( + "rjust01", {"a": "a&b", "b": mark_safe("a&b")} + ) self.assertEqual(output, ". a&b. . a&b.") - @setup({'rjust02': '.{{ a|rjust:"5" }}. .{{ b|rjust:"5" }}.'}) + @setup({"rjust02": '.{{ a|rjust:"5" }}. .{{ b|rjust:"5" }}.'}) def test_rjust02(self): - output = self.engine.render_to_string('rjust02', {"a": "a&b", "b": mark_safe("a&b")}) + output = self.engine.render_to_string( + "rjust02", {"a": "a&b", "b": mark_safe("a&b")} + ) self.assertEqual(output, ". a&b. . a&b.") class FunctionTests(SimpleTestCase): - def test_rjust(self): - self.assertEqual(rjust('test', 10), ' test') + self.assertEqual(rjust("test", 10), " test") def test_less_than_string_length(self): - self.assertEqual(rjust('test', 3), 'test') + self.assertEqual(rjust("test", 3), "test") def test_non_string_input(self): - self.assertEqual(rjust(123, 4), ' 123') + self.assertEqual(rjust(123, 4), " 123") diff --git a/tests/template_tests/filter_tests/test_safe.py b/tests/template_tests/filter_tests/test_safe.py index c05387098d..ecde1c820c 100644 --- a/tests/template_tests/filter_tests/test_safe.py +++ b/tests/template_tests/filter_tests/test_safe.py @@ -4,13 +4,12 @@ from ..utils import setup class SafeTests(SimpleTestCase): - - @setup({'safe01': '{{ a }} -- {{ a|safe }}'}) + @setup({"safe01": "{{ a }} -- {{ a|safe }}"}) def test_safe01(self): - output = self.engine.render_to_string('safe01', {'a': '<b>hello</b>'}) - self.assertEqual(output, '<b>hello</b> -- <b>hello</b>') + output = self.engine.render_to_string("safe01", {"a": "<b>hello</b>"}) + self.assertEqual(output, "<b>hello</b> -- <b>hello</b>") - @setup({'safe02': '{% autoescape off %}{{ a }} -- {{ a|safe }}{% endautoescape %}'}) + @setup({"safe02": "{% autoescape off %}{{ a }} -- {{ a|safe }}{% endautoescape %}"}) def test_safe02(self): - output = self.engine.render_to_string('safe02', {'a': '<b>hello</b>'}) - self.assertEqual(output, '<b>hello</b> -- <b>hello</b>') + output = self.engine.render_to_string("safe02", {"a": "<b>hello</b>"}) + self.assertEqual(output, "<b>hello</b> -- <b>hello</b>") diff --git a/tests/template_tests/filter_tests/test_safeseq.py b/tests/template_tests/filter_tests/test_safeseq.py index 38b1cd6078..4a537551f9 100644 --- a/tests/template_tests/filter_tests/test_safeseq.py +++ b/tests/template_tests/filter_tests/test_safeseq.py @@ -4,13 +4,16 @@ from ..utils import setup class SafeseqTests(SimpleTestCase): - - @setup({'safeseq01': '{{ a|join:", " }} -- {{ a|safeseq|join:", " }}'}) + @setup({"safeseq01": '{{ a|join:", " }} -- {{ a|safeseq|join:", " }}'}) def test_safeseq01(self): - output = self.engine.render_to_string('safeseq01', {'a': ['&', '<']}) - self.assertEqual(output, '&, < -- &, <') + output = self.engine.render_to_string("safeseq01", {"a": ["&", "<"]}) + self.assertEqual(output, "&, < -- &, <") - @setup({'safeseq02': '{% autoescape off %}{{ a|join:", " }} -- {{ a|safeseq|join:", " }}{% endautoescape %}'}) + @setup( + { + "safeseq02": '{% autoescape off %}{{ a|join:", " }} -- {{ a|safeseq|join:", " }}{% endautoescape %}' + } + ) def test_safeseq02(self): - output = self.engine.render_to_string('safeseq02', {'a': ['&', '<']}) - self.assertEqual(output, '&, < -- &, <') + output = self.engine.render_to_string("safeseq02", {"a": ["&", "<"]}) + self.assertEqual(output, "&, < -- &, <") diff --git a/tests/template_tests/filter_tests/test_slice.py b/tests/template_tests/filter_tests/test_slice.py index 1b92776707..f1c91a5008 100644 --- a/tests/template_tests/filter_tests/test_slice.py +++ b/tests/template_tests/filter_tests/test_slice.py @@ -6,41 +6,47 @@ from ..utils import setup class SliceTests(SimpleTestCase): - - @setup({'slice01': '{{ a|slice:"1:3" }} {{ b|slice:"1:3" }}'}) + @setup({"slice01": '{{ a|slice:"1:3" }} {{ b|slice:"1:3" }}'}) def test_slice01(self): - output = self.engine.render_to_string('slice01', {'a': 'a&b', 'b': mark_safe('a&b')}) - self.assertEqual(output, '&b &b') + output = self.engine.render_to_string( + "slice01", {"a": "a&b", "b": mark_safe("a&b")} + ) + self.assertEqual(output, "&b &b") - @setup({'slice02': '{% autoescape off %}{{ a|slice:"1:3" }} {{ b|slice:"1:3" }}{% endautoescape %}'}) + @setup( + { + "slice02": '{% autoescape off %}{{ a|slice:"1:3" }} {{ b|slice:"1:3" }}{% endautoescape %}' + } + ) def test_slice02(self): - output = self.engine.render_to_string('slice02', {'a': 'a&b', 'b': mark_safe('a&b')}) - self.assertEqual(output, '&b &b') + output = self.engine.render_to_string( + "slice02", {"a": "a&b", "b": mark_safe("a&b")} + ) + self.assertEqual(output, "&b &b") class FunctionTests(SimpleTestCase): - def test_zero_length(self): - self.assertEqual(slice_filter('abcdefg', '0'), '') + self.assertEqual(slice_filter("abcdefg", "0"), "") def test_index(self): - self.assertEqual(slice_filter('abcdefg', '1'), 'a') + self.assertEqual(slice_filter("abcdefg", "1"), "a") def test_index_integer(self): - self.assertEqual(slice_filter('abcdefg', 1), 'a') + self.assertEqual(slice_filter("abcdefg", 1), "a") def test_negative_index(self): - self.assertEqual(slice_filter('abcdefg', '-1'), 'abcdef') + self.assertEqual(slice_filter("abcdefg", "-1"), "abcdef") def test_range(self): - self.assertEqual(slice_filter('abcdefg', '1:2'), 'b') + self.assertEqual(slice_filter("abcdefg", "1:2"), "b") def test_range_multiple(self): - self.assertEqual(slice_filter('abcdefg', '1:3'), 'bc') + self.assertEqual(slice_filter("abcdefg", "1:3"), "bc") def test_range_step(self): - self.assertEqual(slice_filter('abcdefg', '0::2'), 'aceg') + self.assertEqual(slice_filter("abcdefg", "0::2"), "aceg") def test_fail_silently(self): obj = object() - self.assertEqual(slice_filter(obj, '0::2'), obj) + self.assertEqual(slice_filter(obj, "0::2"), obj) diff --git a/tests/template_tests/filter_tests/test_slugify.py b/tests/template_tests/filter_tests/test_slugify.py index b1d617f5bc..e0e8a52da9 100644 --- a/tests/template_tests/filter_tests/test_slugify.py +++ b/tests/template_tests/filter_tests/test_slugify.py @@ -12,37 +12,50 @@ class SlugifyTests(SimpleTestCase): but the result is still safe. """ - @setup({'slugify01': '{% autoescape off %}{{ a|slugify }} {{ b|slugify }}{% endautoescape %}'}) + @setup( + { + "slugify01": "{% autoescape off %}{{ a|slugify }} {{ b|slugify }}{% endautoescape %}" + } + ) def test_slugify01(self): - output = self.engine.render_to_string('slugify01', {'a': 'a & b', 'b': mark_safe('a & b')}) - self.assertEqual(output, 'a-b a-amp-b') + output = self.engine.render_to_string( + "slugify01", {"a": "a & b", "b": mark_safe("a & b")} + ) + self.assertEqual(output, "a-b a-amp-b") - @setup({'slugify02': '{{ a|slugify }} {{ b|slugify }}'}) + @setup({"slugify02": "{{ a|slugify }} {{ b|slugify }}"}) def test_slugify02(self): - output = self.engine.render_to_string('slugify02', {'a': 'a & b', 'b': mark_safe('a & b')}) - self.assertEqual(output, 'a-b a-amp-b') + output = self.engine.render_to_string( + "slugify02", {"a": "a & b", "b": mark_safe("a & b")} + ) + self.assertEqual(output, "a-b a-amp-b") class FunctionTests(SimpleTestCase): - def test_slugify(self): self.assertEqual( - slugify(' Jack & Jill like numbers 1,2,3 and 4 and silly characters ?%.$!/'), - 'jack-jill-like-numbers-123-and-4-and-silly-characters', + slugify( + " Jack & Jill like numbers 1,2,3 and 4 and silly characters ?%.$!/" + ), + "jack-jill-like-numbers-123-and-4-and-silly-characters", ) def test_unicode(self): self.assertEqual( slugify("Un \xe9l\xe9phant \xe0 l'or\xe9e du bois"), - 'un-elephant-a-loree-du-bois', + "un-elephant-a-loree-du-bois", ) def test_non_string_input(self): - self.assertEqual(slugify(123), '123') + self.assertEqual(slugify(123), "123") def test_slugify_lazy_string(self): lazy_str = lazy(lambda string: string, str) self.assertEqual( - slugify(lazy_str(' Jack & Jill like numbers 1,2,3 and 4 and silly characters ?%.$!/')), - 'jack-jill-like-numbers-123-and-4-and-silly-characters', + slugify( + lazy_str( + " Jack & Jill like numbers 1,2,3 and 4 and silly characters ?%.$!/" + ) + ), + "jack-jill-like-numbers-123-and-4-and-silly-characters", ) diff --git a/tests/template_tests/filter_tests/test_stringformat.py b/tests/template_tests/filter_tests/test_stringformat.py index 62ee19aef8..e8f06ac4a0 100644 --- a/tests/template_tests/filter_tests/test_stringformat.py +++ b/tests/template_tests/filter_tests/test_stringformat.py @@ -11,32 +11,38 @@ class StringformatTests(SimpleTestCase): formatting here only needs to deal with pre-escaped characters. """ - @setup({ - 'stringformat01': - '{% autoescape off %}.{{ a|stringformat:"5s" }}. .{{ b|stringformat:"5s" }}.{% endautoescape %}' - }) + @setup( + { + "stringformat01": '{% autoescape off %}.{{ a|stringformat:"5s" }}. .{{ b|stringformat:"5s" }}.{% endautoescape %}' + } + ) def test_stringformat01(self): - output = self.engine.render_to_string('stringformat01', {'a': 'a<b', 'b': mark_safe('a<b')}) - self.assertEqual(output, '. a<b. . a<b.') + output = self.engine.render_to_string( + "stringformat01", {"a": "a<b", "b": mark_safe("a<b")} + ) + self.assertEqual(output, ". a<b. . a<b.") - @setup({'stringformat02': '.{{ a|stringformat:"5s" }}. .{{ b|stringformat:"5s" }}.'}) + @setup( + {"stringformat02": '.{{ a|stringformat:"5s" }}. .{{ b|stringformat:"5s" }}.'} + ) def test_stringformat02(self): - output = self.engine.render_to_string('stringformat02', {'a': 'a<b', 'b': mark_safe('a<b')}) - self.assertEqual(output, '. a<b. . a<b.') + output = self.engine.render_to_string( + "stringformat02", {"a": "a<b", "b": mark_safe("a<b")} + ) + self.assertEqual(output, ". a<b. . a<b.") class FunctionTests(SimpleTestCase): - def test_format(self): - self.assertEqual(stringformat(1, '03d'), '001') - self.assertEqual(stringformat([1, None], 's'), '[1, None]') - self.assertEqual(stringformat((1, 2, 3), 's'), '(1, 2, 3)') - self.assertEqual(stringformat((1,), 's'), '(1,)') - self.assertEqual(stringformat({1, 2}, 's'), '{1, 2}') - self.assertEqual(stringformat({1: 2, 2: 3}, 's'), '{1: 2, 2: 3}') + self.assertEqual(stringformat(1, "03d"), "001") + self.assertEqual(stringformat([1, None], "s"), "[1, None]") + self.assertEqual(stringformat((1, 2, 3), "s"), "(1, 2, 3)") + self.assertEqual(stringformat((1,), "s"), "(1,)") + self.assertEqual(stringformat({1, 2}, "s"), "{1, 2}") + self.assertEqual(stringformat({1: 2, 2: 3}, "s"), "{1: 2, 2: 3}") def test_invalid(self): - self.assertEqual(stringformat(1, 'z'), '') - self.assertEqual(stringformat(object(), 'd'), '') - self.assertEqual(stringformat(None, 'd'), '') - self.assertEqual(stringformat((1, 2, 3), 'd'), '') + self.assertEqual(stringformat(1, "z"), "") + self.assertEqual(stringformat(object(), "d"), "") + self.assertEqual(stringformat(None, "d"), "") + self.assertEqual(stringformat((1, 2, 3), "d"), "") diff --git a/tests/template_tests/filter_tests/test_striptags.py b/tests/template_tests/filter_tests/test_striptags.py index 8b946d1f83..7b142f5379 100644 --- a/tests/template_tests/filter_tests/test_striptags.py +++ b/tests/template_tests/filter_tests/test_striptags.py @@ -7,43 +7,51 @@ from ..utils import setup class StriptagsTests(SimpleTestCase): - - @setup({'striptags01': '{{ a|striptags }} {{ b|striptags }}'}) + @setup({"striptags01": "{{ a|striptags }} {{ b|striptags }}"}) def test_striptags01(self): output = self.engine.render_to_string( - 'striptags01', + "striptags01", { - 'a': '<a>x</a> <p><b>y</b></p>', - 'b': mark_safe('<a>x</a> <p><b>y</b></p>'), + "a": "<a>x</a> <p><b>y</b></p>", + "b": mark_safe("<a>x</a> <p><b>y</b></p>"), }, ) - self.assertEqual(output, 'x y x y') + self.assertEqual(output, "x y x y") - @setup({'striptags02': '{% autoescape off %}{{ a|striptags }} {{ b|striptags }}{% endautoescape %}'}) + @setup( + { + "striptags02": "{% autoescape off %}{{ a|striptags }} {{ b|striptags }}{% endautoescape %}" + } + ) def test_striptags02(self): output = self.engine.render_to_string( - 'striptags02', + "striptags02", { - 'a': '<a>x</a> <p><b>y</b></p>', - 'b': mark_safe('<a>x</a> <p><b>y</b></p>'), + "a": "<a>x</a> <p><b>y</b></p>", + "b": mark_safe("<a>x</a> <p><b>y</b></p>"), }, ) - self.assertEqual(output, 'x y x y') + self.assertEqual(output, "x y x y") class FunctionTests(SimpleTestCase): - def test_strip(self): self.assertEqual( - striptags('some <b>html</b> with <script>alert("You smell")</script> disallowed <img /> tags'), + striptags( + 'some <b>html</b> with <script>alert("You smell")</script> disallowed <img /> tags' + ), 'some html with alert("You smell") disallowed tags', ) def test_non_string_input(self): - self.assertEqual(striptags(123), '123') + self.assertEqual(striptags(123), "123") def test_strip_lazy_string(self): self.assertEqual( - striptags(lazystr('some <b>html</b> with <script>alert("Hello")</script> disallowed <img /> tags')), + striptags( + lazystr( + 'some <b>html</b> with <script>alert("Hello")</script> disallowed <img /> tags' + ) + ), 'some html with alert("Hello") disallowed tags', ) diff --git a/tests/template_tests/filter_tests/test_time.py b/tests/template_tests/filter_tests/test_time.py index a848e74378..c8ab58b553 100644 --- a/tests/template_tests/filter_tests/test_time.py +++ b/tests/template_tests/filter_tests/test_time.py @@ -13,54 +13,55 @@ class TimeTests(TimezoneTestCase): #20693: Timezone support for the time template filter """ - @setup({'time00': '{{ dt|time }}'}) + @setup({"time00": "{{ dt|time }}"}) def test_time00(self): - output = self.engine.render_to_string('time00', {'dt': time(16, 25)}) - self.assertEqual(output, '4:25 p.m.') + output = self.engine.render_to_string("time00", {"dt": time(16, 25)}) + self.assertEqual(output, "4:25 p.m.") - @setup({'time00_l10n': '{{ dt|time }}'}) + @setup({"time00_l10n": "{{ dt|time }}"}) def test_time00_l10n(self): - with translation.override('fr'): - output = self.engine.render_to_string('time00_l10n', {'dt': time(16, 25)}) - self.assertEqual(output, '16:25') + with translation.override("fr"): + output = self.engine.render_to_string("time00_l10n", {"dt": time(16, 25)}) + self.assertEqual(output, "16:25") - @setup({'time01': '{{ dt|time:"e:O:T:Z" }}'}) + @setup({"time01": '{{ dt|time:"e:O:T:Z" }}'}) def test_time01(self): - output = self.engine.render_to_string('time01', {'dt': self.now_tz_i}) - self.assertEqual(output, '+0315:+0315:+0315:11700') + output = self.engine.render_to_string("time01", {"dt": self.now_tz_i}) + self.assertEqual(output, "+0315:+0315:+0315:11700") - @setup({'time02': '{{ dt|time:"e:T" }}'}) + @setup({"time02": '{{ dt|time:"e:T" }}'}) def test_time02(self): - output = self.engine.render_to_string('time02', {'dt': self.now}) - self.assertEqual(output, ':' + self.now_tz.tzinfo.tzname(self.now_tz)) + output = self.engine.render_to_string("time02", {"dt": self.now}) + self.assertEqual(output, ":" + self.now_tz.tzinfo.tzname(self.now_tz)) - @setup({'time03': '{{ t|time:"P:e:O:T:Z" }}'}) + @setup({"time03": '{{ t|time:"P:e:O:T:Z" }}'}) def test_time03(self): - output = self.engine.render_to_string('time03', {'t': time(4, 0, tzinfo=timezone.get_fixed_timezone(30))}) - self.assertEqual(output, '4 a.m.::::') + output = self.engine.render_to_string( + "time03", {"t": time(4, 0, tzinfo=timezone.get_fixed_timezone(30))} + ) + self.assertEqual(output, "4 a.m.::::") - @setup({'time04': '{{ t|time:"P:e:O:T:Z" }}'}) + @setup({"time04": '{{ t|time:"P:e:O:T:Z" }}'}) def test_time04(self): - output = self.engine.render_to_string('time04', {'t': time(4, 0)}) - self.assertEqual(output, '4 a.m.::::') + output = self.engine.render_to_string("time04", {"t": time(4, 0)}) + self.assertEqual(output, "4 a.m.::::") - @setup({'time05': '{{ d|time:"P:e:O:T:Z" }}'}) + @setup({"time05": '{{ d|time:"P:e:O:T:Z" }}'}) def test_time05(self): - output = self.engine.render_to_string('time05', {'d': self.today}) - self.assertEqual(output, '') + output = self.engine.render_to_string("time05", {"d": self.today}) + self.assertEqual(output, "") - @setup({'time06': '{{ obj|time:"P:e:O:T:Z" }}'}) + @setup({"time06": '{{ obj|time:"P:e:O:T:Z" }}'}) def test_time06(self): - output = self.engine.render_to_string('time06', {'obj': 'non-datetime-value'}) - self.assertEqual(output, '') + output = self.engine.render_to_string("time06", {"obj": "non-datetime-value"}) + self.assertEqual(output, "") class FunctionTests(SimpleTestCase): - def test_no_args(self): - self.assertEqual(time_filter(''), '') - self.assertEqual(time_filter(None), '') + self.assertEqual(time_filter(""), "") + self.assertEqual(time_filter(None), "") def test_inputs(self): - self.assertEqual(time_filter(time(13), 'h'), '01') - self.assertEqual(time_filter(time(0), 'h'), '12') + self.assertEqual(time_filter(time(13), "h"), "01") + self.assertEqual(time_filter(time(0), "h"), "12") diff --git a/tests/template_tests/filter_tests/test_timesince.py b/tests/template_tests/filter_tests/test_timesince.py index 7fe4831d61..10e4e51d89 100644 --- a/tests/template_tests/filter_tests/test_timesince.py +++ b/tests/template_tests/filter_tests/test_timesince.py @@ -14,125 +14,148 @@ class TimesinceTests(TimezoneTestCase): """ # Default compare with datetime.now() - @setup({'timesince01': '{{ a|timesince }}'}) + @setup({"timesince01": "{{ a|timesince }}"}) def test_timesince01(self): output = self.engine.render_to_string( - 'timesince01', {'a': datetime.now() + timedelta(minutes=-1, seconds=-10)} + "timesince01", {"a": datetime.now() + timedelta(minutes=-1, seconds=-10)} ) - self.assertEqual(output, '1\xa0minute') + self.assertEqual(output, "1\xa0minute") - @setup({'timesince02': '{{ a|timesince }}'}) + @setup({"timesince02": "{{ a|timesince }}"}) def test_timesince02(self): output = self.engine.render_to_string( - 'timesince02', {'a': datetime.now() - timedelta(days=1, minutes=1)} + "timesince02", {"a": datetime.now() - timedelta(days=1, minutes=1)} ) - self.assertEqual(output, '1\xa0day') + self.assertEqual(output, "1\xa0day") - @setup({'timesince03': '{{ a|timesince }}'}) + @setup({"timesince03": "{{ a|timesince }}"}) def test_timesince03(self): output = self.engine.render_to_string( - 'timesince03', {'a': datetime.now() - timedelta(hours=1, minutes=25, seconds=10)} + "timesince03", + {"a": datetime.now() - timedelta(hours=1, minutes=25, seconds=10)}, ) - self.assertEqual(output, '1\xa0hour, 25\xa0minutes') + self.assertEqual(output, "1\xa0hour, 25\xa0minutes") # Compare to a given parameter - @setup({'timesince04': '{{ a|timesince:b }}'}) + @setup({"timesince04": "{{ a|timesince:b }}"}) def test_timesince04(self): output = self.engine.render_to_string( - 'timesince04', - {'a': self.now - timedelta(days=2), 'b': self.now - timedelta(days=1)}, + "timesince04", + {"a": self.now - timedelta(days=2), "b": self.now - timedelta(days=1)}, ) - self.assertEqual(output, '1\xa0day') + self.assertEqual(output, "1\xa0day") - @setup({'timesince05': '{{ a|timesince:b }}'}) + @setup({"timesince05": "{{ a|timesince:b }}"}) def test_timesince05(self): output = self.engine.render_to_string( - 'timesince05', - {'a': self.now - timedelta(days=2, minutes=1), 'b': self.now - timedelta(days=2)}, + "timesince05", + { + "a": self.now - timedelta(days=2, minutes=1), + "b": self.now - timedelta(days=2), + }, ) - self.assertEqual(output, '1\xa0minute') + self.assertEqual(output, "1\xa0minute") # Timezone is respected - @setup({'timesince06': '{{ a|timesince:b }}'}) + @setup({"timesince06": "{{ a|timesince:b }}"}) def test_timesince06(self): - output = self.engine.render_to_string('timesince06', {'a': self.now_tz - timedelta(hours=8), 'b': self.now_tz}) - self.assertEqual(output, '8\xa0hours') + output = self.engine.render_to_string( + "timesince06", {"a": self.now_tz - timedelta(hours=8), "b": self.now_tz} + ) + self.assertEqual(output, "8\xa0hours") # Tests for #7443 - @setup({'timesince07': '{{ earlier|timesince }}'}) + @setup({"timesince07": "{{ earlier|timesince }}"}) def test_timesince07(self): - output = self.engine.render_to_string('timesince07', {'earlier': self.now - timedelta(days=7)}) - self.assertEqual(output, '1\xa0week') + output = self.engine.render_to_string( + "timesince07", {"earlier": self.now - timedelta(days=7)} + ) + self.assertEqual(output, "1\xa0week") - @setup({'timesince08': '{{ earlier|timesince:now }}'}) + @setup({"timesince08": "{{ earlier|timesince:now }}"}) def test_timesince08(self): output = self.engine.render_to_string( - 'timesince08', {'now': self.now, 'earlier': self.now - timedelta(days=7)} + "timesince08", {"now": self.now, "earlier": self.now - timedelta(days=7)} ) - self.assertEqual(output, '1\xa0week') + self.assertEqual(output, "1\xa0week") - @setup({'timesince09': '{{ later|timesince }}'}) + @setup({"timesince09": "{{ later|timesince }}"}) def test_timesince09(self): - output = self.engine.render_to_string('timesince09', {'later': self.now + timedelta(days=7)}) - self.assertEqual(output, '0\xa0minutes') + output = self.engine.render_to_string( + "timesince09", {"later": self.now + timedelta(days=7)} + ) + self.assertEqual(output, "0\xa0minutes") - @setup({'timesince10': '{{ later|timesince:now }}'}) + @setup({"timesince10": "{{ later|timesince:now }}"}) def test_timesince10(self): - output = self.engine.render_to_string('timesince10', {'now': self.now, 'later': self.now + timedelta(days=7)}) - self.assertEqual(output, '0\xa0minutes') + output = self.engine.render_to_string( + "timesince10", {"now": self.now, "later": self.now + timedelta(days=7)} + ) + self.assertEqual(output, "0\xa0minutes") # Differing timezones are calculated correctly. - @setup({'timesince11': '{{ a|timesince }}'}) + @setup({"timesince11": "{{ a|timesince }}"}) def test_timesince11(self): - output = self.engine.render_to_string('timesince11', {'a': self.now}) - self.assertEqual(output, '0\xa0minutes') + output = self.engine.render_to_string("timesince11", {"a": self.now}) + self.assertEqual(output, "0\xa0minutes") @requires_tz_support - @setup({'timesince12': '{{ a|timesince }}'}) + @setup({"timesince12": "{{ a|timesince }}"}) def test_timesince12(self): - output = self.engine.render_to_string('timesince12', {'a': self.now_tz}) - self.assertEqual(output, '0\xa0minutes') + output = self.engine.render_to_string("timesince12", {"a": self.now_tz}) + self.assertEqual(output, "0\xa0minutes") @requires_tz_support - @setup({'timesince13': '{{ a|timesince }}'}) + @setup({"timesince13": "{{ a|timesince }}"}) def test_timesince13(self): - output = self.engine.render_to_string('timesince13', {'a': self.now_tz_i}) - self.assertEqual(output, '0\xa0minutes') + output = self.engine.render_to_string("timesince13", {"a": self.now_tz_i}) + self.assertEqual(output, "0\xa0minutes") - @setup({'timesince14': '{{ a|timesince:b }}'}) + @setup({"timesince14": "{{ a|timesince:b }}"}) def test_timesince14(self): - output = self.engine.render_to_string('timesince14', {'a': self.now_tz, 'b': self.now_tz_i}) - self.assertEqual(output, '0\xa0minutes') + output = self.engine.render_to_string( + "timesince14", {"a": self.now_tz, "b": self.now_tz_i} + ) + self.assertEqual(output, "0\xa0minutes") - @setup({'timesince15': '{{ a|timesince:b }}'}) + @setup({"timesince15": "{{ a|timesince:b }}"}) def test_timesince15(self): - output = self.engine.render_to_string('timesince15', {'a': self.now, 'b': self.now_tz_i}) - self.assertEqual(output, '') + output = self.engine.render_to_string( + "timesince15", {"a": self.now, "b": self.now_tz_i} + ) + self.assertEqual(output, "") - @setup({'timesince16': '{{ a|timesince:b }}'}) + @setup({"timesince16": "{{ a|timesince:b }}"}) def test_timesince16(self): - output = self.engine.render_to_string('timesince16', {'a': self.now_tz_i, 'b': self.now}) - self.assertEqual(output, '') + output = self.engine.render_to_string( + "timesince16", {"a": self.now_tz_i, "b": self.now} + ) + self.assertEqual(output, "") # Tests for #9065 (two date objects). - @setup({'timesince17': '{{ a|timesince:b }}'}) + @setup({"timesince17": "{{ a|timesince:b }}"}) def test_timesince17(self): - output = self.engine.render_to_string('timesince17', {'a': self.today, 'b': self.today}) - self.assertEqual(output, '0\xa0minutes') + output = self.engine.render_to_string( + "timesince17", {"a": self.today, "b": self.today} + ) + self.assertEqual(output, "0\xa0minutes") - @setup({'timesince18': '{{ a|timesince:b }}'}) + @setup({"timesince18": "{{ a|timesince:b }}"}) def test_timesince18(self): - output = self.engine.render_to_string('timesince18', {'a': self.today, 'b': self.today + timedelta(hours=24)}) - self.assertEqual(output, '1\xa0day') + output = self.engine.render_to_string( + "timesince18", {"a": self.today, "b": self.today + timedelta(hours=24)} + ) + self.assertEqual(output, "1\xa0day") class FunctionTests(SimpleTestCase): - def test_since_now(self): - self.assertEqual(timesince_filter(datetime.now() - timedelta(1)), '1\xa0day') + self.assertEqual(timesince_filter(datetime.now() - timedelta(1)), "1\xa0day") def test_no_args(self): - self.assertEqual(timesince_filter(None), '') + self.assertEqual(timesince_filter(None), "") def test_explicit_date(self): - self.assertEqual(timesince_filter(datetime(2005, 12, 29), datetime(2005, 12, 30)), '1\xa0day') + self.assertEqual( + timesince_filter(datetime(2005, 12, 29), datetime(2005, 12, 30)), "1\xa0day" + ) diff --git a/tests/template_tests/filter_tests/test_timeuntil.py b/tests/template_tests/filter_tests/test_timeuntil.py index f3a211c626..1df5a24d15 100644 --- a/tests/template_tests/filter_tests/test_timeuntil.py +++ b/tests/template_tests/filter_tests/test_timeuntil.py @@ -11,110 +11,135 @@ from .timezone_utils import TimezoneTestCase class TimeuntilTests(TimezoneTestCase): # Default compare with datetime.now() - @setup({'timeuntil01': '{{ a|timeuntil }}'}) + @setup({"timeuntil01": "{{ a|timeuntil }}"}) def test_timeuntil01(self): - output = self.engine.render_to_string('timeuntil01', {'a': datetime.now() + timedelta(minutes=2, seconds=10)}) - self.assertEqual(output, '2\xa0minutes') + output = self.engine.render_to_string( + "timeuntil01", {"a": datetime.now() + timedelta(minutes=2, seconds=10)} + ) + self.assertEqual(output, "2\xa0minutes") - @setup({'timeuntil02': '{{ a|timeuntil }}'}) + @setup({"timeuntil02": "{{ a|timeuntil }}"}) def test_timeuntil02(self): - output = self.engine.render_to_string('timeuntil02', {'a': (datetime.now() + timedelta(days=1, seconds=10))}) - self.assertEqual(output, '1\xa0day') + output = self.engine.render_to_string( + "timeuntil02", {"a": (datetime.now() + timedelta(days=1, seconds=10))} + ) + self.assertEqual(output, "1\xa0day") - @setup({'timeuntil03': '{{ a|timeuntil }}'}) + @setup({"timeuntil03": "{{ a|timeuntil }}"}) def test_timeuntil03(self): output = self.engine.render_to_string( - 'timeuntil03', {'a': (datetime.now() + timedelta(hours=8, minutes=10, seconds=10))} + "timeuntil03", + {"a": (datetime.now() + timedelta(hours=8, minutes=10, seconds=10))}, ) - self.assertEqual(output, '8\xa0hours, 10\xa0minutes') + self.assertEqual(output, "8\xa0hours, 10\xa0minutes") # Compare to a given parameter - @setup({'timeuntil04': '{{ a|timeuntil:b }}'}) + @setup({"timeuntil04": "{{ a|timeuntil:b }}"}) def test_timeuntil04(self): output = self.engine.render_to_string( - 'timeuntil04', - {'a': self.now - timedelta(days=1), 'b': self.now - timedelta(days=2)}, + "timeuntil04", + {"a": self.now - timedelta(days=1), "b": self.now - timedelta(days=2)}, ) - self.assertEqual(output, '1\xa0day') + self.assertEqual(output, "1\xa0day") - @setup({'timeuntil05': '{{ a|timeuntil:b }}'}) + @setup({"timeuntil05": "{{ a|timeuntil:b }}"}) def test_timeuntil05(self): output = self.engine.render_to_string( - 'timeuntil05', - {'a': self.now - timedelta(days=2), 'b': self.now - timedelta(days=2, minutes=1)}, + "timeuntil05", + { + "a": self.now - timedelta(days=2), + "b": self.now - timedelta(days=2, minutes=1), + }, ) - self.assertEqual(output, '1\xa0minute') + self.assertEqual(output, "1\xa0minute") # Regression for #7443 - @setup({'timeuntil06': '{{ earlier|timeuntil }}'}) + @setup({"timeuntil06": "{{ earlier|timeuntil }}"}) def test_timeuntil06(self): - output = self.engine.render_to_string('timeuntil06', {'earlier': self.now - timedelta(days=7)}) - self.assertEqual(output, '0\xa0minutes') + output = self.engine.render_to_string( + "timeuntil06", {"earlier": self.now - timedelta(days=7)} + ) + self.assertEqual(output, "0\xa0minutes") - @setup({'timeuntil07': '{{ earlier|timeuntil:now }}'}) + @setup({"timeuntil07": "{{ earlier|timeuntil:now }}"}) def test_timeuntil07(self): output = self.engine.render_to_string( - 'timeuntil07', {'now': self.now, 'earlier': self.now - timedelta(days=7)} + "timeuntil07", {"now": self.now, "earlier": self.now - timedelta(days=7)} ) - self.assertEqual(output, '0\xa0minutes') + self.assertEqual(output, "0\xa0minutes") - @setup({'timeuntil08': '{{ later|timeuntil }}'}) + @setup({"timeuntil08": "{{ later|timeuntil }}"}) def test_timeuntil08(self): - output = self.engine.render_to_string('timeuntil08', {'later': self.now + timedelta(days=7, hours=1)}) - self.assertEqual(output, '1\xa0week') + output = self.engine.render_to_string( + "timeuntil08", {"later": self.now + timedelta(days=7, hours=1)} + ) + self.assertEqual(output, "1\xa0week") - @setup({'timeuntil09': '{{ later|timeuntil:now }}'}) + @setup({"timeuntil09": "{{ later|timeuntil:now }}"}) def test_timeuntil09(self): - output = self.engine.render_to_string('timeuntil09', {'now': self.now, 'later': self.now + timedelta(days=7)}) - self.assertEqual(output, '1\xa0week') + output = self.engine.render_to_string( + "timeuntil09", {"now": self.now, "later": self.now + timedelta(days=7)} + ) + self.assertEqual(output, "1\xa0week") # Differing timezones are calculated correctly. @requires_tz_support - @setup({'timeuntil10': '{{ a|timeuntil }}'}) + @setup({"timeuntil10": "{{ a|timeuntil }}"}) def test_timeuntil10(self): - output = self.engine.render_to_string('timeuntil10', {'a': self.now_tz}) - self.assertEqual(output, '0\xa0minutes') + output = self.engine.render_to_string("timeuntil10", {"a": self.now_tz}) + self.assertEqual(output, "0\xa0minutes") @requires_tz_support - @setup({'timeuntil11': '{{ a|timeuntil }}'}) + @setup({"timeuntil11": "{{ a|timeuntil }}"}) def test_timeuntil11(self): - output = self.engine.render_to_string('timeuntil11', {'a': self.now_tz_i}) - self.assertEqual(output, '0\xa0minutes') + output = self.engine.render_to_string("timeuntil11", {"a": self.now_tz_i}) + self.assertEqual(output, "0\xa0minutes") - @setup({'timeuntil12': '{{ a|timeuntil:b }}'}) + @setup({"timeuntil12": "{{ a|timeuntil:b }}"}) def test_timeuntil12(self): - output = self.engine.render_to_string('timeuntil12', {'a': self.now_tz_i, 'b': self.now_tz}) - self.assertEqual(output, '0\xa0minutes') + output = self.engine.render_to_string( + "timeuntil12", {"a": self.now_tz_i, "b": self.now_tz} + ) + self.assertEqual(output, "0\xa0minutes") # Regression for #9065 (two date objects). - @setup({'timeuntil13': '{{ a|timeuntil:b }}'}) + @setup({"timeuntil13": "{{ a|timeuntil:b }}"}) def test_timeuntil13(self): - output = self.engine.render_to_string('timeuntil13', {'a': self.today, 'b': self.today}) - self.assertEqual(output, '0\xa0minutes') + output = self.engine.render_to_string( + "timeuntil13", {"a": self.today, "b": self.today} + ) + self.assertEqual(output, "0\xa0minutes") - @setup({'timeuntil14': '{{ a|timeuntil:b }}'}) + @setup({"timeuntil14": "{{ a|timeuntil:b }}"}) def test_timeuntil14(self): - output = self.engine.render_to_string('timeuntil14', {'a': self.today, 'b': self.today - timedelta(hours=24)}) - self.assertEqual(output, '1\xa0day') + output = self.engine.render_to_string( + "timeuntil14", {"a": self.today, "b": self.today - timedelta(hours=24)} + ) + self.assertEqual(output, "1\xa0day") - @setup({'timeuntil15': '{{ a|timeuntil:b }}'}) + @setup({"timeuntil15": "{{ a|timeuntil:b }}"}) def test_naive_aware_type_error(self): - output = self.engine.render_to_string('timeuntil15', {'a': self.now, 'b': self.now_tz_i}) - self.assertEqual(output, '') + output = self.engine.render_to_string( + "timeuntil15", {"a": self.now, "b": self.now_tz_i} + ) + self.assertEqual(output, "") - @setup({'timeuntil16': '{{ a|timeuntil:b }}'}) + @setup({"timeuntil16": "{{ a|timeuntil:b }}"}) def test_aware_naive_type_error(self): - output = self.engine.render_to_string('timeuntil16', {'a': self.now_tz_i, 'b': self.now}) - self.assertEqual(output, '') + output = self.engine.render_to_string( + "timeuntil16", {"a": self.now_tz_i, "b": self.now} + ) + self.assertEqual(output, "") class FunctionTests(SimpleTestCase): - def test_until_now(self): - self.assertEqual(timeuntil_filter(datetime.now() + timedelta(1, 1)), '1\xa0day') + self.assertEqual(timeuntil_filter(datetime.now() + timedelta(1, 1)), "1\xa0day") def test_no_args(self): - self.assertEqual(timeuntil_filter(None), '') + self.assertEqual(timeuntil_filter(None), "") def test_explicit_date(self): - self.assertEqual(timeuntil_filter(datetime(2005, 12, 30), datetime(2005, 12, 29)), '1\xa0day') + self.assertEqual( + timeuntil_filter(datetime(2005, 12, 30), datetime(2005, 12, 29)), "1\xa0day" + ) diff --git a/tests/template_tests/filter_tests/test_title.py b/tests/template_tests/filter_tests/test_title.py index 2eaf4a0219..ad2c7c9b28 100644 --- a/tests/template_tests/filter_tests/test_title.py +++ b/tests/template_tests/filter_tests/test_title.py @@ -5,25 +5,23 @@ from ..utils import setup class TitleTests(SimpleTestCase): - - @setup({'title1': '{{ a|title }}'}) + @setup({"title1": "{{ a|title }}"}) def test_title1(self): - output = self.engine.render_to_string('title1', {'a': 'JOE\'S CRAB SHACK'}) - self.assertEqual(output, 'Joe's Crab Shack') + output = self.engine.render_to_string("title1", {"a": "JOE'S CRAB SHACK"}) + self.assertEqual(output, "Joe's Crab Shack") - @setup({'title2': '{{ a|title }}'}) + @setup({"title2": "{{ a|title }}"}) def test_title2(self): - output = self.engine.render_to_string('title2', {'a': '555 WEST 53RD STREET'}) - self.assertEqual(output, '555 West 53rd Street') + output = self.engine.render_to_string("title2", {"a": "555 WEST 53RD STREET"}) + self.assertEqual(output, "555 West 53rd Street") class FunctionTests(SimpleTestCase): - def test_title(self): - self.assertEqual(title('a nice title, isn\'t it?'), "A Nice Title, Isn't It?") + self.assertEqual(title("a nice title, isn't it?"), "A Nice Title, Isn't It?") def test_unicode(self): - self.assertEqual(title('discoth\xe8que'), 'Discoth\xe8que') + self.assertEqual(title("discoth\xe8que"), "Discoth\xe8que") def test_non_string_input(self): - self.assertEqual(title(123), '123') + self.assertEqual(title(123), "123") diff --git a/tests/template_tests/filter_tests/test_truncatechars.py b/tests/template_tests/filter_tests/test_truncatechars.py index 89d48fd1cf..a444125cf8 100644 --- a/tests/template_tests/filter_tests/test_truncatechars.py +++ b/tests/template_tests/filter_tests/test_truncatechars.py @@ -4,18 +4,21 @@ from ..utils import setup class TruncatecharsTests(SimpleTestCase): - - @setup({'truncatechars01': '{{ a|truncatechars:3 }}'}) + @setup({"truncatechars01": "{{ a|truncatechars:3 }}"}) def test_truncatechars01(self): - output = self.engine.render_to_string('truncatechars01', {'a': 'Testing, testing'}) - self.assertEqual(output, 'Te…') + output = self.engine.render_to_string( + "truncatechars01", {"a": "Testing, testing"} + ) + self.assertEqual(output, "Te…") - @setup({'truncatechars02': '{{ a|truncatechars:7 }}'}) + @setup({"truncatechars02": "{{ a|truncatechars:7 }}"}) def test_truncatechars02(self): - output = self.engine.render_to_string('truncatechars02', {'a': 'Testing'}) - self.assertEqual(output, 'Testing') + output = self.engine.render_to_string("truncatechars02", {"a": "Testing"}) + self.assertEqual(output, "Testing") - @setup({'truncatechars03': "{{ a|truncatechars:'e' }}"}) + @setup({"truncatechars03": "{{ a|truncatechars:'e' }}"}) def test_fail_silently_incorrect_arg(self): - output = self.engine.render_to_string('truncatechars03', {'a': 'Testing, testing'}) - self.assertEqual(output, 'Testing, testing') + output = self.engine.render_to_string( + "truncatechars03", {"a": "Testing, testing"} + ) + self.assertEqual(output, "Testing, testing") diff --git a/tests/template_tests/filter_tests/test_truncatechars_html.py b/tests/template_tests/filter_tests/test_truncatechars_html.py index 4948e6534e..6c5fc3c883 100644 --- a/tests/template_tests/filter_tests/test_truncatechars_html.py +++ b/tests/template_tests/filter_tests/test_truncatechars_html.py @@ -3,34 +3,46 @@ from django.test import SimpleTestCase class FunctionTests(SimpleTestCase): - def test_truncate_zero(self): - self.assertEqual(truncatechars_html('<p>one <a href="#">two - three <br>four</a> five</p>', 0), '…') + self.assertEqual( + truncatechars_html( + '<p>one <a href="#">two - three <br>four</a> five</p>', 0 + ), + "…", + ) def test_truncate(self): self.assertEqual( - truncatechars_html('<p>one <a href="#">two - three <br>four</a> five</p>', 4), - '<p>one…</p>', + truncatechars_html( + '<p>one <a href="#">two - three <br>four</a> five</p>', 4 + ), + "<p>one…</p>", ) def test_truncate2(self): self.assertEqual( - truncatechars_html('<p>one <a href="#">two - three <br>four</a> five</p>', 9), + truncatechars_html( + '<p>one <a href="#">two - three <br>four</a> five</p>', 9 + ), '<p>one <a href="#">two …</a></p>', ) def test_truncate3(self): self.assertEqual( - truncatechars_html('<p>one <a href="#">two - three <br>four</a> five</p>', 100), + truncatechars_html( + '<p>one <a href="#">two - three <br>four</a> five</p>', 100 + ), '<p>one <a href="#">two - three <br>four</a> five</p>', ) def test_truncate_unicode(self): - self.assertEqual(truncatechars_html('<b>\xc5ngstr\xf6m</b> was here', 3), '<b>\xc5n…</b>') + self.assertEqual( + truncatechars_html("<b>\xc5ngstr\xf6m</b> was here", 3), "<b>\xc5n…</b>" + ) def test_truncate_something(self): - self.assertEqual(truncatechars_html('a<b>b</b>c', 3), 'a<b>b</b>c') + self.assertEqual(truncatechars_html("a<b>b</b>c", 3), "a<b>b</b>c") def test_invalid_arg(self): html = '<p>one <a href="#">two - three <br>four</a> five</p>' - self.assertEqual(truncatechars_html(html, 'a'), html) + self.assertEqual(truncatechars_html(html, "a"), html) diff --git a/tests/template_tests/filter_tests/test_truncatewords.py b/tests/template_tests/filter_tests/test_truncatewords.py index 636cd55fd5..b3457205ac 100644 --- a/tests/template_tests/filter_tests/test_truncatewords.py +++ b/tests/template_tests/filter_tests/test_truncatewords.py @@ -6,46 +6,48 @@ from ..utils import setup class TruncatewordsTests(SimpleTestCase): - - @setup({ - 'truncatewords01': '{% autoescape off %}{{ a|truncatewords:"2" }} {{ b|truncatewords:"2"}}{% endautoescape %}' - }) + @setup( + { + "truncatewords01": '{% autoescape off %}{{ a|truncatewords:"2" }} {{ b|truncatewords:"2"}}{% endautoescape %}' + } + ) def test_truncatewords01(self): output = self.engine.render_to_string( - 'truncatewords01', {'a': 'alpha & bravo', 'b': mark_safe('alpha & bravo')} + "truncatewords01", + {"a": "alpha & bravo", "b": mark_safe("alpha & bravo")}, ) - self.assertEqual(output, 'alpha & … alpha & …') + self.assertEqual(output, "alpha & … alpha & …") - @setup({'truncatewords02': '{{ a|truncatewords:"2" }} {{ b|truncatewords:"2"}}'}) + @setup({"truncatewords02": '{{ a|truncatewords:"2" }} {{ b|truncatewords:"2"}}'}) def test_truncatewords02(self): output = self.engine.render_to_string( - 'truncatewords02', {'a': 'alpha & bravo', 'b': mark_safe('alpha & bravo')} + "truncatewords02", + {"a": "alpha & bravo", "b": mark_safe("alpha & bravo")}, ) - self.assertEqual(output, 'alpha & … alpha & …') + self.assertEqual(output, "alpha & … alpha & …") class FunctionTests(SimpleTestCase): - def test_truncate(self): - self.assertEqual(truncatewords('A sentence with a few words in it', 1), 'A …') + self.assertEqual(truncatewords("A sentence with a few words in it", 1), "A …") def test_truncate2(self): self.assertEqual( - truncatewords('A sentence with a few words in it', 5), - 'A sentence with a few …', + truncatewords("A sentence with a few words in it", 5), + "A sentence with a few …", ) def test_overtruncate(self): self.assertEqual( - truncatewords('A sentence with a few words in it', 100), - 'A sentence with a few words in it', + truncatewords("A sentence with a few words in it", 100), + "A sentence with a few words in it", ) def test_invalid_number(self): self.assertEqual( - truncatewords('A sentence with a few words in it', 'not a number'), - 'A sentence with a few words in it', + truncatewords("A sentence with a few words in it", "not a number"), + "A sentence with a few words in it", ) def test_non_string_input(self): - self.assertEqual(truncatewords(123, 2), '123') + self.assertEqual(truncatewords(123, 2), "123") diff --git a/tests/template_tests/filter_tests/test_truncatewords_html.py b/tests/template_tests/filter_tests/test_truncatewords_html.py index 6177fc875d..32b7c81a76 100644 --- a/tests/template_tests/filter_tests/test_truncatewords_html.py +++ b/tests/template_tests/filter_tests/test_truncatewords_html.py @@ -3,42 +3,58 @@ from django.test import SimpleTestCase class FunctionTests(SimpleTestCase): - def test_truncate_zero(self): - self.assertEqual(truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 0), '') + self.assertEqual( + truncatewords_html( + '<p>one <a href="#">two - three <br>four</a> five</p>', 0 + ), + "", + ) def test_truncate(self): self.assertEqual( - truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 2), + truncatewords_html( + '<p>one <a href="#">two - three <br>four</a> five</p>', 2 + ), '<p>one <a href="#">two …</a></p>', ) def test_truncate2(self): self.assertEqual( - truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 4), + truncatewords_html( + '<p>one <a href="#">two - three <br>four</a> five</p>', 4 + ), '<p>one <a href="#">two - three …</a></p>', ) def test_truncate3(self): self.assertEqual( - truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 5), + truncatewords_html( + '<p>one <a href="#">two - three <br>four</a> five</p>', 5 + ), '<p>one <a href="#">two - three <br>four …</a></p>', ) def test_truncate4(self): self.assertEqual( - truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 100), + truncatewords_html( + '<p>one <a href="#">two - three <br>four</a> five</p>', 100 + ), '<p>one <a href="#">two - three <br>four</a> five</p>', ) def test_truncate_unicode(self): - self.assertEqual(truncatewords_html('\xc5ngstr\xf6m was here', 1), '\xc5ngstr\xf6m …') + self.assertEqual( + truncatewords_html("\xc5ngstr\xf6m was here", 1), "\xc5ngstr\xf6m …" + ) def test_truncate_complex(self): self.assertEqual( - truncatewords_html('<i>Buenos días! ¿Cómo está?</i>', 3), - '<i>Buenos días! ¿Cómo …</i>', + truncatewords_html( + "<i>Buenos días! ¿Cómo está?</i>", 3 + ), + "<i>Buenos días! ¿Cómo …</i>", ) def test_invalid_arg(self): - self.assertEqual(truncatewords_html('<p>string</p>', 'a'), '<p>string</p>') + self.assertEqual(truncatewords_html("<p>string</p>", "a"), "<p>string</p>") diff --git a/tests/template_tests/filter_tests/test_unordered_list.py b/tests/template_tests/filter_tests/test_unordered_list.py index 6a04664d99..1f08ea790d 100644 --- a/tests/template_tests/filter_tests/test_unordered_list.py +++ b/tests/template_tests/filter_tests/test_unordered_list.py @@ -7,90 +7,110 @@ from ..utils import setup class UnorderedListTests(SimpleTestCase): - - @setup({'unordered_list01': '{{ a|unordered_list }}'}) + @setup({"unordered_list01": "{{ a|unordered_list }}"}) def test_unordered_list01(self): - output = self.engine.render_to_string('unordered_list01', {'a': ['x>', ['<y']]}) - self.assertEqual(output, '\t<li>x>\n\t<ul>\n\t\t<li><y</li>\n\t</ul>\n\t</li>') + output = self.engine.render_to_string("unordered_list01", {"a": ["x>", ["<y"]]}) + self.assertEqual( + output, "\t<li>x>\n\t<ul>\n\t\t<li><y</li>\n\t</ul>\n\t</li>" + ) - @setup({'unordered_list02': '{% autoescape off %}{{ a|unordered_list }}{% endautoescape %}'}) + @setup( + { + "unordered_list02": "{% autoescape off %}{{ a|unordered_list }}{% endautoescape %}" + } + ) def test_unordered_list02(self): - output = self.engine.render_to_string('unordered_list02', {'a': ['x>', ['<y']]}) - self.assertEqual(output, '\t<li>x>\n\t<ul>\n\t\t<li><y</li>\n\t</ul>\n\t</li>') + output = self.engine.render_to_string("unordered_list02", {"a": ["x>", ["<y"]]}) + self.assertEqual(output, "\t<li>x>\n\t<ul>\n\t\t<li><y</li>\n\t</ul>\n\t</li>") - @setup({'unordered_list03': '{{ a|unordered_list }}'}) + @setup({"unordered_list03": "{{ a|unordered_list }}"}) def test_unordered_list03(self): - output = self.engine.render_to_string('unordered_list03', {'a': ['x>', [mark_safe('<y')]]}) - self.assertEqual(output, '\t<li>x>\n\t<ul>\n\t\t<li><y</li>\n\t</ul>\n\t</li>') + output = self.engine.render_to_string( + "unordered_list03", {"a": ["x>", [mark_safe("<y")]]} + ) + self.assertEqual( + output, "\t<li>x>\n\t<ul>\n\t\t<li><y</li>\n\t</ul>\n\t</li>" + ) - @setup({'unordered_list04': '{% autoescape off %}{{ a|unordered_list }}{% endautoescape %}'}) + @setup( + { + "unordered_list04": "{% autoescape off %}{{ a|unordered_list }}{% endautoescape %}" + } + ) def test_unordered_list04(self): - output = self.engine.render_to_string('unordered_list04', {'a': ['x>', [mark_safe('<y')]]}) - self.assertEqual(output, '\t<li>x>\n\t<ul>\n\t\t<li><y</li>\n\t</ul>\n\t</li>') + output = self.engine.render_to_string( + "unordered_list04", {"a": ["x>", [mark_safe("<y")]]} + ) + self.assertEqual(output, "\t<li>x>\n\t<ul>\n\t\t<li><y</li>\n\t</ul>\n\t</li>") - @setup({'unordered_list05': '{% autoescape off %}{{ a|unordered_list }}{% endautoescape %}'}) + @setup( + { + "unordered_list05": "{% autoescape off %}{{ a|unordered_list }}{% endautoescape %}" + } + ) def test_unordered_list05(self): - output = self.engine.render_to_string('unordered_list05', {'a': ['x>', ['<y']]}) - self.assertEqual(output, '\t<li>x>\n\t<ul>\n\t\t<li><y</li>\n\t</ul>\n\t</li>') + output = self.engine.render_to_string("unordered_list05", {"a": ["x>", ["<y"]]}) + self.assertEqual(output, "\t<li>x>\n\t<ul>\n\t\t<li><y</li>\n\t</ul>\n\t</li>") class FunctionTests(SimpleTestCase): - def test_list(self): - self.assertEqual(unordered_list(['item 1', 'item 2']), '\t<li>item 1</li>\n\t<li>item 2</li>') + self.assertEqual( + unordered_list(["item 1", "item 2"]), "\t<li>item 1</li>\n\t<li>item 2</li>" + ) def test_list_gettext(self): self.assertEqual( - unordered_list(['item 1', gettext_lazy('item 2')]), - '\t<li>item 1</li>\n\t<li>item 2</li>' + unordered_list(["item 1", gettext_lazy("item 2")]), + "\t<li>item 1</li>\n\t<li>item 2</li>", ) def test_nested(self): self.assertEqual( - unordered_list(['item 1', ['item 1.1']]), - '\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1</li>\n\t</ul>\n\t</li>', + unordered_list(["item 1", ["item 1.1"]]), + "\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1</li>\n\t</ul>\n\t</li>", ) def test_nested2(self): self.assertEqual( - unordered_list(['item 1', ['item 1.1', 'item1.2'], 'item 2']), - '\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1</li>\n\t\t<li>item1.2' - '</li>\n\t</ul>\n\t</li>\n\t<li>item 2</li>', + unordered_list(["item 1", ["item 1.1", "item1.2"], "item 2"]), + "\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1</li>\n\t\t<li>item1.2" + "</li>\n\t</ul>\n\t</li>\n\t<li>item 2</li>", ) def test_nested3(self): self.assertEqual( - unordered_list(['item 1', 'item 2', ['item 2.1']]), - '\t<li>item 1</li>\n\t<li>item 2\n\t<ul>\n\t\t<li>item 2.1' - '</li>\n\t</ul>\n\t</li>', + unordered_list(["item 1", "item 2", ["item 2.1"]]), + "\t<li>item 1</li>\n\t<li>item 2\n\t<ul>\n\t\t<li>item 2.1" + "</li>\n\t</ul>\n\t</li>", ) def test_nested_multiple(self): self.assertEqual( - unordered_list(['item 1', ['item 1.1', ['item 1.1.1', ['item 1.1.1.1']]]]), - '\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1\n\t\t<ul>\n\t\t\t<li>' - 'item 1.1.1\n\t\t\t<ul>\n\t\t\t\t<li>item 1.1.1.1</li>\n\t\t\t' - '</ul>\n\t\t\t</li>\n\t\t</ul>\n\t\t</li>\n\t</ul>\n\t</li>', + unordered_list(["item 1", ["item 1.1", ["item 1.1.1", ["item 1.1.1.1"]]]]), + "\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1\n\t\t<ul>\n\t\t\t<li>" + "item 1.1.1\n\t\t\t<ul>\n\t\t\t\t<li>item 1.1.1.1</li>\n\t\t\t" + "</ul>\n\t\t\t</li>\n\t\t</ul>\n\t\t</li>\n\t</ul>\n\t</li>", ) def test_nested_multiple2(self): self.assertEqual( - unordered_list(['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]), - '\t<li>States\n\t<ul>\n\t\t<li>Kansas\n\t\t<ul>\n\t\t\t<li>' - 'Lawrence</li>\n\t\t\t<li>Topeka</li>\n\t\t</ul>\n\t\t</li>' - '\n\t\t<li>Illinois</li>\n\t</ul>\n\t</li>', + unordered_list(["States", ["Kansas", ["Lawrence", "Topeka"], "Illinois"]]), + "\t<li>States\n\t<ul>\n\t\t<li>Kansas\n\t\t<ul>\n\t\t\t<li>" + "Lawrence</li>\n\t\t\t<li>Topeka</li>\n\t\t</ul>\n\t\t</li>" + "\n\t\t<li>Illinois</li>\n\t</ul>\n\t</li>", ) def test_autoescape(self): self.assertEqual( - unordered_list(['<a>item 1</a>', 'item 2']), - '\t<li><a>item 1</a></li>\n\t<li>item 2</li>', + unordered_list(["<a>item 1</a>", "item 2"]), + "\t<li><a>item 1</a></li>\n\t<li>item 2</li>", ) def test_autoescape_off(self): self.assertEqual( - unordered_list(['<a>item 1</a>', 'item 2'], autoescape=False), - '\t<li><a>item 1</a></li>\n\t<li>item 2</li>', + unordered_list(["<a>item 1</a>", "item 2"], autoescape=False), + "\t<li><a>item 1</a></li>\n\t<li>item 2</li>", ) def test_ulitem(self): @@ -99,14 +119,14 @@ class FunctionTests(SimpleTestCase): self.title = title def __str__(self): - return 'ulitem-%s' % str(self.title) + return "ulitem-%s" % str(self.title) - a = ULItem('a') - b = ULItem('b') - c = ULItem('<a>c</a>') + a = ULItem("a") + b = ULItem("b") + c = ULItem("<a>c</a>") self.assertEqual( unordered_list([a, b, c]), - '\t<li>ulitem-a</li>\n\t<li>ulitem-b</li>\n\t<li>ulitem-<a>c</a></li>', + "\t<li>ulitem-a</li>\n\t<li>ulitem-b</li>\n\t<li>ulitem-<a>c</a></li>", ) def item_generator(): @@ -114,21 +134,21 @@ class FunctionTests(SimpleTestCase): self.assertEqual( unordered_list(item_generator()), - '\t<li>ulitem-a</li>\n\t<li>ulitem-b</li>\n\t<li>ulitem-<a>c</a></li>', + "\t<li>ulitem-a</li>\n\t<li>ulitem-b</li>\n\t<li>ulitem-<a>c</a></li>", ) def test_nested_generators(self): def inner_generator(): - yield from ('B', 'C') + yield from ("B", "C") def item_generator(): - yield 'A' + yield "A" yield inner_generator() - yield 'D' + yield "D" self.assertEqual( unordered_list(item_generator()), - '\t<li>A\n\t<ul>\n\t\t<li>B</li>\n\t\t<li>C</li>\n\t</ul>\n\t</li>\n\t<li>D</li>', + "\t<li>A\n\t<ul>\n\t\t<li>B</li>\n\t\t<li>C</li>\n\t</ul>\n\t</li>\n\t<li>D</li>", ) def test_ulitem_autoescape_off(self): @@ -137,14 +157,14 @@ class FunctionTests(SimpleTestCase): self.title = title def __str__(self): - return 'ulitem-%s' % str(self.title) + return "ulitem-%s" % str(self.title) - a = ULItem('a') - b = ULItem('b') - c = ULItem('<a>c</a>') + a = ULItem("a") + b = ULItem("b") + c = ULItem("<a>c</a>") self.assertEqual( unordered_list([a, b, c], autoescape=False), - '\t<li>ulitem-a</li>\n\t<li>ulitem-b</li>\n\t<li>ulitem-<a>c</a></li>', + "\t<li>ulitem-a</li>\n\t<li>ulitem-b</li>\n\t<li>ulitem-<a>c</a></li>", ) def item_generator(): @@ -152,5 +172,5 @@ class FunctionTests(SimpleTestCase): self.assertEqual( unordered_list(item_generator(), autoescape=False), - '\t<li>ulitem-a</li>\n\t<li>ulitem-b</li>\n\t<li>ulitem-<a>c</a></li>', + "\t<li>ulitem-a</li>\n\t<li>ulitem-b</li>\n\t<li>ulitem-<a>c</a></li>", ) diff --git a/tests/template_tests/filter_tests/test_upper.py b/tests/template_tests/filter_tests/test_upper.py index a9efaf5322..01a2f306ae 100644 --- a/tests/template_tests/filter_tests/test_upper.py +++ b/tests/template_tests/filter_tests/test_upper.py @@ -11,25 +11,32 @@ class UpperTests(SimpleTestCase): so it's not safe for non-escaping purposes. """ - @setup({'upper01': '{% autoescape off %}{{ a|upper }} {{ b|upper }}{% endautoescape %}'}) + @setup( + { + "upper01": "{% autoescape off %}{{ a|upper }} {{ b|upper }}{% endautoescape %}" + } + ) def test_upper01(self): - output = self.engine.render_to_string('upper01', {'a': 'a & b', 'b': mark_safe('a & b')}) - self.assertEqual(output, 'A & B A & B') + output = self.engine.render_to_string( + "upper01", {"a": "a & b", "b": mark_safe("a & b")} + ) + self.assertEqual(output, "A & B A & B") - @setup({'upper02': '{{ a|upper }} {{ b|upper }}'}) + @setup({"upper02": "{{ a|upper }} {{ b|upper }}"}) def test_upper02(self): - output = self.engine.render_to_string('upper02', {'a': 'a & b', 'b': mark_safe('a & b')}) - self.assertEqual(output, 'A & B A &AMP; B') + output = self.engine.render_to_string( + "upper02", {"a": "a & b", "b": mark_safe("a & b")} + ) + self.assertEqual(output, "A & B A &AMP; B") class FunctionTests(SimpleTestCase): - def test_upper(self): - self.assertEqual(upper('Mixed case input'), 'MIXED CASE INPUT') + self.assertEqual(upper("Mixed case input"), "MIXED CASE INPUT") def test_unicode(self): # lowercase e umlaut - self.assertEqual(upper('\xeb'), '\xcb') + self.assertEqual(upper("\xeb"), "\xcb") def test_non_string_input(self): - self.assertEqual(upper(123), '123') + self.assertEqual(upper(123), "123") diff --git a/tests/template_tests/filter_tests/test_urlencode.py b/tests/template_tests/filter_tests/test_urlencode.py index d095bb8fae..d3c8d2931a 100644 --- a/tests/template_tests/filter_tests/test_urlencode.py +++ b/tests/template_tests/filter_tests/test_urlencode.py @@ -5,22 +5,20 @@ from ..utils import setup class UrlencodeTests(SimpleTestCase): - - @setup({'urlencode01': '{{ url|urlencode }}'}) + @setup({"urlencode01": "{{ url|urlencode }}"}) def test_urlencode01(self): - output = self.engine.render_to_string('urlencode01', {'url': '/test&"/me?/'}) - self.assertEqual(output, '/test%26%22/me%3F/') + output = self.engine.render_to_string("urlencode01", {"url": '/test&"/me?/'}) + self.assertEqual(output, "/test%26%22/me%3F/") - @setup({'urlencode02': '/test/{{ urlbit|urlencode:"" }}/'}) + @setup({"urlencode02": '/test/{{ urlbit|urlencode:"" }}/'}) def test_urlencode02(self): - output = self.engine.render_to_string('urlencode02', {'urlbit': 'escape/slash'}) - self.assertEqual(output, '/test/escape%2Fslash/') + output = self.engine.render_to_string("urlencode02", {"urlbit": "escape/slash"}) + self.assertEqual(output, "/test/escape%2Fslash/") class FunctionTests(SimpleTestCase): - def test_urlencode(self): - self.assertEqual(urlencode('fran\xe7ois & jill'), 'fran%C3%A7ois%20%26%20jill') + self.assertEqual(urlencode("fran\xe7ois & jill"), "fran%C3%A7ois%20%26%20jill") def test_non_string_input(self): - self.assertEqual(urlencode(1), '1') + self.assertEqual(urlencode(1), "1") diff --git a/tests/template_tests/filter_tests/test_urlize.py b/tests/template_tests/filter_tests/test_urlize.py index 7783ed7280..01e97b35fc 100644 --- a/tests/template_tests/filter_tests/test_urlize.py +++ b/tests/template_tests/filter_tests/test_urlize.py @@ -7,73 +7,92 @@ from ..utils import setup class UrlizeTests(SimpleTestCase): - - @setup({'urlize01': '{% autoescape off %}{{ a|urlize }} {{ b|urlize }}{% endautoescape %}'}) + @setup( + { + "urlize01": "{% autoescape off %}{{ a|urlize }} {{ b|urlize }}{% endautoescape %}" + } + ) def test_urlize01(self): output = self.engine.render_to_string( - 'urlize01', - {'a': 'http://example.com/?x=&y=', 'b': mark_safe('http://example.com?x=&y=<2>')}, + "urlize01", + { + "a": "http://example.com/?x=&y=", + "b": mark_safe("http://example.com?x=&y=<2>"), + }, ) self.assertEqual( output, '<a href="http://example.com/?x=&y=" rel="nofollow">http://example.com/?x=&y=</a> ' - '<a href="http://example.com?x=&y=%3C2%3E" rel="nofollow">http://example.com?x=&y=<2></a>' + '<a href="http://example.com?x=&y=%3C2%3E" rel="nofollow">http://example.com?x=&y=<2></a>', ) - @setup({'urlize02': '{{ a|urlize }} {{ b|urlize }}'}) + @setup({"urlize02": "{{ a|urlize }} {{ b|urlize }}"}) def test_urlize02(self): output = self.engine.render_to_string( - 'urlize02', - {'a': "http://example.com/?x=&y=", 'b': mark_safe("http://example.com?x=&y=")}, + "urlize02", + { + "a": "http://example.com/?x=&y=", + "b": mark_safe("http://example.com?x=&y="), + }, ) self.assertEqual( output, '<a href="http://example.com/?x=&y=" rel="nofollow">http://example.com/?x=&y=</a> ' - '<a href="http://example.com?x=&y=" rel="nofollow">http://example.com?x=&y=</a>' + '<a href="http://example.com?x=&y=" rel="nofollow">http://example.com?x=&y=</a>', ) - @setup({'urlize03': '{% autoescape off %}{{ a|urlize }}{% endautoescape %}'}) + @setup({"urlize03": "{% autoescape off %}{{ a|urlize }}{% endautoescape %}"}) def test_urlize03(self): - output = self.engine.render_to_string('urlize03', {'a': mark_safe("a & b")}) - self.assertEqual(output, 'a & b') + output = self.engine.render_to_string("urlize03", {"a": mark_safe("a & b")}) + self.assertEqual(output, "a & b") - @setup({'urlize04': '{{ a|urlize }}'}) + @setup({"urlize04": "{{ a|urlize }}"}) def test_urlize04(self): - output = self.engine.render_to_string('urlize04', {'a': mark_safe("a & b")}) - self.assertEqual(output, 'a & b') + output = self.engine.render_to_string("urlize04", {"a": mark_safe("a & b")}) + self.assertEqual(output, "a & b") # This will lead to a nonsense result, but at least it won't be # exploitable for XSS purposes when auto-escaping is on. - @setup({'urlize05': '{% autoescape off %}{{ a|urlize }}{% endautoescape %}'}) + @setup({"urlize05": "{% autoescape off %}{{ a|urlize }}{% endautoescape %}"}) def test_urlize05(self): - output = self.engine.render_to_string('urlize05', {'a': "<script>alert('foo')</script>"}) + output = self.engine.render_to_string( + "urlize05", {"a": "<script>alert('foo')</script>"} + ) self.assertEqual(output, "<script>alert('foo')</script>") - @setup({'urlize06': '{{ a|urlize }}'}) + @setup({"urlize06": "{{ a|urlize }}"}) def test_urlize06(self): - output = self.engine.render_to_string('urlize06', {'a': "<script>alert('foo')</script>"}) - self.assertEqual(output, '<script>alert('foo')</script>') + output = self.engine.render_to_string( + "urlize06", {"a": "<script>alert('foo')</script>"} + ) + self.assertEqual(output, "<script>alert('foo')</script>") # mailto: testing for urlize - @setup({'urlize07': '{{ a|urlize }}'}) + @setup({"urlize07": "{{ a|urlize }}"}) def test_urlize07(self): - output = self.engine.render_to_string('urlize07', {'a': "Email me at me@example.com"}) + output = self.engine.render_to_string( + "urlize07", {"a": "Email me at me@example.com"} + ) self.assertEqual( output, 'Email me at <a href="mailto:me@example.com">me@example.com</a>', ) - @setup({'urlize08': '{{ a|urlize }}'}) + @setup({"urlize08": "{{ a|urlize }}"}) def test_urlize08(self): - output = self.engine.render_to_string('urlize08', {'a': "Email me at <me@example.com>"}) + output = self.engine.render_to_string( + "urlize08", {"a": "Email me at <me@example.com>"} + ) self.assertEqual( output, 'Email me at <<a href="mailto:me@example.com">me@example.com</a>>', ) - @setup({'urlize09': '{% autoescape off %}{{ a|urlize }}{% endautoescape %}'}) + @setup({"urlize09": "{% autoescape off %}{{ a|urlize }}{% endautoescape %}"}) def test_urlize09(self): - output = self.engine.render_to_string('urlize09', {'a': "http://example.com/?x=&y=<2>"}) + output = self.engine.render_to_string( + "urlize09", {"a": "http://example.com/?x=&y=<2>"} + ) self.assertEqual( output, '<a href="http://example.com/?x=&y=%3C2%3E" rel="nofollow">http://example.com/?x=&y=<2></a>', @@ -81,26 +100,25 @@ class UrlizeTests(SimpleTestCase): class FunctionTests(SimpleTestCase): - def test_urls(self): self.assertEqual( - urlize('http://google.com'), + urlize("http://google.com"), '<a href="http://google.com" rel="nofollow">http://google.com</a>', ) self.assertEqual( - urlize('http://google.com/'), + urlize("http://google.com/"), '<a href="http://google.com/" rel="nofollow">http://google.com/</a>', ) self.assertEqual( - urlize('www.google.com'), + urlize("www.google.com"), '<a href="http://www.google.com" rel="nofollow">www.google.com</a>', ) self.assertEqual( - urlize('djangoproject.org'), + urlize("djangoproject.org"), '<a href="http://djangoproject.org" rel="nofollow">djangoproject.org</a>', ) self.assertEqual( - urlize('djangoproject.org/'), + urlize("djangoproject.org/"), '<a href="http://djangoproject.org/" rel="nofollow">djangoproject.org/</a>', ) @@ -112,30 +130,30 @@ class FunctionTests(SimpleTestCase): '<a href="http://www.server.com" rel="nofollow">www.server.com</a>"abc', ) self.assertEqual( - urlize('www.server.com\'abc'), + urlize("www.server.com'abc"), '<a href="http://www.server.com" rel="nofollow">www.server.com</a>'abc', ) self.assertEqual( - urlize('www.server.com<abc'), + urlize("www.server.com<abc"), '<a href="http://www.server.com" rel="nofollow">www.server.com</a><abc', ) self.assertEqual( - urlize('www.server.com>abc'), + urlize("www.server.com>abc"), '<a href="http://www.server.com" rel="nofollow">www.server.com</a>>abc', ) def test_email(self): self.assertEqual( - urlize('info@djangoproject.org'), + urlize("info@djangoproject.org"), '<a href="mailto:info@djangoproject.org">info@djangoproject.org</a>', ) def test_word_with_dot(self): - self.assertEqual(urlize('some.organization'), 'some.organization'), + self.assertEqual(urlize("some.organization"), "some.organization"), def test_https(self): self.assertEqual( - urlize('https://google.com'), + urlize("https://google.com"), '<a href="https://google.com" rel="nofollow">https://google.com</a>', ) @@ -145,28 +163,28 @@ class FunctionTests(SimpleTestCase): teststring is the urlquoted version of 'http://hi.baidu.com/重新开始' """ self.assertEqual( - urlize('http://hi.baidu.com/%E9%87%8D%E6%96%B0%E5%BC%80%E5%A7%8B'), + urlize("http://hi.baidu.com/%E9%87%8D%E6%96%B0%E5%BC%80%E5%A7%8B"), '<a href="http://hi.baidu.com/%E9%87%8D%E6%96%B0%E5%BC%80%E5%A7%8B" rel="nofollow">' - 'http://hi.baidu.com/%E9%87%8D%E6%96%B0%E5%BC%80%E5%A7%8B</a>', + "http://hi.baidu.com/%E9%87%8D%E6%96%B0%E5%BC%80%E5%A7%8B</a>", ) def test_urlencoded(self): self.assertEqual( - urlize('www.mystore.com/30%OffCoupons!'), + urlize("www.mystore.com/30%OffCoupons!"), '<a href="http://www.mystore.com/30%25OffCoupons" rel="nofollow">' - 'www.mystore.com/30%OffCoupons</a>!', + "www.mystore.com/30%OffCoupons</a>!", ) self.assertEqual( - urlize('https://en.wikipedia.org/wiki/Caf%C3%A9'), + urlize("https://en.wikipedia.org/wiki/Caf%C3%A9"), '<a href="https://en.wikipedia.org/wiki/Caf%C3%A9" rel="nofollow">' - 'https://en.wikipedia.org/wiki/Caf%C3%A9</a>', + "https://en.wikipedia.org/wiki/Caf%C3%A9</a>", ) def test_unicode(self): self.assertEqual( - urlize('https://en.wikipedia.org/wiki/Café'), + urlize("https://en.wikipedia.org/wiki/Café"), '<a href="https://en.wikipedia.org/wiki/Caf%C3%A9" rel="nofollow">' - 'https://en.wikipedia.org/wiki/Café</a>', + "https://en.wikipedia.org/wiki/Café</a>", ) def test_parenthesis(self): @@ -174,14 +192,14 @@ class FunctionTests(SimpleTestCase): #11911 - Check urlize keeps balanced parentheses """ self.assertEqual( - urlize('https://en.wikipedia.org/wiki/Django_(web_framework)'), + urlize("https://en.wikipedia.org/wiki/Django_(web_framework)"), '<a href="https://en.wikipedia.org/wiki/Django_(web_framework)" rel="nofollow">' - 'https://en.wikipedia.org/wiki/Django_(web_framework)</a>', + "https://en.wikipedia.org/wiki/Django_(web_framework)</a>", ) self.assertEqual( - urlize('(see https://en.wikipedia.org/wiki/Django_(web_framework))'), + urlize("(see https://en.wikipedia.org/wiki/Django_(web_framework))"), '(see <a href="https://en.wikipedia.org/wiki/Django_(web_framework)" rel="nofollow">' - 'https://en.wikipedia.org/wiki/Django_(web_framework)</a>)', + "https://en.wikipedia.org/wiki/Django_(web_framework)</a>)", ) def test_nofollow(self): @@ -189,7 +207,7 @@ class FunctionTests(SimpleTestCase): #12183 - Check urlize adds nofollow properly - see #12183 """ self.assertEqual( - urlize('foo@bar.com or www.bar.com'), + urlize("foo@bar.com or www.bar.com"), '<a href="mailto:foo@bar.com">foo@bar.com</a> or ' '<a href="http://www.bar.com" rel="nofollow">www.bar.com</a>', ) @@ -198,38 +216,50 @@ class FunctionTests(SimpleTestCase): """ #13704 - Check urlize handles IDN correctly """ - self.assertEqual(urlize('http://c✶.ws'), '<a href="http://xn--c-lgq.ws" rel="nofollow">http://c✶.ws</a>') - self.assertEqual(urlize('www.c✶.ws'), '<a href="http://www.xn--c-lgq.ws" rel="nofollow">www.c✶.ws</a>') - self.assertEqual(urlize('c✶.org'), '<a href="http://xn--c-lgq.org" rel="nofollow">c✶.org</a>') - self.assertEqual(urlize('info@c✶.org'), '<a href="mailto:info@xn--c-lgq.org">info@c✶.org</a>') + self.assertEqual( + urlize("http://c✶.ws"), + '<a href="http://xn--c-lgq.ws" rel="nofollow">http://c✶.ws</a>', + ) + self.assertEqual( + urlize("www.c✶.ws"), + '<a href="http://www.xn--c-lgq.ws" rel="nofollow">www.c✶.ws</a>', + ) + self.assertEqual( + urlize("c✶.org"), '<a href="http://xn--c-lgq.org" rel="nofollow">c✶.org</a>' + ) + self.assertEqual( + urlize("info@c✶.org"), '<a href="mailto:info@xn--c-lgq.org">info@c✶.org</a>' + ) def test_malformed(self): """ #16395 - Check urlize doesn't highlight malformed URIs """ - self.assertEqual(urlize('http:///www.google.com'), 'http:///www.google.com') - self.assertEqual(urlize('http://.google.com'), 'http://.google.com') - self.assertEqual(urlize('http://@foo.com'), 'http://@foo.com') + self.assertEqual(urlize("http:///www.google.com"), "http:///www.google.com") + self.assertEqual(urlize("http://.google.com"), "http://.google.com") + self.assertEqual(urlize("http://@foo.com"), "http://@foo.com") def test_tlds(self): """ #16656 - Check urlize accepts more TLDs """ - self.assertEqual(urlize('usa.gov'), '<a href="http://usa.gov" rel="nofollow">usa.gov</a>') + self.assertEqual( + urlize("usa.gov"), '<a href="http://usa.gov" rel="nofollow">usa.gov</a>' + ) def test_invalid_email(self): """ #17592 - Check urlize don't crash on invalid email with dot-starting domain """ - self.assertEqual(urlize('email@.stream.ru'), 'email@.stream.ru') + self.assertEqual(urlize("email@.stream.ru"), "email@.stream.ru") def test_uppercase(self): """ #18071 - Check urlize accepts uppercased URL schemes """ self.assertEqual( - urlize('HTTPS://github.com/'), + urlize("HTTPS://github.com/"), '<a href="https://github.com/" rel="nofollow">HTTPS://github.com/</a>', ) @@ -238,26 +268,26 @@ class FunctionTests(SimpleTestCase): #18644 - Check urlize trims trailing period when followed by parenthesis """ self.assertEqual( - urlize('(Go to http://www.example.com/foo.)'), + urlize("(Go to http://www.example.com/foo.)"), '(Go to <a href="http://www.example.com/foo" rel="nofollow">http://www.example.com/foo</a>.)', ) def test_trailing_multiple_punctuation(self): self.assertEqual( - urlize('A test http://testing.com/example..'), - 'A test <a href="http://testing.com/example" rel="nofollow">http://testing.com/example</a>..' + urlize("A test http://testing.com/example.."), + 'A test <a href="http://testing.com/example" rel="nofollow">http://testing.com/example</a>..', ) self.assertEqual( - urlize('A test http://testing.com/example!!'), - 'A test <a href="http://testing.com/example" rel="nofollow">http://testing.com/example</a>!!' + urlize("A test http://testing.com/example!!"), + 'A test <a href="http://testing.com/example" rel="nofollow">http://testing.com/example</a>!!', ) self.assertEqual( - urlize('A test http://testing.com/example!!!'), - 'A test <a href="http://testing.com/example" rel="nofollow">http://testing.com/example</a>!!!' + urlize("A test http://testing.com/example!!!"), + 'A test <a href="http://testing.com/example" rel="nofollow">http://testing.com/example</a>!!!', ) self.assertEqual( urlize('A test http://testing.com/example.,:;)"!'), - 'A test <a href="http://testing.com/example" rel="nofollow">http://testing.com/example</a>.,:;)"!' + 'A test <a href="http://testing.com/example" rel="nofollow">http://testing.com/example</a>.,:;)"!', ) def test_brackets(self): @@ -265,46 +295,46 @@ class FunctionTests(SimpleTestCase): #19070 - Check urlize handles brackets properly """ self.assertEqual( - urlize('[see www.example.com]'), + urlize("[see www.example.com]"), '[see <a href="http://www.example.com" rel="nofollow">www.example.com</a>]', ) self.assertEqual( - urlize('see test[at[example.com'), + urlize("see test[at[example.com"), 'see <a href="http://test[at[example.com" rel="nofollow">test[at[example.com</a>', ) self.assertEqual( - urlize('[http://168.192.0.1](http://168.192.0.1)'), + urlize("[http://168.192.0.1](http://168.192.0.1)"), '[<a href="http://168.192.0.1](http://168.192.0.1)" rel="nofollow">' - 'http://168.192.0.1](http://168.192.0.1)</a>', + "http://168.192.0.1](http://168.192.0.1)</a>", ) def test_wrapping_characters(self): wrapping_chars = ( - ('()', ('(', ')')), - ('<>', ('<', '>')), - ('[]', ('[', ']')), - ('""', ('"', '"')), - ("''", (''', ''')), + ("()", ("(", ")")), + ("<>", ("<", ">")), + ("[]", ("[", "]")), + ('""', (""", """)), + ("''", ("'", "'")), ) for wrapping_in, (start_out, end_out) in wrapping_chars: with self.subTest(wrapping_in=wrapping_in): start_in, end_in = wrapping_in self.assertEqual( - urlize(start_in + 'https://www.example.org/' + end_in), - start_out + - '<a href="https://www.example.org/" rel="nofollow">https://www.example.org/</a>' + - end_out, + urlize(start_in + "https://www.example.org/" + end_in), + start_out + + '<a href="https://www.example.org/" rel="nofollow">https://www.example.org/</a>' + + end_out, ) def test_ipv4(self): self.assertEqual( - urlize('http://192.168.0.15/api/9'), + urlize("http://192.168.0.15/api/9"), '<a href="http://192.168.0.15/api/9" rel="nofollow">http://192.168.0.15/api/9</a>', ) def test_ipv6(self): self.assertEqual( - urlize('http://[2001:db8:cafe::2]/api/9'), + urlize("http://[2001:db8:cafe::2]/api/9"), '<a href="http://[2001:db8:cafe::2]/api/9" rel="nofollow">http://[2001:db8:cafe::2]/api/9</a>', ) @@ -325,15 +355,15 @@ class FunctionTests(SimpleTestCase): 'before "<a href="mailto:hi@example.com">hi@example.com</a> afterward', ) self.assertEqual( - urlize('before \'hi@example.com\' afterward', autoescape=False), - 'before \'<a href="mailto:hi@example.com">hi@example.com</a>\' afterward', + urlize("before 'hi@example.com' afterward", autoescape=False), + "before '<a href=\"mailto:hi@example.com\">hi@example.com</a>' afterward", ) self.assertEqual( - urlize('before hi@example.com\' afterward', autoescape=False), + urlize("before hi@example.com' afterward", autoescape=False), 'before <a href="mailto:hi@example.com">hi@example.com</a>\' afterward', ) self.assertEqual( - urlize('before \'hi@example.com afterward', autoescape=False), + urlize("before 'hi@example.com afterward", autoescape=False), 'before \'<a href="mailto:hi@example.com">hi@example.com</a> afterward', ) @@ -342,7 +372,9 @@ class FunctionTests(SimpleTestCase): #20364 - Check urlize copes with commas following URLs in quotes """ self.assertEqual( - urlize('Email us at "hi@example.com", or phone us at +xx.yy', autoescape=False), + urlize( + 'Email us at "hi@example.com", or phone us at +xx.yy', autoescape=False + ), 'Email us at "<a href="mailto:hi@example.com">hi@example.com</a>", or phone us at +xx.yy', ) @@ -352,29 +384,29 @@ class FunctionTests(SimpleTestCase): or query string """ self.assertEqual( - urlize('Go to djangoproject.com! and enjoy.'), + urlize("Go to djangoproject.com! and enjoy."), 'Go to <a href="http://djangoproject.com" rel="nofollow">djangoproject.com</a>! and enjoy.', ) self.assertEqual( - urlize('Search for google.com/?q=! and see.'), + urlize("Search for google.com/?q=! and see."), 'Search for <a href="http://google.com/?q=" rel="nofollow">google.com/?q=</a>! and see.', ) self.assertEqual( - urlize('Search for google.com/?q=dj!`? and see.'), + urlize("Search for google.com/?q=dj!`? and see."), 'Search for <a href="http://google.com/?q=dj%21%60%3F" rel="nofollow">google.com/?q=dj!`?</a> and see.', ) self.assertEqual( - urlize('Search for google.com/?q=dj!`?! and see.'), + urlize("Search for google.com/?q=dj!`?! and see."), 'Search for <a href="http://google.com/?q=dj%21%60%3F" rel="nofollow">google.com/?q=dj!`?</a>! and see.', ) def test_non_string_input(self): - self.assertEqual(urlize(123), '123') + self.assertEqual(urlize(123), "123") def test_autoescape(self): self.assertEqual( urlize('foo<a href=" google.com ">bar</a>buz'), - 'foo<a href=" <a href="http://google.com" rel="nofollow">google.com</a> ">bar</a>buz' + 'foo<a href=" <a href="http://google.com" rel="nofollow">google.com</a> ">bar</a>buz', ) def test_autoescape_off(self): @@ -384,8 +416,8 @@ class FunctionTests(SimpleTestCase): ) def test_lazystring(self): - prepend_www = lazy(lambda url: 'www.' + url, str) + prepend_www = lazy(lambda url: "www." + url, str) self.assertEqual( - urlize(prepend_www('google.com')), + urlize(prepend_www("google.com")), '<a href="http://www.google.com" rel="nofollow">www.google.com</a>', ) diff --git a/tests/template_tests/filter_tests/test_urlizetrunc.py b/tests/template_tests/filter_tests/test_urlizetrunc.py index 09bbe776cf..69e4ec4741 100644 --- a/tests/template_tests/filter_tests/test_urlizetrunc.py +++ b/tests/template_tests/filter_tests/test_urlizetrunc.py @@ -6,56 +6,56 @@ from ..utils import setup class UrlizetruncTests(SimpleTestCase): - - @setup({ - 'urlizetrunc01': '{% autoescape off %}{{ a|urlizetrunc:"8" }} {{ b|urlizetrunc:"8" }}{% endautoescape %}' - }) + @setup( + { + "urlizetrunc01": '{% autoescape off %}{{ a|urlizetrunc:"8" }} {{ b|urlizetrunc:"8" }}{% endautoescape %}' + } + ) def test_urlizetrunc01(self): output = self.engine.render_to_string( - 'urlizetrunc01', + "urlizetrunc01", { - 'a': '"Unsafe" http://example.com/x=&y=', - 'b': mark_safe('"Safe" http://example.com?x=&y='), + "a": '"Unsafe" http://example.com/x=&y=', + "b": mark_safe(""Safe" http://example.com?x=&y="), }, ) self.assertEqual( output, '"Unsafe" <a href="http://example.com/x=&y=" rel="nofollow">http://…</a> ' - '"Safe" <a href="http://example.com?x=&y=" rel="nofollow">http://…</a>' + '"Safe" <a href="http://example.com?x=&y=" rel="nofollow">http://…</a>', ) - @setup({'urlizetrunc02': '{{ a|urlizetrunc:"8" }} {{ b|urlizetrunc:"8" }}'}) + @setup({"urlizetrunc02": '{{ a|urlizetrunc:"8" }} {{ b|urlizetrunc:"8" }}'}) def test_urlizetrunc02(self): output = self.engine.render_to_string( - 'urlizetrunc02', + "urlizetrunc02", { - 'a': '"Unsafe" http://example.com/x=&y=', - 'b': mark_safe('"Safe" http://example.com?x=&y='), + "a": '"Unsafe" http://example.com/x=&y=', + "b": mark_safe(""Safe" http://example.com?x=&y="), }, ) self.assertEqual( output, '"Unsafe" <a href="http://example.com/x=&y=" rel="nofollow">http://…</a> ' - '"Safe" <a href="http://example.com?x=&y=" rel="nofollow">http://…</a>' + '"Safe" <a href="http://example.com?x=&y=" rel="nofollow">http://…</a>', ) class FunctionTests(SimpleTestCase): - def test_truncate(self): - uri = 'http://31characteruri.com/test/' + uri = "http://31characteruri.com/test/" self.assertEqual(len(uri), 31) self.assertEqual( urlizetrunc(uri, 31), '<a href="http://31characteruri.com/test/" rel="nofollow">' - 'http://31characteruri.com/test/</a>', + "http://31characteruri.com/test/</a>", ) self.assertEqual( urlizetrunc(uri, 30), '<a href="http://31characteruri.com/test/" rel="nofollow">' - 'http://31characteruri.com/tes…</a>', + "http://31characteruri.com/tes…</a>", ) self.assertEqual( @@ -65,24 +65,27 @@ class FunctionTests(SimpleTestCase): def test_overtruncate(self): self.assertEqual( - urlizetrunc('http://short.com/', 20), + urlizetrunc("http://short.com/", 20), '<a href="http://short.com/" rel="nofollow">http://short.com/</a>', ) def test_query_string(self): self.assertEqual( - urlizetrunc('http://www.google.co.uk/search?hl=en&q=some+long+url&btnG=Search&meta=', 20), + urlizetrunc( + "http://www.google.co.uk/search?hl=en&q=some+long+url&btnG=Search&meta=", + 20, + ), '<a href="http://www.google.co.uk/search?hl=en&q=some+long+url&btnG=Search&' 'meta=" rel="nofollow">http://www.google.c…</a>', ) def test_non_string_input(self): - self.assertEqual(urlizetrunc(123, 1), '123') + self.assertEqual(urlizetrunc(123, 1), "123") def test_autoescape(self): self.assertEqual( urlizetrunc('foo<a href=" google.com ">bar</a>buz', 10), - 'foo<a href=" <a href="http://google.com" rel="nofollow">google.com</a> ">bar</a>buz' + 'foo<a href=" <a href="http://google.com" rel="nofollow">google.com</a> ">bar</a>buz', ) def test_autoescape_off(self): diff --git a/tests/template_tests/filter_tests/test_wordcount.py b/tests/template_tests/filter_tests/test_wordcount.py index c49ebdf48b..d15447086f 100644 --- a/tests/template_tests/filter_tests/test_wordcount.py +++ b/tests/template_tests/filter_tests/test_wordcount.py @@ -6,28 +6,34 @@ from ..utils import setup class WordcountTests(SimpleTestCase): - - @setup({'wordcount01': '{% autoescape off %}{{ a|wordcount }} {{ b|wordcount }}{% endautoescape %}'}) + @setup( + { + "wordcount01": "{% autoescape off %}{{ a|wordcount }} {{ b|wordcount }}{% endautoescape %}" + } + ) def test_wordcount01(self): - output = self.engine.render_to_string('wordcount01', {'a': 'a & b', 'b': mark_safe('a & b')}) - self.assertEqual(output, '3 3') + output = self.engine.render_to_string( + "wordcount01", {"a": "a & b", "b": mark_safe("a & b")} + ) + self.assertEqual(output, "3 3") - @setup({'wordcount02': '{{ a|wordcount }} {{ b|wordcount }}'}) + @setup({"wordcount02": "{{ a|wordcount }} {{ b|wordcount }}"}) def test_wordcount02(self): - output = self.engine.render_to_string('wordcount02', {'a': 'a & b', 'b': mark_safe('a & b')}) - self.assertEqual(output, '3 3') + output = self.engine.render_to_string( + "wordcount02", {"a": "a & b", "b": mark_safe("a & b")} + ) + self.assertEqual(output, "3 3") class FunctionTests(SimpleTestCase): - def test_empty_string(self): - self.assertEqual(wordcount(''), 0) + self.assertEqual(wordcount(""), 0) def test_count_one(self): - self.assertEqual(wordcount('oneword'), 1) + self.assertEqual(wordcount("oneword"), 1) def test_count_multiple(self): - self.assertEqual(wordcount('lots of words'), 3) + self.assertEqual(wordcount("lots of words"), 3) def test_non_string_input(self): self.assertEqual(wordcount(123), 1) diff --git a/tests/template_tests/filter_tests/test_wordwrap.py b/tests/template_tests/filter_tests/test_wordwrap.py index 02f860582b..fb2bce5a90 100644 --- a/tests/template_tests/filter_tests/test_wordwrap.py +++ b/tests/template_tests/filter_tests/test_wordwrap.py @@ -7,47 +7,63 @@ from ..utils import setup class WordwrapTests(SimpleTestCase): - - @setup({ - 'wordwrap01': '{% autoescape off %}{{ a|wordwrap:"3" }} {{ b|wordwrap:"3" }}{% endautoescape %}' - }) + @setup( + { + "wordwrap01": '{% autoescape off %}{{ a|wordwrap:"3" }} {{ b|wordwrap:"3" }}{% endautoescape %}' + } + ) def test_wordwrap01(self): - output = self.engine.render_to_string('wordwrap01', {'a': 'a & b', 'b': mark_safe('a & b')}) - self.assertEqual(output, 'a &\nb a &\nb') + output = self.engine.render_to_string( + "wordwrap01", {"a": "a & b", "b": mark_safe("a & b")} + ) + self.assertEqual(output, "a &\nb a &\nb") - @setup({'wordwrap02': '{{ a|wordwrap:"3" }} {{ b|wordwrap:"3" }}'}) + @setup({"wordwrap02": '{{ a|wordwrap:"3" }} {{ b|wordwrap:"3" }}'}) def test_wordwrap02(self): - output = self.engine.render_to_string('wordwrap02', {'a': 'a & b', 'b': mark_safe('a & b')}) - self.assertEqual(output, 'a &\nb a &\nb') + output = self.engine.render_to_string( + "wordwrap02", {"a": "a & b", "b": mark_safe("a & b")} + ) + self.assertEqual(output, "a &\nb a &\nb") class FunctionTests(SimpleTestCase): - def test_wrap(self): self.assertEqual( - wordwrap('this is a long paragraph of text that really needs to be wrapped I\'m afraid', 14), - 'this is a long\nparagraph of\ntext that\nreally needs\nto be wrapped\nI\'m afraid', + wordwrap( + "this is a long paragraph of text that really needs to be wrapped I'm afraid", + 14, + ), + "this is a long\nparagraph of\ntext that\nreally needs\nto be wrapped\nI'm afraid", ) def test_indent(self): self.assertEqual( - wordwrap('this is a short paragraph of text.\n But this line should be indented', 14), - 'this is a\nshort\nparagraph of\ntext.\n But this\nline should be\nindented', + wordwrap( + "this is a short paragraph of text.\n But this line should be indented", + 14, + ), + "this is a\nshort\nparagraph of\ntext.\n But this\nline should be\nindented", ) def test_indent2(self): self.assertEqual( - wordwrap('this is a short paragraph of text.\n But this line should be indented', 15), - 'this is a short\nparagraph of\ntext.\n But this line\nshould be\nindented', + wordwrap( + "this is a short paragraph of text.\n But this line should be indented", + 15, + ), + "this is a short\nparagraph of\ntext.\n But this line\nshould be\nindented", ) def test_non_string_input(self): - self.assertEqual(wordwrap(123, 2), '123') + self.assertEqual(wordwrap(123, 2), "123") def test_wrap_lazy_string(self): self.assertEqual( - wordwrap(lazystr( - 'this is a long paragraph of text that really needs to be wrapped I\'m afraid' - ), 14), - 'this is a long\nparagraph of\ntext that\nreally needs\nto be wrapped\nI\'m afraid', + wordwrap( + lazystr( + "this is a long paragraph of text that really needs to be wrapped I'm afraid" + ), + 14, + ), + "this is a long\nparagraph of\ntext that\nreally needs\nto be wrapped\nI'm afraid", ) diff --git a/tests/template_tests/filter_tests/test_yesno.py b/tests/template_tests/filter_tests/test_yesno.py index 70b383a2b6..d26b2a7684 100644 --- a/tests/template_tests/filter_tests/test_yesno.py +++ b/tests/template_tests/filter_tests/test_yesno.py @@ -5,36 +5,37 @@ from ..utils import setup class YesNoTests(SimpleTestCase): - @setup({'t': '{{ var|yesno:"yup,nup,mup" }} {{ var|yesno }}'}) + @setup({"t": '{{ var|yesno:"yup,nup,mup" }} {{ var|yesno }}'}) def test_true(self): - output = self.engine.render_to_string('t', {'var': True}) - self.assertEqual(output, 'yup yes') + output = self.engine.render_to_string("t", {"var": True}) + self.assertEqual(output, "yup yes") class FunctionTests(SimpleTestCase): - def test_true(self): - self.assertEqual(yesno(True), 'yes') + self.assertEqual(yesno(True), "yes") def test_false(self): - self.assertEqual(yesno(False), 'no') + self.assertEqual(yesno(False), "no") def test_none(self): - self.assertEqual(yesno(None), 'maybe') + self.assertEqual(yesno(None), "maybe") def test_true_arguments(self): - self.assertEqual(yesno(True, 'certainly,get out of town,perhaps'), 'certainly') + self.assertEqual(yesno(True, "certainly,get out of town,perhaps"), "certainly") def test_false_arguments(self): - self.assertEqual(yesno(False, 'certainly,get out of town,perhaps'), 'get out of town') + self.assertEqual( + yesno(False, "certainly,get out of town,perhaps"), "get out of town" + ) def test_none_two_arguments(self): - self.assertEqual(yesno(None, 'certainly,get out of town'), 'get out of town') + self.assertEqual(yesno(None, "certainly,get out of town"), "get out of town") def test_none_three_arguments(self): - self.assertEqual(yesno(None, 'certainly,get out of town,perhaps'), 'perhaps') + self.assertEqual(yesno(None, "certainly,get out of town,perhaps"), "perhaps") def test_invalid_value(self): - self.assertIs(yesno(True, 'yes'), True) - self.assertIs(yesno(False, 'yes'), False) - self.assertIsNone(yesno(None, 'yes')) + self.assertIs(yesno(True, "yes"), True) + self.assertIs(yesno(False, "yes"), False) + self.assertIsNone(yesno(None, "yes")) diff --git a/tests/template_tests/filter_tests/timezone_utils.py b/tests/template_tests/filter_tests/timezone_utils.py index 874c634cfd..a990d164ae 100644 --- a/tests/template_tests/filter_tests/timezone_utils.py +++ b/tests/template_tests/filter_tests/timezone_utils.py @@ -5,13 +5,14 @@ from django.utils import timezone class TimezoneTestCase(SimpleTestCase): - def setUp(self): self.now = datetime.now() self.now_tz = timezone.make_aware( - self.now, timezone.get_default_timezone(), + self.now, + timezone.get_default_timezone(), ) self.now_tz_i = timezone.localtime( - self.now_tz, timezone.get_fixed_timezone(195), + self.now_tz, + timezone.get_fixed_timezone(195), ) self.today = date.today() diff --git a/tests/template_tests/syntax_tests/i18n/base.py b/tests/template_tests/syntax_tests/i18n/base.py index 61d2bbdb1c..6197179ee4 100644 --- a/tests/template_tests/syntax_tests/i18n/base.py +++ b/tests/template_tests/syntax_tests/i18n/base.py @@ -7,7 +7,7 @@ from django.utils.translation import activate, get_language here = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) pdir = os.path.split(os.path.split(os.path.abspath(here))[0])[0] extended_locale_paths = settings.LOCALE_PATHS + [ - os.path.join(pdir, 'i18n', 'other', 'locale'), + os.path.join(pdir, "i18n", "other", "locale"), ] diff --git a/tests/template_tests/syntax_tests/i18n/test_blocktranslate.py b/tests/template_tests/syntax_tests/i18n/test_blocktranslate.py index 114d4392c6..8ad004a899 100644 --- a/tests/template_tests/syntax_tests/i18n/test_blocktranslate.py +++ b/tests/template_tests/syntax_tests/i18n/test_blocktranslate.py @@ -18,18 +18,18 @@ from .base import MultipleLocaleActivationTestCase, extended_locale_paths, here def setup(templates, *args, **kwargs): blocktranslate_setup = base_setup(templates, *args, **kwargs) - blocktrans_setup = base_setup({ - name: template.replace( - '{% blocktranslate ', '{% blocktrans ' - ).replace( - '{% endblocktranslate %}', '{% endblocktrans %}' - ) - for name, template in templates.items() - }) + blocktrans_setup = base_setup( + { + name: template.replace("{% blocktranslate ", "{% blocktrans ").replace( + "{% endblocktranslate %}", "{% endblocktrans %}" + ) + for name, template in templates.items() + } + ) tags = { - 'blocktrans': blocktrans_setup, - 'blocktranslate': blocktranslate_setup, + "blocktrans": blocktrans_setup, + "blocktranslate": blocktranslate_setup, } def decorator(func): @@ -37,300 +37,459 @@ def setup(templates, *args, **kwargs): def inner(self, *args): signature = inspect.signature(func) for tag_name, setup_func in tags.items(): - if 'tag_name' in signature.parameters: + if "tag_name" in signature.parameters: setup_func(partial(func, tag_name=tag_name))(self) else: setup_func(func)(self) + return inner + return decorator class I18nBlockTransTagTests(SimpleTestCase): - libraries = {'i18n': 'django.templatetags.i18n'} + libraries = {"i18n": "django.templatetags.i18n"} - @setup({'i18n03': '{% load i18n %}{% blocktranslate %}{{ anton }}{% endblocktranslate %}'}) + @setup( + { + "i18n03": "{% load i18n %}{% blocktranslate %}{{ anton }}{% endblocktranslate %}" + } + ) def test_i18n03(self): """simple translation of a variable""" - output = self.engine.render_to_string('i18n03', {'anton': 'Å'}) - self.assertEqual(output, 'Å') + output = self.engine.render_to_string("i18n03", {"anton": "Å"}) + self.assertEqual(output, "Å") - @setup({'i18n04': '{% load i18n %}{% blocktranslate with berta=anton|lower %}{{ berta }}{% endblocktranslate %}'}) + @setup( + { + "i18n04": "{% load i18n %}{% blocktranslate with berta=anton|lower %}{{ berta }}{% endblocktranslate %}" + } + ) def test_i18n04(self): """simple translation of a variable and filter""" - output = self.engine.render_to_string('i18n04', {'anton': 'Å'}) - self.assertEqual(output, 'å') + output = self.engine.render_to_string("i18n04", {"anton": "Å"}) + self.assertEqual(output, "å") - @setup({'legacyi18n04': '{% load i18n %}' - '{% blocktranslate with anton|lower as berta %}{{ berta }}{% endblocktranslate %}'}) + @setup( + { + "legacyi18n04": "{% load i18n %}" + "{% blocktranslate with anton|lower as berta %}{{ berta }}{% endblocktranslate %}" + } + ) def test_legacyi18n04(self): """simple translation of a variable and filter""" - output = self.engine.render_to_string('legacyi18n04', {'anton': 'Å'}) - self.assertEqual(output, 'å') + output = self.engine.render_to_string("legacyi18n04", {"anton": "Å"}) + self.assertEqual(output, "å") - @setup({'i18n05': '{% load i18n %}{% blocktranslate %}xxx{{ anton }}xxx{% endblocktranslate %}'}) + @setup( + { + "i18n05": "{% load i18n %}{% blocktranslate %}xxx{{ anton }}xxx{% endblocktranslate %}" + } + ) def test_i18n05(self): """simple translation of a string with interpolation""" - output = self.engine.render_to_string('i18n05', {'anton': 'yyy'}) - self.assertEqual(output, 'xxxyyyxxx') + output = self.engine.render_to_string("i18n05", {"anton": "yyy"}) + self.assertEqual(output, "xxxyyyxxx") - @setup({'i18n07': '{% load i18n %}' - '{% blocktranslate count counter=number %}singular{% plural %}' - '{{ counter }} plural{% endblocktranslate %}'}) + @setup( + { + "i18n07": "{% load i18n %}" + "{% blocktranslate count counter=number %}singular{% plural %}" + "{{ counter }} plural{% endblocktranslate %}" + } + ) def test_i18n07(self): """translation of singular form""" - output = self.engine.render_to_string('i18n07', {'number': 1}) - self.assertEqual(output, 'singular') + output = self.engine.render_to_string("i18n07", {"number": 1}) + self.assertEqual(output, "singular") - @setup({'legacyi18n07': '{% load i18n %}' - '{% blocktranslate count number as counter %}singular{% plural %}' - '{{ counter }} plural{% endblocktranslate %}'}) + @setup( + { + "legacyi18n07": "{% load i18n %}" + "{% blocktranslate count number as counter %}singular{% plural %}" + "{{ counter }} plural{% endblocktranslate %}" + } + ) def test_legacyi18n07(self): """translation of singular form""" - output = self.engine.render_to_string('legacyi18n07', {'number': 1}) - self.assertEqual(output, 'singular') + output = self.engine.render_to_string("legacyi18n07", {"number": 1}) + self.assertEqual(output, "singular") - @setup({'i18n08': '{% load i18n %}' - '{% blocktranslate count number as counter %}singular{% plural %}' - '{{ counter }} plural{% endblocktranslate %}'}) + @setup( + { + "i18n08": "{% load i18n %}" + "{% blocktranslate count number as counter %}singular{% plural %}" + "{{ counter }} plural{% endblocktranslate %}" + } + ) def test_i18n08(self): """translation of plural form""" - output = self.engine.render_to_string('i18n08', {'number': 2}) - self.assertEqual(output, '2 plural') + output = self.engine.render_to_string("i18n08", {"number": 2}) + self.assertEqual(output, "2 plural") - @setup({'legacyi18n08': '{% load i18n %}' - '{% blocktranslate count counter=number %}singular{% plural %}' - '{{ counter }} plural{% endblocktranslate %}'}) + @setup( + { + "legacyi18n08": "{% load i18n %}" + "{% blocktranslate count counter=number %}singular{% plural %}" + "{{ counter }} plural{% endblocktranslate %}" + } + ) def test_legacyi18n08(self): """translation of plural form""" - output = self.engine.render_to_string('legacyi18n08', {'number': 2}) - self.assertEqual(output, '2 plural') + output = self.engine.render_to_string("legacyi18n08", {"number": 2}) + self.assertEqual(output, "2 plural") - @setup({'i18n17': '{% load i18n %}' - '{% blocktranslate with berta=anton|escape %}{{ berta }}{% endblocktranslate %}'}) + @setup( + { + "i18n17": "{% load i18n %}" + "{% blocktranslate with berta=anton|escape %}{{ berta }}{% endblocktranslate %}" + } + ) def test_i18n17(self): """ Escaping inside blocktranslate and translate works as if it was directly in the template. """ - output = self.engine.render_to_string('i18n17', {'anton': 'α & β'}) - self.assertEqual(output, 'α & β') + output = self.engine.render_to_string("i18n17", {"anton": "α & β"}) + self.assertEqual(output, "α & β") - @setup({'i18n18': '{% load i18n %}' - '{% blocktranslate with berta=anton|force_escape %}{{ berta }}{% endblocktranslate %}'}) + @setup( + { + "i18n18": "{% load i18n %}" + "{% blocktranslate with berta=anton|force_escape %}{{ berta }}{% endblocktranslate %}" + } + ) def test_i18n18(self): - output = self.engine.render_to_string('i18n18', {'anton': 'α & β'}) - self.assertEqual(output, 'α & β') + output = self.engine.render_to_string("i18n18", {"anton": "α & β"}) + self.assertEqual(output, "α & β") - @setup({'i18n19': '{% load i18n %}{% blocktranslate %}{{ andrew }}{% endblocktranslate %}'}) + @setup( + { + "i18n19": "{% load i18n %}{% blocktranslate %}{{ andrew }}{% endblocktranslate %}" + } + ) def test_i18n19(self): - output = self.engine.render_to_string('i18n19', {'andrew': 'a & b'}) - self.assertEqual(output, 'a & b') + output = self.engine.render_to_string("i18n19", {"andrew": "a & b"}) + self.assertEqual(output, "a & b") - @setup({'i18n21': '{% load i18n %}{% blocktranslate %}{{ andrew }}{% endblocktranslate %}'}) + @setup( + { + "i18n21": "{% load i18n %}{% blocktranslate %}{{ andrew }}{% endblocktranslate %}" + } + ) def test_i18n21(self): - output = self.engine.render_to_string('i18n21', {'andrew': mark_safe('a & b')}) - self.assertEqual(output, 'a & b') + output = self.engine.render_to_string("i18n21", {"andrew": mark_safe("a & b")}) + self.assertEqual(output, "a & b") - @setup({'legacyi18n17': '{% load i18n %}' - '{% blocktranslate with anton|escape as berta %}{{ berta }}{% endblocktranslate %}'}) + @setup( + { + "legacyi18n17": "{% load i18n %}" + "{% blocktranslate with anton|escape as berta %}{{ berta }}{% endblocktranslate %}" + } + ) def test_legacyi18n17(self): - output = self.engine.render_to_string('legacyi18n17', {'anton': 'α & β'}) - self.assertEqual(output, 'α & β') + output = self.engine.render_to_string("legacyi18n17", {"anton": "α & β"}) + self.assertEqual(output, "α & β") - @setup({'legacyi18n18': '{% load i18n %}' - '{% blocktranslate with anton|force_escape as berta %}' - '{{ berta }}{% endblocktranslate %}'}) + @setup( + { + "legacyi18n18": "{% load i18n %}" + "{% blocktranslate with anton|force_escape as berta %}" + "{{ berta }}{% endblocktranslate %}" + } + ) def test_legacyi18n18(self): - output = self.engine.render_to_string('legacyi18n18', {'anton': 'α & β'}) - self.assertEqual(output, 'α & β') + output = self.engine.render_to_string("legacyi18n18", {"anton": "α & β"}) + self.assertEqual(output, "α & β") - @setup({'i18n26': '{% load i18n %}' - '{% blocktranslate with extra_field=myextra_field count counter=number %}' - 'singular {{ extra_field }}{% plural %}plural{% endblocktranslate %}'}) + @setup( + { + "i18n26": "{% load i18n %}" + "{% blocktranslate with extra_field=myextra_field count counter=number %}" + "singular {{ extra_field }}{% plural %}plural{% endblocktranslate %}" + } + ) def test_i18n26(self): """ translation of plural form with extra field in singular form (#13568) """ - output = self.engine.render_to_string('i18n26', {'myextra_field': 'test', 'number': 1}) - self.assertEqual(output, 'singular test') + output = self.engine.render_to_string( + "i18n26", {"myextra_field": "test", "number": 1} + ) + self.assertEqual(output, "singular test") - @setup({'legacyi18n26': '{% load i18n %}' - '{% blocktranslate with myextra_field as extra_field count number as counter %}' - 'singular {{ extra_field }}{% plural %}plural{% endblocktranslate %}'}) + @setup( + { + "legacyi18n26": "{% load i18n %}" + "{% blocktranslate with myextra_field as extra_field count number as counter %}" + "singular {{ extra_field }}{% plural %}plural{% endblocktranslate %}" + } + ) def test_legacyi18n26(self): - output = self.engine.render_to_string('legacyi18n26', {'myextra_field': 'test', 'number': 1}) - self.assertEqual(output, 'singular test') + output = self.engine.render_to_string( + "legacyi18n26", {"myextra_field": "test", "number": 1} + ) + self.assertEqual(output, "singular test") - @setup({'i18n27': '{% load i18n %}{% blocktranslate count counter=number %}' - '{{ counter }} result{% plural %}{{ counter }} results' - '{% endblocktranslate %}'}) + @setup( + { + "i18n27": "{% load i18n %}{% blocktranslate count counter=number %}" + "{{ counter }} result{% plural %}{{ counter }} results" + "{% endblocktranslate %}" + } + ) def test_i18n27(self): """translation of singular form in Russian (#14126)""" - with translation.override('ru'): - output = self.engine.render_to_string('i18n27', {'number': 1}) - self.assertEqual(output, '1 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442') + with translation.override("ru"): + output = self.engine.render_to_string("i18n27", {"number": 1}) + self.assertEqual( + output, "1 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442" + ) - @setup({'legacyi18n27': '{% load i18n %}' - '{% blocktranslate count number as counter %}{{ counter }} result' - '{% plural %}{{ counter }} results{% endblocktranslate %}'}) + @setup( + { + "legacyi18n27": "{% load i18n %}" + "{% blocktranslate count number as counter %}{{ counter }} result" + "{% plural %}{{ counter }} results{% endblocktranslate %}" + } + ) def test_legacyi18n27(self): - with translation.override('ru'): - output = self.engine.render_to_string('legacyi18n27', {'number': 1}) - self.assertEqual(output, '1 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442') + with translation.override("ru"): + output = self.engine.render_to_string("legacyi18n27", {"number": 1}) + self.assertEqual( + output, "1 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442" + ) - @setup({'i18n28': '{% load i18n %}' - '{% blocktranslate with a=anton b=berta %}{{ a }} + {{ b }}{% endblocktranslate %}'}) + @setup( + { + "i18n28": "{% load i18n %}" + "{% blocktranslate with a=anton b=berta %}{{ a }} + {{ b }}{% endblocktranslate %}" + } + ) def test_i18n28(self): """simple translation of multiple variables""" - output = self.engine.render_to_string('i18n28', {'anton': 'α', 'berta': 'β'}) - self.assertEqual(output, 'α + β') + output = self.engine.render_to_string("i18n28", {"anton": "α", "berta": "β"}) + self.assertEqual(output, "α + β") - @setup({'legacyi18n28': '{% load i18n %}' - '{% blocktranslate with anton as a and berta as b %}' - '{{ a }} + {{ b }}{% endblocktranslate %}'}) + @setup( + { + "legacyi18n28": "{% load i18n %}" + "{% blocktranslate with anton as a and berta as b %}" + "{{ a }} + {{ b }}{% endblocktranslate %}" + } + ) def test_legacyi18n28(self): - output = self.engine.render_to_string('legacyi18n28', {'anton': 'α', 'berta': 'β'}) - self.assertEqual(output, 'α + β') + output = self.engine.render_to_string( + "legacyi18n28", {"anton": "α", "berta": "β"} + ) + self.assertEqual(output, "α + β") # blocktranslate handling of variables which are not in the context. # this should work as if blocktranslate was not there (#19915) - @setup({'i18n34': '{% load i18n %}{% blocktranslate %}{{ missing }}{% endblocktranslate %}'}) + @setup( + { + "i18n34": "{% load i18n %}{% blocktranslate %}{{ missing }}{% endblocktranslate %}" + } + ) def test_i18n34(self): - output = self.engine.render_to_string('i18n34') + output = self.engine.render_to_string("i18n34") if self.engine.string_if_invalid: - self.assertEqual(output, 'INVALID') + self.assertEqual(output, "INVALID") else: - self.assertEqual(output, '') + self.assertEqual(output, "") - @setup({'i18n34_2': '{% load i18n %}{% blocktranslate with a=\'α\' %}{{ missing }}{% endblocktranslate %}'}) + @setup( + { + "i18n34_2": "{% load i18n %}{% blocktranslate with a='α' %}{{ missing }}{% endblocktranslate %}" + } + ) def test_i18n34_2(self): - output = self.engine.render_to_string('i18n34_2') + output = self.engine.render_to_string("i18n34_2") if self.engine.string_if_invalid: - self.assertEqual(output, 'INVALID') + self.assertEqual(output, "INVALID") else: - self.assertEqual(output, '') + self.assertEqual(output, "") - @setup({'i18n34_3': '{% load i18n %}{% blocktranslate with a=anton %}{{ missing }}{% endblocktranslate %}'}) + @setup( + { + "i18n34_3": "{% load i18n %}{% blocktranslate with a=anton %}{{ missing }}{% endblocktranslate %}" + } + ) def test_i18n34_3(self): - output = self.engine.render_to_string( - 'i18n34_3', {'anton': '\xce\xb1'}) + output = self.engine.render_to_string("i18n34_3", {"anton": "\xce\xb1"}) if self.engine.string_if_invalid: - self.assertEqual(output, 'INVALID') + self.assertEqual(output, "INVALID") else: - self.assertEqual(output, '') + self.assertEqual(output, "") - @setup({'i18n37': '{% load i18n %}' - '{% translate "Page not found" as page_not_found %}' - '{% blocktranslate %}Error: {{ page_not_found }}{% endblocktranslate %}'}) + @setup( + { + "i18n37": "{% load i18n %}" + '{% translate "Page not found" as page_not_found %}' + "{% blocktranslate %}Error: {{ page_not_found }}{% endblocktranslate %}" + } + ) def test_i18n37(self): - with translation.override('de'): - output = self.engine.render_to_string('i18n37') - self.assertEqual(output, 'Error: Seite nicht gefunden') + with translation.override("de"): + output = self.engine.render_to_string("i18n37") + self.assertEqual(output, "Error: Seite nicht gefunden") # blocktranslate tag with asvar - @setup({'i18n39': '{% load i18n %}' - '{% blocktranslate asvar page_not_found %}Page not found{% endblocktranslate %}' - '>{{ page_not_found }}<'}) + @setup( + { + "i18n39": "{% load i18n %}" + "{% blocktranslate asvar page_not_found %}Page not found{% endblocktranslate %}" + ">{{ page_not_found }}<" + } + ) def test_i18n39(self): - with translation.override('de'): - output = self.engine.render_to_string('i18n39') - self.assertEqual(output, '>Seite nicht gefunden<') + with translation.override("de"): + output = self.engine.render_to_string("i18n39") + self.assertEqual(output, ">Seite nicht gefunden<") - @setup({'i18n40': '{% load i18n %}' - '{% translate "Page not found" as pg_404 %}' - '{% blocktranslate with page_not_found=pg_404 asvar output %}' - 'Error: {{ page_not_found }}' - '{% endblocktranslate %}'}) + @setup( + { + "i18n40": "{% load i18n %}" + '{% translate "Page not found" as pg_404 %}' + "{% blocktranslate with page_not_found=pg_404 asvar output %}" + "Error: {{ page_not_found }}" + "{% endblocktranslate %}" + } + ) def test_i18n40(self): - output = self.engine.render_to_string('i18n40') - self.assertEqual(output, '') + output = self.engine.render_to_string("i18n40") + self.assertEqual(output, "") - @setup({'i18n41': '{% load i18n %}' - '{% translate "Page not found" as pg_404 %}' - '{% blocktranslate with page_not_found=pg_404 asvar output %}' - 'Error: {{ page_not_found }}' - '{% endblocktranslate %}' - '>{{ output }}<'}) + @setup( + { + "i18n41": "{% load i18n %}" + '{% translate "Page not found" as pg_404 %}' + "{% blocktranslate with page_not_found=pg_404 asvar output %}" + "Error: {{ page_not_found }}" + "{% endblocktranslate %}" + ">{{ output }}<" + } + ) def test_i18n41(self): - with translation.override('de'): - output = self.engine.render_to_string('i18n41') - self.assertEqual(output, '>Error: Seite nicht gefunden<') + with translation.override("de"): + output = self.engine.render_to_string("i18n41") + self.assertEqual(output, ">Error: Seite nicht gefunden<") - @setup({'template': '{% load i18n %}{% blocktranslate asvar %}Yes{% endblocktranslate %}'}) + @setup( + { + "template": "{% load i18n %}{% blocktranslate asvar %}Yes{% endblocktranslate %}" + } + ) def test_blocktrans_syntax_error_missing_assignment(self, tag_name): - msg = "No argument provided to the '{}' tag for the asvar option.".format(tag_name) + msg = "No argument provided to the '{}' tag for the asvar option.".format( + tag_name + ) with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('template') + self.engine.render_to_string("template") - @setup({'template': '{% load i18n %}{% blocktranslate %}%s{% endblocktranslate %}'}) + @setup({"template": "{% load i18n %}{% blocktranslate %}%s{% endblocktranslate %}"}) def test_blocktrans_tag_using_a_string_that_looks_like_str_fmt(self): - output = self.engine.render_to_string('template') - self.assertEqual(output, '%s') + output = self.engine.render_to_string("template") + self.assertEqual(output, "%s") - @setup({'template': '{% load i18n %}{% blocktranslate %}{% block b %} {% endblock %}{% endblocktranslate %}'}) + @setup( + { + "template": "{% load i18n %}{% blocktranslate %}{% block b %} {% endblock %}{% endblocktranslate %}" + } + ) def test_with_block(self, tag_name): - msg = "'{}' doesn't allow other block tags (seen 'block b') inside it".format(tag_name) + msg = "'{}' doesn't allow other block tags (seen 'block b') inside it".format( + tag_name + ) with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('template') + self.engine.render_to_string("template") - @setup({'template': ( - '{% load i18n %}' - '{% blocktranslate %}{% for b in [1, 2, 3] %} {% endfor %}' - '{% endblocktranslate %}' - )}) + @setup( + { + "template": ( + "{% load i18n %}" + "{% blocktranslate %}{% for b in [1, 2, 3] %} {% endfor %}" + "{% endblocktranslate %}" + ) + } + ) def test_with_for(self, tag_name): - msg = "'{}' doesn't allow other block tags (seen 'for b in [1, 2, 3]') inside it".format(tag_name) + msg = "'{}' doesn't allow other block tags (seen 'for b in [1, 2, 3]') inside it".format( + tag_name + ) with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('template') + self.engine.render_to_string("template") - @setup({'template': '{% load i18n %}{% blocktranslate with foo=bar with %}{{ foo }}{% endblocktranslate %}'}) + @setup( + { + "template": "{% load i18n %}{% blocktranslate with foo=bar with %}{{ foo }}{% endblocktranslate %}" + } + ) def test_variable_twice(self): - with self.assertRaisesMessage(TemplateSyntaxError, "The 'with' option was specified more than once"): - self.engine.render_to_string('template', {'foo': 'bar'}) + with self.assertRaisesMessage( + TemplateSyntaxError, "The 'with' option was specified more than once" + ): + self.engine.render_to_string("template", {"foo": "bar"}) - @setup({'template': '{% load i18n %}{% blocktranslate with %}{% endblocktranslate %}'}) + @setup( + {"template": "{% load i18n %}{% blocktranslate with %}{% endblocktranslate %}"} + ) def test_no_args_with(self, tag_name): - msg = '"with" in \'{}\' tag needs at least one keyword argument.'.format(tag_name) + msg = "\"with\" in '{}' tag needs at least one keyword argument.".format( + tag_name + ) with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('template') + self.engine.render_to_string("template") - @setup({'template': '{% load i18n %}{% blocktranslate count a %}{% endblocktranslate %}'}) + @setup( + { + "template": "{% load i18n %}{% blocktranslate count a %}{% endblocktranslate %}" + } + ) def test_count(self, tag_name): - msg = '"count" in \'{}\' tag expected exactly one keyword argument.'.format(tag_name) + msg = "\"count\" in '{}' tag expected exactly one keyword argument.".format( + tag_name + ) with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('template', {'a': [1, 2, 3]}) + self.engine.render_to_string("template", {"a": [1, 2, 3]}) - @setup({'template': ( - '{% load i18n %}{% blocktranslate count counter=num %}{{ counter }}' - '{% plural %}{{ counter }}{% endblocktranslate %}' - )}) + @setup( + { + "template": ( + "{% load i18n %}{% blocktranslate count counter=num %}{{ counter }}" + "{% plural %}{{ counter }}{% endblocktranslate %}" + ) + } + ) def test_count_not_number(self, tag_name): msg = "'counter' argument to '{}' tag must be a number.".format(tag_name) with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('template', {'num': '1'}) + self.engine.render_to_string("template", {"num": "1"}) - @setup({'template': ( - '{% load i18n %}{% blocktranslate count count=var|length %}' - 'There is {{ count }} object. {% block a %} {% endblock %}' - '{% endblocktranslate %}' - )}) + @setup( + { + "template": ( + "{% load i18n %}{% blocktranslate count count=var|length %}" + "There is {{ count }} object. {% block a %} {% endblock %}" + "{% endblocktranslate %}" + ) + } + ) def test_plural_bad_syntax(self, tag_name): msg = "'{}' doesn't allow other block tags inside it".format(tag_name) with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('template', {'var': [1, 2, 3]}) + self.engine.render_to_string("template", {"var": [1, 2, 3]}) class TranslationBlockTranslateTagTests(SimpleTestCase): - tag_name = 'blocktranslate' + tag_name = "blocktranslate" def get_template(self, template_string): return Template( template_string.replace( - '{{% blocktranslate ', - '{{% {}'.format(self.tag_name) + "{{% blocktranslate ", "{{% {}".format(self.tag_name) ).replace( - '{{% endblocktranslate %}}', - '{{% end{} %}}'.format(self.tag_name) + "{{% endblocktranslate %}}", "{{% end{} %}}".format(self.tag_name) ) ) @@ -339,108 +498,112 @@ class TranslationBlockTranslateTagTests(SimpleTestCase): """{% blocktranslate %} takes message contexts into account (#14806).""" trans_real._active = Local() trans_real._translations = {} - with translation.override('de'): + with translation.override("de"): # Nonexistent context t = self.get_template( '{% load i18n %}{% blocktranslate context "nonexistent" %}May' - '{% endblocktranslate %}' + "{% endblocktranslate %}" ) rendered = t.render(Context()) - self.assertEqual(rendered, 'May') + self.assertEqual(rendered, "May") # Existing context... using a literal - t = self.get_template('{% load i18n %}{% blocktranslate context "month name" %}May{% endblocktranslate %}') + t = self.get_template( + '{% load i18n %}{% blocktranslate context "month name" %}May{% endblocktranslate %}' + ) rendered = t.render(Context()) - self.assertEqual(rendered, 'Mai') - t = self.get_template('{% load i18n %}{% blocktranslate context "verb" %}May{% endblocktranslate %}') + self.assertEqual(rendered, "Mai") + t = self.get_template( + '{% load i18n %}{% blocktranslate context "verb" %}May{% endblocktranslate %}' + ) rendered = t.render(Context()) - self.assertEqual(rendered, 'Kann') + self.assertEqual(rendered, "Kann") # Using a variable t = self.get_template( - '{% load i18n %}{% blocktranslate context message_context %}' - 'May{% endblocktranslate %}' + "{% load i18n %}{% blocktranslate context message_context %}" + "May{% endblocktranslate %}" ) - rendered = t.render(Context({'message_context': 'month name'})) - self.assertEqual(rendered, 'Mai') + rendered = t.render(Context({"message_context": "month name"})) + self.assertEqual(rendered, "Mai") t = self.get_template( - '{% load i18n %}{% blocktranslate context message_context %}' - 'May{% endblocktranslate %}' + "{% load i18n %}{% blocktranslate context message_context %}" + "May{% endblocktranslate %}" ) - rendered = t.render(Context({'message_context': 'verb'})) - self.assertEqual(rendered, 'Kann') + rendered = t.render(Context({"message_context": "verb"})) + self.assertEqual(rendered, "Kann") # Using a filter t = self.get_template( - '{% load i18n %}{% blocktranslate context message_context|lower %}May{% endblocktranslate %}' + "{% load i18n %}{% blocktranslate context message_context|lower %}May{% endblocktranslate %}" ) - rendered = t.render(Context({'message_context': 'MONTH NAME'})) - self.assertEqual(rendered, 'Mai') + rendered = t.render(Context({"message_context": "MONTH NAME"})) + self.assertEqual(rendered, "Mai") t = self.get_template( - '{% load i18n %}{% blocktranslate context message_context|lower %}May{% endblocktranslate %}' + "{% load i18n %}{% blocktranslate context message_context|lower %}May{% endblocktranslate %}" ) - rendered = t.render(Context({'message_context': 'VERB'})) - self.assertEqual(rendered, 'Kann') + rendered = t.render(Context({"message_context": "VERB"})) + self.assertEqual(rendered, "Kann") # Using 'count' t = self.get_template( '{% load i18n %}{% blocktranslate count number=1 context "super search" %}' - '{{ number }} super result{% plural %}{{ number }} super results{% endblocktranslate %}' + "{{ number }} super result{% plural %}{{ number }} super results{% endblocktranslate %}" ) rendered = t.render(Context()) - self.assertEqual(rendered, '1 Super-Ergebnis') + self.assertEqual(rendered, "1 Super-Ergebnis") t = self.get_template( '{% load i18n %}{% blocktranslate count number=2 context "super search" %}{{ number }}' - ' super result{% plural %}{{ number }} super results{% endblocktranslate %}' + " super result{% plural %}{{ number }} super results{% endblocktranslate %}" ) rendered = t.render(Context()) - self.assertEqual(rendered, '2 Super-Ergebnisse') + self.assertEqual(rendered, "2 Super-Ergebnisse") t = self.get_template( '{% load i18n %}{% blocktranslate context "other super search" count number=1 %}' - '{{ number }} super result{% plural %}{{ number }} super results{% endblocktranslate %}' + "{{ number }} super result{% plural %}{{ number }} super results{% endblocktranslate %}" ) rendered = t.render(Context()) - self.assertEqual(rendered, '1 anderen Super-Ergebnis') + self.assertEqual(rendered, "1 anderen Super-Ergebnis") t = self.get_template( '{% load i18n %}{% blocktranslate context "other super search" count number=2 %}' - '{{ number }} super result{% plural %}{{ number }} super results{% endblocktranslate %}' + "{{ number }} super result{% plural %}{{ number }} super results{% endblocktranslate %}" ) rendered = t.render(Context()) - self.assertEqual(rendered, '2 andere Super-Ergebnisse') + self.assertEqual(rendered, "2 andere Super-Ergebnisse") # Using 'with' t = self.get_template( '{% load i18n %}{% blocktranslate with num_comments=5 context "comment count" %}' - 'There are {{ num_comments }} comments{% endblocktranslate %}' + "There are {{ num_comments }} comments{% endblocktranslate %}" ) rendered = t.render(Context()) - self.assertEqual(rendered, 'Es gibt 5 Kommentare') + self.assertEqual(rendered, "Es gibt 5 Kommentare") t = self.get_template( '{% load i18n %}{% blocktranslate with num_comments=5 context "other comment count" %}' - 'There are {{ num_comments }} comments{% endblocktranslate %}' + "There are {{ num_comments }} comments{% endblocktranslate %}" ) rendered = t.render(Context()) - self.assertEqual(rendered, 'Andere: Es gibt 5 Kommentare') + self.assertEqual(rendered, "Andere: Es gibt 5 Kommentare") # Using trimmed t = self.get_template( - '{% load i18n %}{% blocktranslate trimmed %}\n\nThere\n\t are 5 ' - '\n\n comments\n{% endblocktranslate %}' + "{% load i18n %}{% blocktranslate trimmed %}\n\nThere\n\t are 5 " + "\n\n comments\n{% endblocktranslate %}" ) rendered = t.render(Context()) - self.assertEqual(rendered, 'There are 5 comments') + self.assertEqual(rendered, "There are 5 comments") t = self.get_template( '{% load i18n %}{% blocktranslate with num_comments=5 context "comment count" trimmed %}\n\n' - 'There are \t\n \t {{ num_comments }} comments\n\n{% endblocktranslate %}' + "There are \t\n \t {{ num_comments }} comments\n\n{% endblocktranslate %}" ) rendered = t.render(Context()) - self.assertEqual(rendered, 'Es gibt 5 Kommentare') + self.assertEqual(rendered, "Es gibt 5 Kommentare") t = self.get_template( '{% load i18n %}{% blocktranslate context "other super search" count number=2 trimmed %}\n' - '{{ number }} super \n result{% plural %}{{ number }} super results{% endblocktranslate %}' + "{{ number }} super \n result{% plural %}{{ number }} super results{% endblocktranslate %}" ) rendered = t.render(Context()) - self.assertEqual(rendered, '2 andere Super-Ergebnisse') + self.assertEqual(rendered, "2 andere Super-Ergebnisse") # Misuses msg = "Unknown argument for 'blocktranslate' tag: %r." @@ -448,55 +611,61 @@ class TranslationBlockTranslateTagTests(SimpleTestCase): self.get_template( '{% load i18n %}{% blocktranslate context with month="May" %}{{ month }}{% endblocktranslate %}' ) - msg = '"context" in %r tag expected exactly one argument.' % 'blocktranslate' + msg = ( + '"context" in %r tag expected exactly one argument.' % "blocktranslate" + ) with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.get_template('{% load i18n %}{% blocktranslate context %}{% endblocktranslate %}') + self.get_template( + "{% load i18n %}{% blocktranslate context %}{% endblocktranslate %}" + ) with self.assertRaisesMessage(TemplateSyntaxError, msg): self.get_template( - '{% load i18n %}{% blocktranslate count number=2 context %}' - '{{ number }} super result{% plural %}{{ number }}' - ' super results{% endblocktranslate %}' + "{% load i18n %}{% blocktranslate count number=2 context %}" + "{{ number }} super result{% plural %}{{ number }}" + " super results{% endblocktranslate %}" ) - @override_settings(LOCALE_PATHS=[os.path.join(here, 'other', 'locale')]) + @override_settings(LOCALE_PATHS=[os.path.join(here, "other", "locale")]) def test_bad_placeholder_1(self): """ Error in translation file should not crash template rendering (#16516). (%(person)s is translated as %(personne)s in fr.po). """ - with translation.override('fr'): - t = Template('{% load i18n %}{% blocktranslate %}My name is {{ person }}.{% endblocktranslate %}') - rendered = t.render(Context({'person': 'James'})) - self.assertEqual(rendered, 'My name is James.') + with translation.override("fr"): + t = Template( + "{% load i18n %}{% blocktranslate %}My name is {{ person }}.{% endblocktranslate %}" + ) + rendered = t.render(Context({"person": "James"})) + self.assertEqual(rendered, "My name is James.") - @override_settings(LOCALE_PATHS=[os.path.join(here, 'other', 'locale')]) + @override_settings(LOCALE_PATHS=[os.path.join(here, "other", "locale")]) def test_bad_placeholder_2(self): """ Error in translation file should not crash template rendering (#18393). (%(person) misses a 's' in fr.po, causing the string formatting to fail) . """ - with translation.override('fr'): - t = Template('{% load i18n %}{% blocktranslate %}My other name is {{ person }}.{% endblocktranslate %}') - rendered = t.render(Context({'person': 'James'})) - self.assertEqual(rendered, 'My other name is James.') + with translation.override("fr"): + t = Template( + "{% load i18n %}{% blocktranslate %}My other name is {{ person }}.{% endblocktranslate %}" + ) + rendered = t.render(Context({"person": "James"})) + self.assertEqual(rendered, "My other name is James.") class TranslationBlockTransnTagTests(TranslationBlockTranslateTagTests): - tag_name = 'blocktrans' + tag_name = "blocktrans" class MultipleLocaleActivationBlockTranslateTests(MultipleLocaleActivationTestCase): - tag_name = 'blocktranslate' + tag_name = "blocktranslate" def get_template(self, template_string): return Template( template_string.replace( - '{{% blocktranslate ', - '{{% {}'.format(self.tag_name) + "{{% blocktranslate ", "{{% {}".format(self.tag_name) ).replace( - '{{% endblocktranslate %}}', - '{{% end{} %}}'.format(self.tag_name) + "{{% endblocktranslate %}}", "{{% end{} %}}".format(self.tag_name) ) ) @@ -505,46 +674,54 @@ class MultipleLocaleActivationBlockTranslateTests(MultipleLocaleActivationTestCa Simple baseline behavior with one locale for all the supported i18n constructs. """ - with translation.override('fr'): + with translation.override("fr"): self.assertEqual( - self.get_template("{% load i18n %}{% blocktranslate %}Yes{% endblocktranslate %}").render(Context({})), - 'Oui' + self.get_template( + "{% load i18n %}{% blocktranslate %}Yes{% endblocktranslate %}" + ).render(Context({})), + "Oui", ) def test_multiple_locale_btrans(self): - with translation.override('de'): - t = self.get_template("{% load i18n %}{% blocktranslate %}No{% endblocktranslate %}") - with translation.override(self._old_language), translation.override('nl'): - self.assertEqual(t.render(Context({})), 'Nee') + with translation.override("de"): + t = self.get_template( + "{% load i18n %}{% blocktranslate %}No{% endblocktranslate %}" + ) + with translation.override(self._old_language), translation.override("nl"): + self.assertEqual(t.render(Context({})), "Nee") def test_multiple_locale_deactivate_btrans(self): - with translation.override('de', deactivate=True): - t = self.get_template("{% load i18n %}{% blocktranslate %}No{% endblocktranslate %}") - with translation.override('nl'): - self.assertEqual(t.render(Context({})), 'Nee') + with translation.override("de", deactivate=True): + t = self.get_template( + "{% load i18n %}{% blocktranslate %}No{% endblocktranslate %}" + ) + with translation.override("nl"): + self.assertEqual(t.render(Context({})), "Nee") def test_multiple_locale_direct_switch_btrans(self): - with translation.override('de'): - t = self.get_template("{% load i18n %}{% blocktranslate %}No{% endblocktranslate %}") - with translation.override('nl'): - self.assertEqual(t.render(Context({})), 'Nee') + with translation.override("de"): + t = self.get_template( + "{% load i18n %}{% blocktranslate %}No{% endblocktranslate %}" + ) + with translation.override("nl"): + self.assertEqual(t.render(Context({})), "Nee") -class MultipleLocaleActivationBlockTransTests(MultipleLocaleActivationBlockTranslateTests): - tag_name = 'blocktrans' +class MultipleLocaleActivationBlockTransTests( + MultipleLocaleActivationBlockTranslateTests +): + tag_name = "blocktrans" class MiscTests(SimpleTestCase): - tag_name = 'blocktranslate' + tag_name = "blocktranslate" def get_template(self, template_string): return Template( template_string.replace( - '{{% blocktranslate ', - '{{% {}'.format(self.tag_name) + "{{% blocktranslate ", "{{% {}".format(self.tag_name) ).replace( - '{{% endblocktranslate %}}', - '{{% end{} %}}'.format(self.tag_name) + "{{% endblocktranslate %}}", "{{% end{} %}}".format(self.tag_name) ) ) @@ -558,10 +735,18 @@ class MiscTests(SimpleTestCase): "{{ percent }}% represents {{ num }} object{% plural %}" "{{ percent }}% represents {{ num }} objects{% endblocktranslate %}" ) - with translation.override('de'): - self.assertEqual(t_sing.render(Context({'percent': 42})), 'Das Ergebnis war 42%') - self.assertEqual(t_plur.render(Context({'percent': 42, 'num': 1})), '42% stellt 1 Objekt dar') - self.assertEqual(t_plur.render(Context({'percent': 42, 'num': 4})), '42% stellt 4 Objekte dar') + with translation.override("de"): + self.assertEqual( + t_sing.render(Context({"percent": 42})), "Das Ergebnis war 42%" + ) + self.assertEqual( + t_plur.render(Context({"percent": 42, "num": 1})), + "42% stellt 1 Objekt dar", + ) + self.assertEqual( + t_plur.render(Context({"percent": 42, "num": 4})), + "42% stellt 4 Objekte dar", + ) @override_settings(LOCALE_PATHS=extended_locale_paths) def test_percent_formatting_in_blocktranslate(self): @@ -577,26 +762,38 @@ class MiscTests(SimpleTestCase): "%(percent)s% represents {{ num }} object{% plural %}" "%(percent)s% represents {{ num }} objects{% endblocktranslate %}" ) - with translation.override('de'): + with translation.override("de"): # Strings won't get translated as they don't match after escaping % - self.assertEqual(t_sing.render(Context({'num_comments': 42})), 'There are %(num_comments)s comments') - self.assertEqual(t_plur.render(Context({'percent': 42, 'num': 1})), '%(percent)s% represents 1 object') - self.assertEqual(t_plur.render(Context({'percent': 42, 'num': 4})), '%(percent)s% represents 4 objects') + self.assertEqual( + t_sing.render(Context({"num_comments": 42})), + "There are %(num_comments)s comments", + ) + self.assertEqual( + t_plur.render(Context({"percent": 42, "num": 1})), + "%(percent)s% represents 1 object", + ) + self.assertEqual( + t_plur.render(Context({"percent": 42, "num": 4})), + "%(percent)s% represents 4 objects", + ) class MiscBlockTranslationTests(MiscTests): - tag_name = 'blocktrans' + tag_name = "blocktrans" class BlockTranslateNodeTests(SimpleTestCase): def test_repr(self): - block_translate_node = BlockTranslateNode(extra_context={}, singular=[ - Token(TokenType.TEXT, 'content'), - Token(TokenType.VAR, 'variable'), - ]) + block_translate_node = BlockTranslateNode( + extra_context={}, + singular=[ + Token(TokenType.TEXT, "content"), + Token(TokenType.VAR, "variable"), + ], + ) self.assertEqual( repr(block_translate_node), - '<BlockTranslateNode: extra_context={} ' + "<BlockTranslateNode: extra_context={} " 'singular=[<Text token: "content...">, <Var token: "variable...">] ' - 'plural=None>', + "plural=None>", ) diff --git a/tests/template_tests/syntax_tests/i18n/test_filters.py b/tests/template_tests/syntax_tests/i18n/test_filters.py index cf8e4573c3..c78b8aca5f 100644 --- a/tests/template_tests/syntax_tests/i18n/test_filters.py +++ b/tests/template_tests/syntax_tests/i18n/test_filters.py @@ -6,42 +6,56 @@ from ...utils import setup class I18nFiltersTests(SimpleTestCase): libraries = { - 'custom': 'template_tests.templatetags.custom', - 'i18n': 'django.templatetags.i18n', + "custom": "template_tests.templatetags.custom", + "i18n": "django.templatetags.i18n", } - @setup({'i18n32': '{% load i18n %}{{ "hu"|language_name }} ' - '{{ "hu"|language_name_local }} {{ "hu"|language_bidi }} ' - '{{ "hu"|language_name_translated }}'}) + @setup( + { + "i18n32": '{% load i18n %}{{ "hu"|language_name }} ' + '{{ "hu"|language_name_local }} {{ "hu"|language_bidi }} ' + '{{ "hu"|language_name_translated }}' + } + ) def test_i18n32(self): - output = self.engine.render_to_string('i18n32') - self.assertEqual(output, 'Hungarian Magyar False Hungarian') + output = self.engine.render_to_string("i18n32") + self.assertEqual(output, "Hungarian Magyar False Hungarian") - with translation.override('cs'): - output = self.engine.render_to_string('i18n32') - self.assertEqual(output, 'Hungarian Magyar False maďarsky') + with translation.override("cs"): + output = self.engine.render_to_string("i18n32") + self.assertEqual(output, "Hungarian Magyar False maďarsky") - @setup({'i18n33': '{% load i18n %}' - '{{ langcode|language_name }} {{ langcode|language_name_local }} ' - '{{ langcode|language_bidi }} {{ langcode|language_name_translated }}'}) + @setup( + { + "i18n33": "{% load i18n %}" + "{{ langcode|language_name }} {{ langcode|language_name_local }} " + "{{ langcode|language_bidi }} {{ langcode|language_name_translated }}" + } + ) def test_i18n33(self): - output = self.engine.render_to_string('i18n33', {'langcode': 'nl'}) - self.assertEqual(output, 'Dutch Nederlands False Dutch') + output = self.engine.render_to_string("i18n33", {"langcode": "nl"}) + self.assertEqual(output, "Dutch Nederlands False Dutch") - with translation.override('cs'): - output = self.engine.render_to_string('i18n33', {'langcode': 'nl'}) - self.assertEqual(output, 'Dutch Nederlands False nizozemsky') + with translation.override("cs"): + output = self.engine.render_to_string("i18n33", {"langcode": "nl"}) + self.assertEqual(output, "Dutch Nederlands False nizozemsky") - @setup({'i18n38_2': '{% load i18n custom %}' - '{% get_language_info_list for langcodes|noop:"x y" as langs %}' - '{% for l in langs %}{{ l.code }}: {{ l.name }}/' - '{{ l.name_local }}/{{ l.name_translated }} ' - 'bidi={{ l.bidi }}; {% endfor %}'}) + @setup( + { + "i18n38_2": "{% load i18n custom %}" + '{% get_language_info_list for langcodes|noop:"x y" as langs %}' + "{% for l in langs %}{{ l.code }}: {{ l.name }}/" + "{{ l.name_local }}/{{ l.name_translated }} " + "bidi={{ l.bidi }}; {% endfor %}" + } + ) def test_i18n38_2(self): - with translation.override('cs'): - output = self.engine.render_to_string('i18n38_2', {'langcodes': ['it', 'fr']}) + with translation.override("cs"): + output = self.engine.render_to_string( + "i18n38_2", {"langcodes": ["it", "fr"]} + ) self.assertEqual( output, - 'it: Italian/italiano/italsky bidi=False; ' - 'fr: French/français/francouzsky bidi=False; ' + "it: Italian/italiano/italsky bidi=False; " + "fr: French/français/francouzsky bidi=False; ", ) diff --git a/tests/template_tests/syntax_tests/i18n/test_get_available_languages.py b/tests/template_tests/syntax_tests/i18n/test_get_available_languages.py index 5ac97a4f79..dce5a4de66 100644 --- a/tests/template_tests/syntax_tests/i18n/test_get_available_languages.py +++ b/tests/template_tests/syntax_tests/i18n/test_get_available_languages.py @@ -5,17 +5,21 @@ from ...utils import setup class GetAvailableLanguagesTagTests(SimpleTestCase): - libraries = {'i18n': 'django.templatetags.i18n'} + libraries = {"i18n": "django.templatetags.i18n"} - @setup({'i18n12': '{% load i18n %}' - '{% get_available_languages as langs %}{% for lang in langs %}' - '{% if lang.0 == "de" %}{{ lang.0 }}{% endif %}{% endfor %}'}) + @setup( + { + "i18n12": "{% load i18n %}" + "{% get_available_languages as langs %}{% for lang in langs %}" + '{% if lang.0 == "de" %}{{ lang.0 }}{% endif %}{% endfor %}' + } + ) def test_i18n12(self): - output = self.engine.render_to_string('i18n12') - self.assertEqual(output, 'de') + output = self.engine.render_to_string("i18n12") + self.assertEqual(output, "de") - @setup({'syntax_i18n': '{% load i18n %}{% get_available_languages a langs %}'}) + @setup({"syntax_i18n": "{% load i18n %}{% get_available_languages a langs %}"}) def test_no_as_var(self): msg = "'get_available_languages' requires 'as variable' (got ['get_available_languages', 'a', 'langs'])" with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('syntax_i18n') + self.engine.render_to_string("syntax_i18n") diff --git a/tests/template_tests/syntax_tests/i18n/test_get_current_language.py b/tests/template_tests/syntax_tests/i18n/test_get_current_language.py index f168b74f8e..8ed7f742c2 100644 --- a/tests/template_tests/syntax_tests/i18n/test_get_current_language.py +++ b/tests/template_tests/syntax_tests/i18n/test_get_current_language.py @@ -5,10 +5,10 @@ from django.test import SimpleTestCase class I18nGetCurrentLanguageTagTests(SimpleTestCase): - libraries = {'i18n': 'django.templatetags.i18n'} + libraries = {"i18n": "django.templatetags.i18n"} - @setup({'template': '{% load i18n %} {% get_current_language %}'}) + @setup({"template": "{% load i18n %} {% get_current_language %}"}) def test_no_as_var(self): msg = "'get_current_language' requires 'as variable' (got ['get_current_language'])" with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('template') + self.engine.render_to_string("template") diff --git a/tests/template_tests/syntax_tests/i18n/test_get_current_language_bidi.py b/tests/template_tests/syntax_tests/i18n/test_get_current_language_bidi.py index 0ac408f78f..3f307471ae 100644 --- a/tests/template_tests/syntax_tests/i18n/test_get_current_language_bidi.py +++ b/tests/template_tests/syntax_tests/i18n/test_get_current_language_bidi.py @@ -5,10 +5,10 @@ from django.test import SimpleTestCase class I18nGetCurrentLanguageBidiTagTests(SimpleTestCase): - libraries = {'i18n': 'django.templatetags.i18n'} + libraries = {"i18n": "django.templatetags.i18n"} - @setup({'template': '{% load i18n %} {% get_current_language_bidi %}'}) + @setup({"template": "{% load i18n %} {% get_current_language_bidi %}"}) def test_no_as_var(self): msg = "'get_current_language_bidi' requires 'as variable' (got ['get_current_language_bidi'])" with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('template') + self.engine.render_to_string("template") diff --git a/tests/template_tests/syntax_tests/i18n/test_get_language_info.py b/tests/template_tests/syntax_tests/i18n/test_get_language_info.py index 4ae8186af5..cf05df13db 100644 --- a/tests/template_tests/syntax_tests/i18n/test_get_language_info.py +++ b/tests/template_tests/syntax_tests/i18n/test_get_language_info.py @@ -7,37 +7,49 @@ from ...utils import setup class I18nGetLanguageInfoTagTests(SimpleTestCase): libraries = { - 'custom': 'template_tests.templatetags.custom', - 'i18n': 'django.templatetags.i18n', + "custom": "template_tests.templatetags.custom", + "i18n": "django.templatetags.i18n", } # retrieving language information - @setup({'i18n28_2': '{% load i18n %}' - '{% get_language_info for "de" as l %}' - '{{ l.code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}'}) + @setup( + { + "i18n28_2": "{% load i18n %}" + '{% get_language_info for "de" as l %}' + "{{ l.code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}" + } + ) def test_i18n28_2(self): - output = self.engine.render_to_string('i18n28_2') - self.assertEqual(output, 'de: German/Deutsch bidi=False') + output = self.engine.render_to_string("i18n28_2") + self.assertEqual(output, "de: German/Deutsch bidi=False") - @setup({'i18n29': '{% load i18n %}' - '{% get_language_info for LANGUAGE_CODE as l %}' - '{{ l.code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}'}) + @setup( + { + "i18n29": "{% load i18n %}" + "{% get_language_info for LANGUAGE_CODE as l %}" + "{{ l.code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}" + } + ) def test_i18n29(self): - output = self.engine.render_to_string('i18n29', {'LANGUAGE_CODE': 'fi'}) - self.assertEqual(output, 'fi: Finnish/suomi bidi=False') + output = self.engine.render_to_string("i18n29", {"LANGUAGE_CODE": "fi"}) + self.assertEqual(output, "fi: Finnish/suomi bidi=False") # Test whitespace in filter arguments - @setup({'i18n38': '{% load i18n custom %}' - '{% get_language_info for "de"|noop:"x y" as l %}' - '{{ l.code }}: {{ l.name }}/{{ l.name_local }}/' - '{{ l.name_translated }} bidi={{ l.bidi }}'}) + @setup( + { + "i18n38": "{% load i18n custom %}" + '{% get_language_info for "de"|noop:"x y" as l %}' + "{{ l.code }}: {{ l.name }}/{{ l.name_local }}/" + "{{ l.name_translated }} bidi={{ l.bidi }}" + } + ) def test_i18n38(self): - with translation.override('cs'): - output = self.engine.render_to_string('i18n38') - self.assertEqual(output, 'de: German/Deutsch/německy bidi=False') + with translation.override("cs"): + output = self.engine.render_to_string("i18n38") + self.assertEqual(output, "de: German/Deutsch/německy bidi=False") - @setup({'template': '{% load i18n %}{% get_language_info %}'}) + @setup({"template": "{% load i18n %}{% get_language_info %}"}) def test_no_for_as(self): msg = "'get_language_info' requires 'for string as variable' (got [])" with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('template') + self.engine.render_to_string("template") diff --git a/tests/template_tests/syntax_tests/i18n/test_get_language_info_list.py b/tests/template_tests/syntax_tests/i18n/test_get_language_info_list.py index c2c7f8b9cb..93038daa2f 100644 --- a/tests/template_tests/syntax_tests/i18n/test_get_language_info_list.py +++ b/tests/template_tests/syntax_tests/i18n/test_get_language_info_list.py @@ -7,46 +7,64 @@ from ...utils import setup class GetLanguageInfoListTests(SimpleTestCase): libraries = { - 'custom': 'template_tests.templatetags.custom', - 'i18n': 'django.templatetags.i18n', + "custom": "template_tests.templatetags.custom", + "i18n": "django.templatetags.i18n", } - @setup({'i18n30': '{% load i18n %}' - '{% get_language_info_list for langcodes as langs %}' - '{% for l in langs %}{{ l.code }}: {{ l.name }}/' - '{{ l.name_local }} bidi={{ l.bidi }}; {% endfor %}'}) + @setup( + { + "i18n30": "{% load i18n %}" + "{% get_language_info_list for langcodes as langs %}" + "{% for l in langs %}{{ l.code }}: {{ l.name }}/" + "{{ l.name_local }} bidi={{ l.bidi }}; {% endfor %}" + } + ) def test_i18n30(self): - output = self.engine.render_to_string('i18n30', {'langcodes': ['it', 'no']}) - self.assertEqual(output, 'it: Italian/italiano bidi=False; no: Norwegian/norsk bidi=False; ') + output = self.engine.render_to_string("i18n30", {"langcodes": ["it", "no"]}) + self.assertEqual( + output, "it: Italian/italiano bidi=False; no: Norwegian/norsk bidi=False; " + ) - @setup({'i18n31': '{% load i18n %}' - '{% get_language_info_list for langcodes as langs %}' - '{% for l in langs %}{{ l.code }}: {{ l.name }}/' - '{{ l.name_local }} bidi={{ l.bidi }}; {% endfor %}'}) + @setup( + { + "i18n31": "{% load i18n %}" + "{% get_language_info_list for langcodes as langs %}" + "{% for l in langs %}{{ l.code }}: {{ l.name }}/" + "{{ l.name_local }} bidi={{ l.bidi }}; {% endfor %}" + } + ) def test_i18n31(self): - output = self.engine.render_to_string('i18n31', {'langcodes': (('sl', 'Slovenian'), ('fa', 'Persian'))}) + output = self.engine.render_to_string( + "i18n31", {"langcodes": (("sl", "Slovenian"), ("fa", "Persian"))} + ) self.assertEqual( output, - 'sl: Slovenian/Sloven\u0161\u010dina bidi=False; ' - 'fa: Persian/\u0641\u0627\u0631\u0633\u06cc bidi=True; ' + "sl: Slovenian/Sloven\u0161\u010dina bidi=False; " + "fa: Persian/\u0641\u0627\u0631\u0633\u06cc bidi=True; ", ) - @setup({'i18n38_2': '{% load i18n custom %}' - '{% get_language_info_list for langcodes|noop:"x y" as langs %}' - '{% for l in langs %}{{ l.code }}: {{ l.name }}/' - '{{ l.name_local }}/{{ l.name_translated }} ' - 'bidi={{ l.bidi }}; {% endfor %}'}) + @setup( + { + "i18n38_2": "{% load i18n custom %}" + '{% get_language_info_list for langcodes|noop:"x y" as langs %}' + "{% for l in langs %}{{ l.code }}: {{ l.name }}/" + "{{ l.name_local }}/{{ l.name_translated }} " + "bidi={{ l.bidi }}; {% endfor %}" + } + ) def test_i18n38_2(self): - with translation.override('cs'): - output = self.engine.render_to_string('i18n38_2', {'langcodes': ['it', 'fr']}) + with translation.override("cs"): + output = self.engine.render_to_string( + "i18n38_2", {"langcodes": ["it", "fr"]} + ) self.assertEqual( output, - 'it: Italian/italiano/italsky bidi=False; ' - 'fr: French/français/francouzsky bidi=False; ' + "it: Italian/italiano/italsky bidi=False; " + "fr: French/français/francouzsky bidi=False; ", ) - @setup({'i18n_syntax': '{% load i18n %} {% get_language_info_list error %}'}) + @setup({"i18n_syntax": "{% load i18n %} {% get_language_info_list error %}"}) def test_no_for_as(self): msg = "'get_language_info_list' requires 'for sequence as variable' (got ['error'])" with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('i18n_syntax') + self.engine.render_to_string("i18n_syntax") diff --git a/tests/template_tests/syntax_tests/i18n/test_language.py b/tests/template_tests/syntax_tests/i18n/test_language.py index 47797befae..57a3a53866 100644 --- a/tests/template_tests/syntax_tests/i18n/test_language.py +++ b/tests/template_tests/syntax_tests/i18n/test_language.py @@ -5,9 +5,11 @@ from django.test import SimpleTestCase class I18nLanguageTagTests(SimpleTestCase): - libraries = {'i18n': 'django.templatetags.i18n'} + libraries = {"i18n": "django.templatetags.i18n"} - @setup({'i18n_language': '{% load i18n %} {% language %} {% endlanguage %}'}) + @setup({"i18n_language": "{% load i18n %} {% language %} {% endlanguage %}"}) def test_no_arg(self): - with self.assertRaisesMessage(TemplateSyntaxError, "'language' takes one argument (language)"): - self.engine.render_to_string('i18n_language') + with self.assertRaisesMessage( + TemplateSyntaxError, "'language' takes one argument (language)" + ): + self.engine.render_to_string("i18n_language") diff --git a/tests/template_tests/syntax_tests/i18n/test_translate.py b/tests/template_tests/syntax_tests/i18n/test_translate.py index 55fdb92f7a..932b47a373 100644 --- a/tests/template_tests/syntax_tests/i18n/test_translate.py +++ b/tests/template_tests/syntax_tests/i18n/test_translate.py @@ -16,14 +16,16 @@ from .base import MultipleLocaleActivationTestCase, extended_locale_paths def setup(templates, *args, **kwargs): translate_setup = base_setup(templates, *args, **kwargs) - trans_setup = base_setup({ - name: template.replace('{% translate ', '{% trans ') - for name, template in templates.items() - }) + trans_setup = base_setup( + { + name: template.replace("{% translate ", "{% trans ") + for name, template in templates.items() + } + ) tags = { - 'trans': trans_setup, - 'translate': translate_setup, + "trans": trans_setup, + "translate": translate_setup, } def decorator(func): @@ -31,143 +33,162 @@ def setup(templates, *args, **kwargs): def inner(self, *args): signature = inspect.signature(func) for tag_name, setup_func in tags.items(): - if 'tag_name' in signature.parameters: + if "tag_name" in signature.parameters: setup_func(partial(func, tag_name=tag_name))(self) else: setup_func(func)(self) + return inner + return decorator class I18nTransTagTests(SimpleTestCase): - libraries = {'i18n': 'django.templatetags.i18n'} + libraries = {"i18n": "django.templatetags.i18n"} - @setup({'i18n01': '{% load i18n %}{% translate \'xxxyyyxxx\' %}'}) + @setup({"i18n01": "{% load i18n %}{% translate 'xxxyyyxxx' %}"}) def test_i18n01(self): """simple translation of a string delimited by '.""" - output = self.engine.render_to_string('i18n01') - self.assertEqual(output, 'xxxyyyxxx') + output = self.engine.render_to_string("i18n01") + self.assertEqual(output, "xxxyyyxxx") - @setup({'i18n02': '{% load i18n %}{% translate "xxxyyyxxx" %}'}) + @setup({"i18n02": '{% load i18n %}{% translate "xxxyyyxxx" %}'}) def test_i18n02(self): """simple translation of a string delimited by ".""" - output = self.engine.render_to_string('i18n02') - self.assertEqual(output, 'xxxyyyxxx') + output = self.engine.render_to_string("i18n02") + self.assertEqual(output, "xxxyyyxxx") - @setup({'i18n06': '{% load i18n %}{% translate "Page not found" %}'}) + @setup({"i18n06": '{% load i18n %}{% translate "Page not found" %}'}) def test_i18n06(self): """simple translation of a string to German""" - with translation.override('de'): - output = self.engine.render_to_string('i18n06') - self.assertEqual(output, 'Seite nicht gefunden') + with translation.override("de"): + output = self.engine.render_to_string("i18n06") + self.assertEqual(output, "Seite nicht gefunden") - @setup({'i18n09': '{% load i18n %}{% translate "Page not found" noop %}'}) + @setup({"i18n09": '{% load i18n %}{% translate "Page not found" noop %}'}) def test_i18n09(self): """simple non-translation (only marking) of a string to German""" - with translation.override('de'): - output = self.engine.render_to_string('i18n09') - self.assertEqual(output, 'Page not found') + with translation.override("de"): + output = self.engine.render_to_string("i18n09") + self.assertEqual(output, "Page not found") - @setup({'i18n20': '{% load i18n %}{% translate andrew %}'}) + @setup({"i18n20": "{% load i18n %}{% translate andrew %}"}) def test_i18n20(self): - output = self.engine.render_to_string('i18n20', {'andrew': 'a & b'}) - self.assertEqual(output, 'a & b') + output = self.engine.render_to_string("i18n20", {"andrew": "a & b"}) + self.assertEqual(output, "a & b") - @setup({'i18n22': '{% load i18n %}{% translate andrew %}'}) + @setup({"i18n22": "{% load i18n %}{% translate andrew %}"}) def test_i18n22(self): - output = self.engine.render_to_string('i18n22', {'andrew': mark_safe('a & b')}) - self.assertEqual(output, 'a & b') + output = self.engine.render_to_string("i18n22", {"andrew": mark_safe("a & b")}) + self.assertEqual(output, "a & b") - @setup({'i18n23': '{% load i18n %}{% translate "Page not found"|capfirst|slice:"6:" %}'}) + @setup( + { + "i18n23": '{% load i18n %}{% translate "Page not found"|capfirst|slice:"6:" %}' + } + ) def test_i18n23(self): """Using filters with the {% translate %} tag (#5972).""" - with translation.override('de'): - output = self.engine.render_to_string('i18n23') - self.assertEqual(output, 'nicht gefunden') + with translation.override("de"): + output = self.engine.render_to_string("i18n23") + self.assertEqual(output, "nicht gefunden") - @setup({'i18n24': '{% load i18n %}{% translate \'Page not found\'|upper %}'}) + @setup({"i18n24": "{% load i18n %}{% translate 'Page not found'|upper %}"}) def test_i18n24(self): - with translation.override('de'): - output = self.engine.render_to_string('i18n24') - self.assertEqual(output, 'SEITE NICHT GEFUNDEN') + with translation.override("de"): + output = self.engine.render_to_string("i18n24") + self.assertEqual(output, "SEITE NICHT GEFUNDEN") - @setup({'i18n25': '{% load i18n %}{% translate somevar|upper %}'}) + @setup({"i18n25": "{% load i18n %}{% translate somevar|upper %}"}) def test_i18n25(self): - with translation.override('de'): - output = self.engine.render_to_string('i18n25', {'somevar': 'Page not found'}) - self.assertEqual(output, 'SEITE NICHT GEFUNDEN') + with translation.override("de"): + output = self.engine.render_to_string( + "i18n25", {"somevar": "Page not found"} + ) + self.assertEqual(output, "SEITE NICHT GEFUNDEN") # trans tag with as var - @setup({'i18n35': '{% load i18n %}{% translate "Page not found" as page_not_found %}{{ page_not_found }}'}) + @setup( + { + "i18n35": '{% load i18n %}{% translate "Page not found" as page_not_found %}{{ page_not_found }}' + } + ) def test_i18n35(self): - with translation.override('de'): - output = self.engine.render_to_string('i18n35') - self.assertEqual(output, 'Seite nicht gefunden') + with translation.override("de"): + output = self.engine.render_to_string("i18n35") + self.assertEqual(output, "Seite nicht gefunden") - @setup({'i18n36': '{% load i18n %}' - '{% translate "Page not found" noop as page_not_found %}{{ page_not_found }}'}) + @setup( + { + "i18n36": "{% load i18n %}" + '{% translate "Page not found" noop as page_not_found %}{{ page_not_found }}' + } + ) def test_i18n36(self): - with translation.override('de'): - output = self.engine.render_to_string('i18n36') - self.assertEqual(output, 'Page not found') + with translation.override("de"): + output = self.engine.render_to_string("i18n36") + self.assertEqual(output, "Page not found") - @setup({'template': '{% load i18n %}{% translate %}A}'}) + @setup({"template": "{% load i18n %}{% translate %}A}"}) def test_syntax_error_no_arguments(self, tag_name): msg = "'{}' takes at least one argument".format(tag_name) with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('template') + self.engine.render_to_string("template") - @setup({'template': '{% load i18n %}{% translate "Yes" badoption %}'}) + @setup({"template": '{% load i18n %}{% translate "Yes" badoption %}'}) def test_syntax_error_bad_option(self, tag_name): msg = "Unknown argument for '{}' tag: 'badoption'".format(tag_name) with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('template') + self.engine.render_to_string("template") - @setup({'template': '{% load i18n %}{% translate "Yes" as %}'}) + @setup({"template": '{% load i18n %}{% translate "Yes" as %}'}) def test_syntax_error_missing_assignment(self, tag_name): msg = "No argument provided to the '{}' tag for the as option.".format(tag_name) with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('template') + self.engine.render_to_string("template") - @setup({'template': '{% load i18n %}{% translate "Yes" as var context %}'}) + @setup({"template": '{% load i18n %}{% translate "Yes" as var context %}'}) def test_syntax_error_missing_context(self, tag_name): - msg = "No argument provided to the '{}' tag for the context option.".format(tag_name) + msg = "No argument provided to the '{}' tag for the context option.".format( + tag_name + ) with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('template') + self.engine.render_to_string("template") - @setup({'template': '{% load i18n %}{% translate "Yes" context as var %}'}) + @setup({"template": '{% load i18n %}{% translate "Yes" context as var %}'}) def test_syntax_error_context_as(self, tag_name): - msg = "Invalid argument 'as' provided to the '{}' tag for the context option".format(tag_name) + msg = "Invalid argument 'as' provided to the '{}' tag for the context option".format( + tag_name + ) with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('template') + self.engine.render_to_string("template") - @setup({'template': '{% load i18n %}{% translate "Yes" context noop %}'}) + @setup({"template": '{% load i18n %}{% translate "Yes" context noop %}'}) def test_syntax_error_context_noop(self, tag_name): - msg = "Invalid argument 'noop' provided to the '{}' tag for the context option".format(tag_name) + msg = "Invalid argument 'noop' provided to the '{}' tag for the context option".format( + tag_name + ) with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('template') + self.engine.render_to_string("template") - @setup({'template': '{% load i18n %}{% translate "Yes" noop noop %}'}) + @setup({"template": '{% load i18n %}{% translate "Yes" noop noop %}'}) def test_syntax_error_duplicate_option(self): msg = "The 'noop' option was specified more than once." with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('template') + self.engine.render_to_string("template") - @setup({'template': '{% load i18n %}{% translate "%s" %}'}) + @setup({"template": '{% load i18n %}{% translate "%s" %}'}) def test_trans_tag_using_a_string_that_looks_like_str_fmt(self): - output = self.engine.render_to_string('template') - self.assertEqual(output, '%s') + output = self.engine.render_to_string("template") + self.assertEqual(output, "%s") class TranslationTransTagTests(SimpleTestCase): - tag_name = 'trans' + tag_name = "trans" def get_template(self, template_string): return Template( - template_string.replace( - '{{% translate ', - '{{% {}'.format(self.tag_name) - ) + template_string.replace("{{% translate ", "{{% {}".format(self.tag_name)) ) @override_settings(LOCALE_PATHS=extended_locale_paths) @@ -175,58 +196,71 @@ class TranslationTransTagTests(SimpleTestCase): """{% translate %} takes message contexts into account (#14806).""" trans_real._active = Local() trans_real._translations = {} - with translation.override('de'): + with translation.override("de"): # Nonexistent context... - t = self.get_template('{% load i18n %}{% translate "May" context "nonexistent" %}') + t = self.get_template( + '{% load i18n %}{% translate "May" context "nonexistent" %}' + ) rendered = t.render(Context()) - self.assertEqual(rendered, 'May') + self.assertEqual(rendered, "May") # Existing context... using a literal - t = self.get_template('{% load i18n %}{% translate "May" context "month name" %}') + t = self.get_template( + '{% load i18n %}{% translate "May" context "month name" %}' + ) rendered = t.render(Context()) - self.assertEqual(rendered, 'Mai') + self.assertEqual(rendered, "Mai") t = self.get_template('{% load i18n %}{% translate "May" context "verb" %}') rendered = t.render(Context()) - self.assertEqual(rendered, 'Kann') + self.assertEqual(rendered, "Kann") # Using a variable - t = self.get_template('{% load i18n %}{% translate "May" context message_context %}') - rendered = t.render(Context({'message_context': 'month name'})) - self.assertEqual(rendered, 'Mai') - t = self.get_template('{% load i18n %}{% translate "May" context message_context %}') - rendered = t.render(Context({'message_context': 'verb'})) - self.assertEqual(rendered, 'Kann') + t = self.get_template( + '{% load i18n %}{% translate "May" context message_context %}' + ) + rendered = t.render(Context({"message_context": "month name"})) + self.assertEqual(rendered, "Mai") + t = self.get_template( + '{% load i18n %}{% translate "May" context message_context %}' + ) + rendered = t.render(Context({"message_context": "verb"})) + self.assertEqual(rendered, "Kann") # Using a filter - t = self.get_template('{% load i18n %}{% translate "May" context message_context|lower %}') - rendered = t.render(Context({'message_context': 'MONTH NAME'})) - self.assertEqual(rendered, 'Mai') - t = self.get_template('{% load i18n %}{% translate "May" context message_context|lower %}') - rendered = t.render(Context({'message_context': 'VERB'})) - self.assertEqual(rendered, 'Kann') + t = self.get_template( + '{% load i18n %}{% translate "May" context message_context|lower %}' + ) + rendered = t.render(Context({"message_context": "MONTH NAME"})) + self.assertEqual(rendered, "Mai") + t = self.get_template( + '{% load i18n %}{% translate "May" context message_context|lower %}' + ) + rendered = t.render(Context({"message_context": "VERB"})) + self.assertEqual(rendered, "Kann") # Using 'as' - t = self.get_template('{% load i18n %}{% translate "May" context "month name" as var %}Value: {{ var }}') + t = self.get_template( + '{% load i18n %}{% translate "May" context "month name" as var %}Value: {{ var }}' + ) rendered = t.render(Context()) - self.assertEqual(rendered, 'Value: Mai') - t = self.get_template('{% load i18n %}{% translate "May" as var context "verb" %}Value: {{ var }}') + self.assertEqual(rendered, "Value: Mai") + t = self.get_template( + '{% load i18n %}{% translate "May" as var context "verb" %}Value: {{ var }}' + ) rendered = t.render(Context()) - self.assertEqual(rendered, 'Value: Kann') + self.assertEqual(rendered, "Value: Kann") class TranslationTranslateTagTests(TranslationTransTagTests): - tag_name = 'translate' + tag_name = "translate" class MultipleLocaleActivationTransTagTests(MultipleLocaleActivationTestCase): - tag_name = 'trans' + tag_name = "trans" def get_template(self, template_string): return Template( - template_string.replace( - '{{% translate ', - '{{% {}'.format(self.tag_name) - ) + template_string.replace("{{% translate ", "{{% {}".format(self.tag_name)) ) def test_single_locale_activation(self): @@ -234,36 +268,38 @@ class MultipleLocaleActivationTransTagTests(MultipleLocaleActivationTestCase): Simple baseline behavior with one locale for all the supported i18n constructs. """ - with translation.override('fr'): + with translation.override("fr"): self.assertEqual( - self.get_template("{% load i18n %}{% translate 'Yes' %}").render(Context({})), - 'Oui' + self.get_template("{% load i18n %}{% translate 'Yes' %}").render( + Context({}) + ), + "Oui", ) def test_multiple_locale_trans(self): - with translation.override('de'): + with translation.override("de"): t = self.get_template("{% load i18n %}{% translate 'No' %}") - with translation.override(self._old_language), translation.override('nl'): - self.assertEqual(t.render(Context({})), 'Nee') + with translation.override(self._old_language), translation.override("nl"): + self.assertEqual(t.render(Context({})), "Nee") def test_multiple_locale_deactivate_trans(self): - with translation.override('de', deactivate=True): + with translation.override("de", deactivate=True): t = self.get_template("{% load i18n %}{% translate 'No' %}") - with translation.override('nl'): - self.assertEqual(t.render(Context({})), 'Nee') + with translation.override("nl"): + self.assertEqual(t.render(Context({})), "Nee") def test_multiple_locale_direct_switch_trans(self): - with translation.override('de'): + with translation.override("de"): t = self.get_template("{% load i18n %}{% translate 'No' %}") - with translation.override('nl'): - self.assertEqual(t.render(Context({})), 'Nee') + with translation.override("nl"): + self.assertEqual(t.render(Context({})), "Nee") class MultipleLocaleActivationTranslateTagTests(MultipleLocaleActivationTransTagTests): - tag_name = 'translate' + tag_name = "translate" class LocalizeNodeTests(SimpleTestCase): def test_repr(self): node = LocalizeNode(nodelist=[], use_l10n=True) - self.assertEqual(repr(node), '<LocalizeNode>') + self.assertEqual(repr(node), "<LocalizeNode>") diff --git a/tests/template_tests/syntax_tests/i18n/test_underscore_syntax.py b/tests/template_tests/syntax_tests/i18n/test_underscore_syntax.py index 38d929e214..dfb035999c 100644 --- a/tests/template_tests/syntax_tests/i18n/test_underscore_syntax.py +++ b/tests/template_tests/syntax_tests/i18n/test_underscore_syntax.py @@ -7,101 +7,105 @@ from .base import MultipleLocaleActivationTestCase class MultipleLocaleActivationTests(MultipleLocaleActivationTestCase): - def test_single_locale_activation(self): """ Simple baseline behavior with one locale for all the supported i18n constructs. """ - with translation.override('fr'): - self.assertEqual(Template("{{ _('Yes') }}").render(Context({})), 'Oui') + with translation.override("fr"): + self.assertEqual(Template("{{ _('Yes') }}").render(Context({})), "Oui") # Literal marked up with _() in a filter expression def test_multiple_locale_filter(self): - with translation.override('de'): + with translation.override("de"): t = Template("{% load i18n %}{{ 0|yesno:_('yes,no,maybe') }}") - with translation.override(self._old_language), translation.override('nl'): - self.assertEqual(t.render(Context({})), 'nee') + with translation.override(self._old_language), translation.override("nl"): + self.assertEqual(t.render(Context({})), "nee") def test_multiple_locale_filter_deactivate(self): - with translation.override('de', deactivate=True): + with translation.override("de", deactivate=True): t = Template("{% load i18n %}{{ 0|yesno:_('yes,no,maybe') }}") - with translation.override('nl'): - self.assertEqual(t.render(Context({})), 'nee') + with translation.override("nl"): + self.assertEqual(t.render(Context({})), "nee") def test_multiple_locale_filter_direct_switch(self): - with translation.override('de'): + with translation.override("de"): t = Template("{% load i18n %}{{ 0|yesno:_('yes,no,maybe') }}") - with translation.override('nl'): - self.assertEqual(t.render(Context({})), 'nee') + with translation.override("nl"): + self.assertEqual(t.render(Context({})), "nee") # Literal marked up with _() def test_multiple_locale(self): - with translation.override('de'): + with translation.override("de"): t = Template("{{ _('No') }}") - with translation.override(self._old_language), translation.override('nl'): - self.assertEqual(t.render(Context({})), 'Nee') + with translation.override(self._old_language), translation.override("nl"): + self.assertEqual(t.render(Context({})), "Nee") def test_multiple_locale_deactivate(self): - with translation.override('de', deactivate=True): + with translation.override("de", deactivate=True): t = Template("{{ _('No') }}") - with translation.override('nl'): - self.assertEqual(t.render(Context({})), 'Nee') + with translation.override("nl"): + self.assertEqual(t.render(Context({})), "Nee") def test_multiple_locale_direct_switch(self): - with translation.override('de'): + with translation.override("de"): t = Template("{{ _('No') }}") - with translation.override('nl'): - self.assertEqual(t.render(Context({})), 'Nee') + with translation.override("nl"): + self.assertEqual(t.render(Context({})), "Nee") # Literal marked up with _(), loading the i18n template tag library def test_multiple_locale_loadi18n(self): - with translation.override('de'): + with translation.override("de"): t = Template("{% load i18n %}{{ _('No') }}") - with translation.override(self._old_language), translation.override('nl'): - self.assertEqual(t.render(Context({})), 'Nee') + with translation.override(self._old_language), translation.override("nl"): + self.assertEqual(t.render(Context({})), "Nee") def test_multiple_locale_loadi18n_deactivate(self): - with translation.override('de', deactivate=True): + with translation.override("de", deactivate=True): t = Template("{% load i18n %}{{ _('No') }}") - with translation.override('nl'): - self.assertEqual(t.render(Context({})), 'Nee') + with translation.override("nl"): + self.assertEqual(t.render(Context({})), "Nee") def test_multiple_locale_loadi18n_direct_switch(self): - with translation.override('de'): + with translation.override("de"): t = Template("{% load i18n %}{{ _('No') }}") - with translation.override('nl'): - self.assertEqual(t.render(Context({})), 'Nee') + with translation.override("nl"): + self.assertEqual(t.render(Context({})), "Nee") class I18nStringLiteralTests(SimpleTestCase): """translation of constant strings""" - libraries = {'i18n': 'django.templatetags.i18n'} - @setup({'i18n13': '{{ _("Password") }}'}) + libraries = {"i18n": "django.templatetags.i18n"} + + @setup({"i18n13": '{{ _("Password") }}'}) def test_i18n13(self): - with translation.override('de'): - output = self.engine.render_to_string('i18n13') - self.assertEqual(output, 'Passwort') + with translation.override("de"): + output = self.engine.render_to_string("i18n13") + self.assertEqual(output, "Passwort") - @setup({'i18n14': '{% cycle "foo" _("Password") _(\'Password\') as c %} {% cycle c %} {% cycle c %}'}) + @setup( + { + "i18n14": '{% cycle "foo" _("Password") _(\'Password\') as c %} {% cycle c %} {% cycle c %}' + } + ) def test_i18n14(self): - with translation.override('de'): - output = self.engine.render_to_string('i18n14') - self.assertEqual(output, 'foo Passwort Passwort') + with translation.override("de"): + output = self.engine.render_to_string("i18n14") + self.assertEqual(output, "foo Passwort Passwort") - @setup({'i18n15': '{{ absent|default:_("Password") }}'}) + @setup({"i18n15": '{{ absent|default:_("Password") }}'}) def test_i18n15(self): - with translation.override('de'): - output = self.engine.render_to_string('i18n15', {'absent': ''}) - self.assertEqual(output, 'Passwort') + with translation.override("de"): + output = self.engine.render_to_string("i18n15", {"absent": ""}) + self.assertEqual(output, "Passwort") - @setup({'i18n16': '{{ _("<") }}'}) + @setup({"i18n16": '{{ _("<") }}'}) def test_i18n16(self): - with translation.override('de'): - output = self.engine.render_to_string('i18n16') - self.assertEqual(output, '<') + with translation.override("de"): + output = self.engine.render_to_string("i18n16") + self.assertEqual(output, "<") diff --git a/tests/template_tests/syntax_tests/test_autoescape.py b/tests/template_tests/syntax_tests/test_autoescape.py index 13968537a6..d3c5cb02da 100644 --- a/tests/template_tests/syntax_tests/test_autoescape.py +++ b/tests/template_tests/syntax_tests/test_autoescape.py @@ -6,72 +6,89 @@ from ..utils import SafeClass, UnsafeClass, setup class AutoescapeTagTests(SimpleTestCase): - - @setup({'autoescape-tag01': '{% autoescape off %}hello{% endautoescape %}'}) + @setup({"autoescape-tag01": "{% autoescape off %}hello{% endautoescape %}"}) def test_autoescape_tag01(self): - output = self.engine.render_to_string('autoescape-tag01') - self.assertEqual(output, 'hello') + output = self.engine.render_to_string("autoescape-tag01") + self.assertEqual(output, "hello") - @setup({'autoescape-tag02': '{% autoescape off %}{{ first }}{% endautoescape %}'}) + @setup({"autoescape-tag02": "{% autoescape off %}{{ first }}{% endautoescape %}"}) def test_autoescape_tag02(self): - output = self.engine.render_to_string('autoescape-tag02', {'first': '<b>hello</b>'}) - self.assertEqual(output, '<b>hello</b>') + output = self.engine.render_to_string( + "autoescape-tag02", {"first": "<b>hello</b>"} + ) + self.assertEqual(output, "<b>hello</b>") - @setup({'autoescape-tag03': '{% autoescape on %}{{ first }}{% endautoescape %}'}) + @setup({"autoescape-tag03": "{% autoescape on %}{{ first }}{% endautoescape %}"}) def test_autoescape_tag03(self): - output = self.engine.render_to_string('autoescape-tag03', {'first': '<b>hello</b>'}) - self.assertEqual(output, '<b>hello</b>') + output = self.engine.render_to_string( + "autoescape-tag03", {"first": "<b>hello</b>"} + ) + self.assertEqual(output, "<b>hello</b>") # Autoescape disabling and enabling nest in a predictable way. - @setup({ - 'autoescape-tag04': - '{% autoescape off %}{{ first }} {% autoescape on %}{{ first }}{% endautoescape %}{% endautoescape %}' - }) + @setup( + { + "autoescape-tag04": "{% autoescape off %}{{ first }} {% autoescape on %}{{ first }}{% endautoescape %}{% endautoescape %}" + } + ) def test_autoescape_tag04(self): - output = self.engine.render_to_string('autoescape-tag04', {'first': '<a>'}) - self.assertEqual(output, '<a> <a>') + output = self.engine.render_to_string("autoescape-tag04", {"first": "<a>"}) + self.assertEqual(output, "<a> <a>") - @setup({'autoescape-tag05': '{% autoescape on %}{{ first }}{% endautoescape %}'}) + @setup({"autoescape-tag05": "{% autoescape on %}{{ first }}{% endautoescape %}"}) def test_autoescape_tag05(self): - output = self.engine.render_to_string('autoescape-tag05', {'first': '<b>first</b>'}) - self.assertEqual(output, '<b>first</b>') + output = self.engine.render_to_string( + "autoescape-tag05", {"first": "<b>first</b>"} + ) + self.assertEqual(output, "<b>first</b>") # Strings (ASCII or Unicode) already marked as "safe" are not # auto-escaped - @setup({'autoescape-tag06': '{{ first }}'}) + @setup({"autoescape-tag06": "{{ first }}"}) def test_autoescape_tag06(self): - output = self.engine.render_to_string('autoescape-tag06', {'first': mark_safe('<b>first</b>')}) - self.assertEqual(output, '<b>first</b>') + output = self.engine.render_to_string( + "autoescape-tag06", {"first": mark_safe("<b>first</b>")} + ) + self.assertEqual(output, "<b>first</b>") - @setup({'autoescape-tag07': '{% autoescape on %}{{ first }}{% endautoescape %}'}) + @setup({"autoescape-tag07": "{% autoescape on %}{{ first }}{% endautoescape %}"}) def test_autoescape_tag07(self): - output = self.engine.render_to_string('autoescape-tag07', {'first': mark_safe('<b>Apple</b>')}) - self.assertEqual(output, '<b>Apple</b>') + output = self.engine.render_to_string( + "autoescape-tag07", {"first": mark_safe("<b>Apple</b>")} + ) + self.assertEqual(output, "<b>Apple</b>") - @setup({ - 'autoescape-tag08': - r'{% autoescape on %}{{ var|default_if_none:" endquote\" hah" }}{% endautoescape %}' - }) + @setup( + { + "autoescape-tag08": r'{% autoescape on %}{{ var|default_if_none:" endquote\" hah" }}{% endautoescape %}' + } + ) def test_autoescape_tag08(self): """ Literal string arguments to filters, if used in the result, are safe. """ - output = self.engine.render_to_string('autoescape-tag08', {"var": None}) + output = self.engine.render_to_string("autoescape-tag08", {"var": None}) self.assertEqual(output, ' endquote" hah') # Objects which return safe strings as their __str__ method # won't get double-escaped. - @setup({'autoescape-tag09': r'{{ unsafe }}'}) + @setup({"autoescape-tag09": r"{{ unsafe }}"}) def test_autoescape_tag09(self): - output = self.engine.render_to_string('autoescape-tag09', {'unsafe': UnsafeClass()}) - self.assertEqual(output, 'you & me') + output = self.engine.render_to_string( + "autoescape-tag09", {"unsafe": UnsafeClass()} + ) + self.assertEqual(output, "you & me") - @setup({'autoescape-tag10': r'{{ safe }}'}) + @setup({"autoescape-tag10": r"{{ safe }}"}) def test_autoescape_tag10(self): - output = self.engine.render_to_string('autoescape-tag10', {'safe': SafeClass()}) - self.assertEqual(output, 'you > me') + output = self.engine.render_to_string("autoescape-tag10", {"safe": SafeClass()}) + self.assertEqual(output, "you > me") - @setup({'autoescape-filtertag01': '{{ first }}{% filter safe %}{{ first }} x<y{% endfilter %}'}) + @setup( + { + "autoescape-filtertag01": "{{ first }}{% filter safe %}{{ first }} x<y{% endfilter %}" + } + ) def test_autoescape_filtertag01(self): """ The "safe" and "escape" filters cannot work due to internal @@ -79,51 +96,69 @@ class AutoescapeTagTests(SimpleTestCase): tags can be used in those cases) """ with self.assertRaises(TemplateSyntaxError): - self.engine.render_to_string('autoescape-filtertag01', {'first': '<a>'}) + self.engine.render_to_string("autoescape-filtertag01", {"first": "<a>"}) # Arguments to filters are 'safe' and manipulate their input unescaped. - @setup({'autoescape-filters01': '{{ var|cut:"&" }}'}) + @setup({"autoescape-filters01": '{{ var|cut:"&" }}'}) def test_autoescape_filters01(self): - output = self.engine.render_to_string('autoescape-filters01', {'var': 'this & that'}) - self.assertEqual(output, 'this that') + output = self.engine.render_to_string( + "autoescape-filters01", {"var": "this & that"} + ) + self.assertEqual(output, "this that") - @setup({'autoescape-filters02': '{{ var|join:" & " }}'}) + @setup({"autoescape-filters02": '{{ var|join:" & " }}'}) def test_autoescape_filters02(self): - output = self.engine.render_to_string('autoescape-filters02', {'var': ('Tom', 'Dick', 'Harry')}) - self.assertEqual(output, 'Tom & Dick & Harry') + output = self.engine.render_to_string( + "autoescape-filters02", {"var": ("Tom", "Dick", "Harry")} + ) + self.assertEqual(output, "Tom & Dick & Harry") - @setup({'autoescape-literals01': '{{ "this & that" }}'}) + @setup({"autoescape-literals01": '{{ "this & that" }}'}) def test_autoescape_literals01(self): """ Literal strings are safe. """ - output = self.engine.render_to_string('autoescape-literals01') - self.assertEqual(output, 'this & that') + output = self.engine.render_to_string("autoescape-literals01") + self.assertEqual(output, "this & that") - @setup({'autoescape-stringiterations01': '{% for l in var %}{{ l }},{% endfor %}'}) + @setup({"autoescape-stringiterations01": "{% for l in var %}{{ l }},{% endfor %}"}) def test_autoescape_stringiterations01(self): """ Iterating over strings outputs safe characters. """ - output = self.engine.render_to_string('autoescape-stringiterations01', {'var': 'K&R'}) - self.assertEqual(output, 'K,&,R,') + output = self.engine.render_to_string( + "autoescape-stringiterations01", {"var": "K&R"} + ) + self.assertEqual(output, "K,&,R,") - @setup({'autoescape-lookup01': '{{ var.key }}'}) + @setup({"autoescape-lookup01": "{{ var.key }}"}) def test_autoescape_lookup01(self): """ Escape requirement survives lookup. """ - output = self.engine.render_to_string('autoescape-lookup01', {'var': {'key': 'this & that'}}) - self.assertEqual(output, 'this & that') + output = self.engine.render_to_string( + "autoescape-lookup01", {"var": {"key": "this & that"}} + ) + self.assertEqual(output, "this & that") - @setup({'autoescape-incorrect-arg': '{% autoescape true %}{{ var.key }}{% endautoescape %}'}) + @setup( + { + "autoescape-incorrect-arg": "{% autoescape true %}{{ var.key }}{% endautoescape %}" + } + ) def test_invalid_arg(self): msg = "'autoescape' argument should be 'on' or 'off'" with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('autoescape-incorrect-arg', {'var': {'key': 'this & that'}}) + self.engine.render_to_string( + "autoescape-incorrect-arg", {"var": {"key": "this & that"}} + ) - @setup({'autoescape-incorrect-arg': '{% autoescape %}{{ var.key }}{% endautoescape %}'}) + @setup( + {"autoescape-incorrect-arg": "{% autoescape %}{{ var.key }}{% endautoescape %}"} + ) def test_no_arg(self): msg = "'autoescape' tag requires exactly one argument." with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('autoescape-incorrect-arg', {'var': {'key': 'this & that'}}) + self.engine.render_to_string( + "autoescape-incorrect-arg", {"var": {"key": "this & that"}} + ) diff --git a/tests/template_tests/syntax_tests/test_basic.py b/tests/template_tests/syntax_tests/test_basic.py index 011ce51229..20bf30d55c 100644 --- a/tests/template_tests/syntax_tests/test_basic.py +++ b/tests/template_tests/syntax_tests/test_basic.py @@ -6,20 +6,19 @@ from django.test import SimpleTestCase from ..utils import SilentAttrClass, SilentGetItemClass, SomeClass, setup basic_templates = { - 'basic-syntax01': 'something cool', - 'basic-syntax02': '{{ headline }}', - 'basic-syntax03': '{{ first }} --- {{ second }}', + "basic-syntax01": "something cool", + "basic-syntax02": "{{ headline }}", + "basic-syntax03": "{{ first }} --- {{ second }}", } class BasicSyntaxTests(SimpleTestCase): - @setup(basic_templates) def test_basic_syntax01(self): """ Plain text should go through the template parser untouched. """ - output = self.engine.render_to_string('basic-syntax01') + output = self.engine.render_to_string("basic-syntax01") self.assertEqual(output, "something cool") @setup(basic_templates) @@ -28,318 +27,330 @@ class BasicSyntaxTests(SimpleTestCase): Variables should be replaced with their value in the current context """ - output = self.engine.render_to_string('basic-syntax02', {'headline': 'Success'}) - self.assertEqual(output, 'Success') + output = self.engine.render_to_string("basic-syntax02", {"headline": "Success"}) + self.assertEqual(output, "Success") @setup(basic_templates) def test_basic_syntax03(self): """ More than one replacement variable is allowed in a template """ - output = self.engine.render_to_string('basic-syntax03', {"first": 1, "second": 2}) - self.assertEqual(output, '1 --- 2') + output = self.engine.render_to_string( + "basic-syntax03", {"first": 1, "second": 2} + ) + self.assertEqual(output, "1 --- 2") - @setup({'basic-syntax04': 'as{{ missing }}df'}) + @setup({"basic-syntax04": "as{{ missing }}df"}) def test_basic_syntax04(self): """ Fail silently when a variable is not found in the current context """ - output = self.engine.render_to_string('basic-syntax04') + output = self.engine.render_to_string("basic-syntax04") if self.engine.string_if_invalid: - self.assertEqual(output, 'asINVALIDdf') + self.assertEqual(output, "asINVALIDdf") else: - self.assertEqual(output, 'asdf') + self.assertEqual(output, "asdf") - @setup({'basic-syntax06': '{{ multi word variable }}'}) + @setup({"basic-syntax06": "{{ multi word variable }}"}) def test_basic_syntax06(self): """ A variable may not contain more than one word """ with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('basic-syntax06') + self.engine.get_template("basic-syntax06") - @setup({'basic-syntax07': '{{ }}'}) + @setup({"basic-syntax07": "{{ }}"}) def test_basic_syntax07(self): """ Raise TemplateSyntaxError for empty variable tags. """ - with self.assertRaisesMessage(TemplateSyntaxError, 'Empty variable tag on line 1'): - self.engine.get_template('basic-syntax07') + with self.assertRaisesMessage( + TemplateSyntaxError, "Empty variable tag on line 1" + ): + self.engine.get_template("basic-syntax07") - @setup({'basic-syntax08': '{{ }}'}) + @setup({"basic-syntax08": "{{ }}"}) def test_basic_syntax08(self): """ Raise TemplateSyntaxError for empty variable tags. """ - with self.assertRaisesMessage(TemplateSyntaxError, 'Empty variable tag on line 1'): - self.engine.get_template('basic-syntax08') + with self.assertRaisesMessage( + TemplateSyntaxError, "Empty variable tag on line 1" + ): + self.engine.get_template("basic-syntax08") - @setup({'basic-syntax09': '{{ var.method }}'}) + @setup({"basic-syntax09": "{{ var.method }}"}) def test_basic_syntax09(self): """ Attribute syntax allows a template to call an object's attribute """ - output = self.engine.render_to_string('basic-syntax09', {'var': SomeClass()}) - self.assertEqual(output, 'SomeClass.method') + output = self.engine.render_to_string("basic-syntax09", {"var": SomeClass()}) + self.assertEqual(output, "SomeClass.method") - @setup({'basic-syntax10': '{{ var.otherclass.method }}'}) + @setup({"basic-syntax10": "{{ var.otherclass.method }}"}) def test_basic_syntax10(self): """ Multiple levels of attribute access are allowed. """ - output = self.engine.render_to_string('basic-syntax10', {'var': SomeClass()}) - self.assertEqual(output, 'OtherClass.method') + output = self.engine.render_to_string("basic-syntax10", {"var": SomeClass()}) + self.assertEqual(output, "OtherClass.method") - @setup({'basic-syntax11': '{{ var.blech }}'}) + @setup({"basic-syntax11": "{{ var.blech }}"}) def test_basic_syntax11(self): """ Fail silently when a variable's attribute isn't found. """ - output = self.engine.render_to_string('basic-syntax11', {'var': SomeClass()}) + output = self.engine.render_to_string("basic-syntax11", {"var": SomeClass()}) if self.engine.string_if_invalid: - self.assertEqual(output, 'INVALID') + self.assertEqual(output, "INVALID") else: - self.assertEqual(output, '') + self.assertEqual(output, "") - @setup({'basic-syntax12': '{{ var.__dict__ }}'}) + @setup({"basic-syntax12": "{{ var.__dict__ }}"}) def test_basic_syntax12(self): """ Raise TemplateSyntaxError when trying to access a variable beginning with an underscore. """ with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('basic-syntax12') + self.engine.get_template("basic-syntax12") # Raise TemplateSyntaxError when trying to access a variable # containing an illegal character. - @setup({'basic-syntax13': "{{ va>r }}"}) + @setup({"basic-syntax13": "{{ va>r }}"}) def test_basic_syntax13(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('basic-syntax13') + self.engine.get_template("basic-syntax13") - @setup({'basic-syntax14': "{{ (var.r) }}"}) + @setup({"basic-syntax14": "{{ (var.r) }}"}) def test_basic_syntax14(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('basic-syntax14') + self.engine.get_template("basic-syntax14") - @setup({'basic-syntax15': "{{ sp%am }}"}) + @setup({"basic-syntax15": "{{ sp%am }}"}) def test_basic_syntax15(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('basic-syntax15') + self.engine.get_template("basic-syntax15") - @setup({'basic-syntax16': "{{ eggs! }}"}) + @setup({"basic-syntax16": "{{ eggs! }}"}) def test_basic_syntax16(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('basic-syntax16') + self.engine.get_template("basic-syntax16") - @setup({'basic-syntax17': "{{ moo? }}"}) + @setup({"basic-syntax17": "{{ moo? }}"}) def test_basic_syntax17(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('basic-syntax17') + self.engine.get_template("basic-syntax17") - @setup({'basic-syntax18': "{{ foo.bar }}"}) + @setup({"basic-syntax18": "{{ foo.bar }}"}) def test_basic_syntax18(self): """ Attribute syntax allows a template to call a dictionary key's value. """ - output = self.engine.render_to_string('basic-syntax18', {"foo": {"bar": "baz"}}) + output = self.engine.render_to_string("basic-syntax18", {"foo": {"bar": "baz"}}) self.assertEqual(output, "baz") - @setup({'basic-syntax19': "{{ foo.spam }}"}) + @setup({"basic-syntax19": "{{ foo.spam }}"}) def test_basic_syntax19(self): """ Fail silently when a variable's dictionary key isn't found. """ - output = self.engine.render_to_string('basic-syntax19', {"foo": {"bar": "baz"}}) + output = self.engine.render_to_string("basic-syntax19", {"foo": {"bar": "baz"}}) if self.engine.string_if_invalid: - self.assertEqual(output, 'INVALID') + self.assertEqual(output, "INVALID") else: - self.assertEqual(output, '') + self.assertEqual(output, "") - @setup({'basic-syntax20': "{{ var.method2 }}"}) + @setup({"basic-syntax20": "{{ var.method2 }}"}) def test_basic_syntax20(self): """ Fail silently when accessing a non-simple method """ - output = self.engine.render_to_string('basic-syntax20', {'var': SomeClass()}) + output = self.engine.render_to_string("basic-syntax20", {"var": SomeClass()}) if self.engine.string_if_invalid: - self.assertEqual(output, 'INVALID') + self.assertEqual(output, "INVALID") else: - self.assertEqual(output, '') + self.assertEqual(output, "") - @setup({'basic-syntax20b': "{{ var.method5 }}"}) + @setup({"basic-syntax20b": "{{ var.method5 }}"}) def test_basic_syntax20b(self): """ Don't silence a TypeError if it was raised inside a callable. """ - template = self.engine.get_template('basic-syntax20b') + template = self.engine.get_template("basic-syntax20b") with self.assertRaises(TypeError): - template.render(Context({'var': SomeClass()})) + template.render(Context({"var": SomeClass()})) # Don't get confused when parsing something that is almost, but not # quite, a template tag. - @setup({'basic-syntax21': "a {{ moo %} b"}) + @setup({"basic-syntax21": "a {{ moo %} b"}) def test_basic_syntax21(self): - output = self.engine.render_to_string('basic-syntax21') + output = self.engine.render_to_string("basic-syntax21") self.assertEqual(output, "a {{ moo %} b") - @setup({'basic-syntax22': "{{ moo #}"}) + @setup({"basic-syntax22": "{{ moo #}"}) def test_basic_syntax22(self): - output = self.engine.render_to_string('basic-syntax22') + output = self.engine.render_to_string("basic-syntax22") self.assertEqual(output, "{{ moo #}") - @setup({'basic-syntax23': "{{ moo #} {{ cow }}"}) + @setup({"basic-syntax23": "{{ moo #} {{ cow }}"}) def test_basic_syntax23(self): """ Treat "moo #} {{ cow" as the variable. Not ideal, but costly to work around, so this triggers an error. """ with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('basic-syntax23') + self.engine.get_template("basic-syntax23") - @setup({'basic-syntax24': "{{ moo\n }}"}) + @setup({"basic-syntax24": "{{ moo\n }}"}) def test_basic_syntax24(self): """ Embedded newlines make it not-a-tag. """ - output = self.engine.render_to_string('basic-syntax24') + output = self.engine.render_to_string("basic-syntax24") self.assertEqual(output, "{{ moo\n }}") # Literal strings are permitted inside variables, mostly for i18n # purposes. - @setup({'basic-syntax25': '{{ "fred" }}'}) + @setup({"basic-syntax25": '{{ "fred" }}'}) def test_basic_syntax25(self): - output = self.engine.render_to_string('basic-syntax25') + output = self.engine.render_to_string("basic-syntax25") self.assertEqual(output, "fred") - @setup({'basic-syntax26': r'{{ "\"fred\"" }}'}) + @setup({"basic-syntax26": r'{{ "\"fred\"" }}'}) def test_basic_syntax26(self): - output = self.engine.render_to_string('basic-syntax26') - self.assertEqual(output, "\"fred\"") + output = self.engine.render_to_string("basic-syntax26") + self.assertEqual(output, '"fred"') - @setup({'basic-syntax27': r'{{ _("\"fred\"") }}'}) + @setup({"basic-syntax27": r'{{ _("\"fred\"") }}'}) def test_basic_syntax27(self): - output = self.engine.render_to_string('basic-syntax27') - self.assertEqual(output, "\"fred\"") + output = self.engine.render_to_string("basic-syntax27") + self.assertEqual(output, '"fred"') # #12554 -- Make sure a silent_variable_failure Exception is # suppressed on dictionary and attribute lookup. - @setup({'basic-syntax28': "{{ a.b }}"}) + @setup({"basic-syntax28": "{{ a.b }}"}) def test_basic_syntax28(self): - output = self.engine.render_to_string('basic-syntax28', {'a': SilentGetItemClass()}) + output = self.engine.render_to_string( + "basic-syntax28", {"a": SilentGetItemClass()} + ) if self.engine.string_if_invalid: - self.assertEqual(output, 'INVALID') + self.assertEqual(output, "INVALID") else: - self.assertEqual(output, '') + self.assertEqual(output, "") - @setup({'basic-syntax29': "{{ a.b }}"}) + @setup({"basic-syntax29": "{{ a.b }}"}) def test_basic_syntax29(self): - output = self.engine.render_to_string('basic-syntax29', {'a': SilentAttrClass()}) + output = self.engine.render_to_string( + "basic-syntax29", {"a": SilentAttrClass()} + ) if self.engine.string_if_invalid: - self.assertEqual(output, 'INVALID') + self.assertEqual(output, "INVALID") else: - self.assertEqual(output, '') + self.assertEqual(output, "") # Something that starts like a number but has an extra lookup works # as a lookup. - @setup({'basic-syntax30': "{{ 1.2.3 }}"}) + @setup({"basic-syntax30": "{{ 1.2.3 }}"}) def test_basic_syntax30(self): output = self.engine.render_to_string( - 'basic-syntax30', - {"1": {"2": {"3": "d"}}} + "basic-syntax30", {"1": {"2": {"3": "d"}}} ) - self.assertEqual(output, 'd') + self.assertEqual(output, "d") - @setup({'basic-syntax31': "{{ 1.2.3 }}"}) + @setup({"basic-syntax31": "{{ 1.2.3 }}"}) def test_basic_syntax31(self): output = self.engine.render_to_string( - 'basic-syntax31', + "basic-syntax31", {"1": {"2": ("a", "b", "c", "d")}}, ) - self.assertEqual(output, 'd') + self.assertEqual(output, "d") - @setup({'basic-syntax32': "{{ 1.2.3 }}"}) + @setup({"basic-syntax32": "{{ 1.2.3 }}"}) def test_basic_syntax32(self): output = self.engine.render_to_string( - 'basic-syntax32', + "basic-syntax32", {"1": (("x", "x", "x", "x"), ("y", "y", "y", "y"), ("a", "b", "c", "d"))}, ) - self.assertEqual(output, 'd') + self.assertEqual(output, "d") - @setup({'basic-syntax33': "{{ 1.2.3 }}"}) + @setup({"basic-syntax33": "{{ 1.2.3 }}"}) def test_basic_syntax33(self): output = self.engine.render_to_string( - 'basic-syntax33', + "basic-syntax33", {"1": ("xxxx", "yyyy", "abcd")}, ) - self.assertEqual(output, 'd') + self.assertEqual(output, "d") - @setup({'basic-syntax34': "{{ 1.2.3 }}"}) + @setup({"basic-syntax34": "{{ 1.2.3 }}"}) def test_basic_syntax34(self): output = self.engine.render_to_string( - 'basic-syntax34', - {"1": ({"x": "x"}, {"y": "y"}, {"z": "z", "3": "d"})} + "basic-syntax34", {"1": ({"x": "x"}, {"y": "y"}, {"z": "z", "3": "d"})} ) - self.assertEqual(output, 'd') + self.assertEqual(output, "d") # Numbers are numbers even if their digits are in the context. - @setup({'basic-syntax35': "{{ 1 }}"}) + @setup({"basic-syntax35": "{{ 1 }}"}) def test_basic_syntax35(self): - output = self.engine.render_to_string('basic-syntax35', {"1": "abc"}) - self.assertEqual(output, '1') + output = self.engine.render_to_string("basic-syntax35", {"1": "abc"}) + self.assertEqual(output, "1") - @setup({'basic-syntax36': "{{ 1.2 }}"}) + @setup({"basic-syntax36": "{{ 1.2 }}"}) def test_basic_syntax36(self): - output = self.engine.render_to_string('basic-syntax36', {"1": "abc"}) - self.assertEqual(output, '1.2') + output = self.engine.render_to_string("basic-syntax36", {"1": "abc"}) + self.assertEqual(output, "1.2") - @setup({'basic-syntax37': '{{ callable }}'}) + @setup({"basic-syntax37": "{{ callable }}"}) def test_basic_syntax37(self): """ Call methods in the top level of the context. """ - output = self.engine.render_to_string('basic-syntax37', {"callable": lambda: "foo bar"}) - self.assertEqual(output, 'foo bar') + output = self.engine.render_to_string( + "basic-syntax37", {"callable": lambda: "foo bar"} + ) + self.assertEqual(output, "foo bar") - @setup({'basic-syntax38': '{{ var.callable }}'}) + @setup({"basic-syntax38": "{{ var.callable }}"}) def test_basic_syntax38(self): """ Call methods returned from dictionary lookups. """ - output = self.engine.render_to_string('basic-syntax38', {"var": {"callable": lambda: "foo bar"}}) - self.assertEqual(output, 'foo bar') + output = self.engine.render_to_string( + "basic-syntax38", {"var": {"callable": lambda: "foo bar"}} + ) + self.assertEqual(output, "foo bar") - @setup({'template': '{% block content %}'}) + @setup({"template": "{% block content %}"}) def test_unclosed_block(self): msg = "Unclosed tag on line 1: 'block'. Looking for one of: endblock." with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('template') + self.engine.render_to_string("template") - @setup({'template': '{% if a %}'}) + @setup({"template": "{% if a %}"}) def test_unclosed_block2(self): msg = "Unclosed tag on line 1: 'if'. Looking for one of: elif, else, endif." with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('template') + self.engine.render_to_string("template") - @setup({'tpl-str': '%s', 'tpl-percent': '%%', 'tpl-weird-percent': '% %s'}) + @setup({"tpl-str": "%s", "tpl-percent": "%%", "tpl-weird-percent": "% %s"}) def test_ignores_strings_that_look_like_format_interpolation(self): - output = self.engine.render_to_string('tpl-str') - self.assertEqual(output, '%s') - output = self.engine.render_to_string('tpl-percent') - self.assertEqual(output, '%%') - output = self.engine.render_to_string('tpl-weird-percent') - self.assertEqual(output, '% %s') + output = self.engine.render_to_string("tpl-str") + self.assertEqual(output, "%s") + output = self.engine.render_to_string("tpl-percent") + self.assertEqual(output, "%%") + output = self.engine.render_to_string("tpl-weird-percent") + self.assertEqual(output, "% %s") class BlockContextTests(SimpleTestCase): def test_repr(self): block_context = BlockContext() - block_context.add_blocks({'content': BlockNode('content', [])}) + block_context.add_blocks({"content": BlockNode("content", [])}) self.assertEqual( repr(block_context), "<BlockContext: blocks=defaultdict(<class 'list'>, " diff --git a/tests/template_tests/syntax_tests/test_builtins.py b/tests/template_tests/syntax_tests/test_builtins.py index 8ade96c65a..6e81410556 100644 --- a/tests/template_tests/syntax_tests/test_builtins.py +++ b/tests/template_tests/syntax_tests/test_builtins.py @@ -4,18 +4,17 @@ from ..utils import setup class BuiltinsTests(SimpleTestCase): - - @setup({'builtins01': '{{ True }}'}) + @setup({"builtins01": "{{ True }}"}) def test_builtins01(self): - output = self.engine.render_to_string('builtins01') - self.assertEqual(output, 'True') + output = self.engine.render_to_string("builtins01") + self.assertEqual(output, "True") - @setup({'builtins02': '{{ False }}'}) + @setup({"builtins02": "{{ False }}"}) def test_builtins02(self): - output = self.engine.render_to_string('builtins02') - self.assertEqual(output, 'False') + output = self.engine.render_to_string("builtins02") + self.assertEqual(output, "False") - @setup({'builtins03': '{{ None }}'}) + @setup({"builtins03": "{{ None }}"}) def test_builtins03(self): - output = self.engine.render_to_string('builtins03') - self.assertEqual(output, 'None') + output = self.engine.render_to_string("builtins03") + self.assertEqual(output, "None") diff --git a/tests/template_tests/syntax_tests/test_cache.py b/tests/template_tests/syntax_tests/test_cache.py index 80af1c2bd6..a722420637 100644 --- a/tests/template_tests/syntax_tests/test_cache.py +++ b/tests/template_tests/syntax_tests/test_cache.py @@ -7,176 +7,203 @@ from ..utils import setup class CacheTagTests(SimpleTestCase): libraries = { - 'cache': 'django.templatetags.cache', - 'custom': 'template_tests.templatetags.custom', + "cache": "django.templatetags.cache", + "custom": "template_tests.templatetags.custom", } def tearDown(self): cache.clear() - @setup({'cache03': '{% load cache %}{% cache 2 test %}cache03{% endcache %}'}) + @setup({"cache03": "{% load cache %}{% cache 2 test %}cache03{% endcache %}"}) def test_cache03(self): - output = self.engine.render_to_string('cache03') - self.assertEqual(output, 'cache03') + output = self.engine.render_to_string("cache03") + self.assertEqual(output, "cache03") - @setup({ - 'cache03': '{% load cache %}{% cache 2 test %}cache03{% endcache %}', - 'cache04': '{% load cache %}{% cache 2 test %}cache04{% endcache %}', - }) + @setup( + { + "cache03": "{% load cache %}{% cache 2 test %}cache03{% endcache %}", + "cache04": "{% load cache %}{% cache 2 test %}cache04{% endcache %}", + } + ) def test_cache04(self): - self.engine.render_to_string('cache03') - output = self.engine.render_to_string('cache04') - self.assertEqual(output, 'cache03') + self.engine.render_to_string("cache03") + output = self.engine.render_to_string("cache04") + self.assertEqual(output, "cache03") - @setup({'cache05': '{% load cache %}{% cache 2 test foo %}cache05{% endcache %}'}) + @setup({"cache05": "{% load cache %}{% cache 2 test foo %}cache05{% endcache %}"}) def test_cache05(self): - output = self.engine.render_to_string('cache05', {'foo': 1}) - self.assertEqual(output, 'cache05') + output = self.engine.render_to_string("cache05", {"foo": 1}) + self.assertEqual(output, "cache05") - @setup({'cache06': '{% load cache %}{% cache 2 test foo %}cache06{% endcache %}'}) + @setup({"cache06": "{% load cache %}{% cache 2 test foo %}cache06{% endcache %}"}) def test_cache06(self): - output = self.engine.render_to_string('cache06', {'foo': 2}) - self.assertEqual(output, 'cache06') + output = self.engine.render_to_string("cache06", {"foo": 2}) + self.assertEqual(output, "cache06") - @setup({ - 'cache05': '{% load cache %}{% cache 2 test foo %}cache05{% endcache %}', - 'cache07': '{% load cache %}{% cache 2 test foo %}cache07{% endcache %}', - }) + @setup( + { + "cache05": "{% load cache %}{% cache 2 test foo %}cache05{% endcache %}", + "cache07": "{% load cache %}{% cache 2 test foo %}cache07{% endcache %}", + } + ) def test_cache07(self): - context = {'foo': 1} - self.engine.render_to_string('cache05', context) - output = self.engine.render_to_string('cache07', context) - self.assertEqual(output, 'cache05') + context = {"foo": 1} + self.engine.render_to_string("cache05", context) + output = self.engine.render_to_string("cache07", context) + self.assertEqual(output, "cache05") - @setup({ - 'cache06': '{% load cache %}{% cache 2 test foo %}cache06{% endcache %}', - 'cache08': '{% load cache %}{% cache time test foo %}cache08{% endcache %}', - }) + @setup( + { + "cache06": "{% load cache %}{% cache 2 test foo %}cache06{% endcache %}", + "cache08": "{% load cache %}{% cache time test foo %}cache08{% endcache %}", + } + ) def test_cache08(self): """ Allow first argument to be a variable. """ - context = {'foo': 2, 'time': 2} - self.engine.render_to_string('cache06', context) - output = self.engine.render_to_string('cache08', context) - self.assertEqual(output, 'cache06') + context = {"foo": 2, "time": 2} + self.engine.render_to_string("cache06", context) + output = self.engine.render_to_string("cache08", context) + self.assertEqual(output, "cache06") # Raise exception if we don't have at least 2 args, first one integer. - @setup({'cache11': '{% load cache %}{% cache %}{% endcache %}'}) + @setup({"cache11": "{% load cache %}{% cache %}{% endcache %}"}) def test_cache11(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('cache11') + self.engine.get_template("cache11") - @setup({'cache12': '{% load cache %}{% cache 1 %}{% endcache %}'}) + @setup({"cache12": "{% load cache %}{% cache 1 %}{% endcache %}"}) def test_cache12(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('cache12') + self.engine.get_template("cache12") - @setup({'cache13': '{% load cache %}{% cache foo bar %}{% endcache %}'}) + @setup({"cache13": "{% load cache %}{% cache foo bar %}{% endcache %}"}) def test_cache13(self): with self.assertRaises(TemplateSyntaxError): - self.engine.render_to_string('cache13') + self.engine.render_to_string("cache13") - @setup({'cache14': '{% load cache %}{% cache foo bar %}{% endcache %}'}) + @setup({"cache14": "{% load cache %}{% cache foo bar %}{% endcache %}"}) def test_cache14(self): with self.assertRaises(TemplateSyntaxError): - self.engine.render_to_string('cache14', {'foo': 'fail'}) + self.engine.render_to_string("cache14", {"foo": "fail"}) - @setup({'cache15': '{% load cache %}{% cache foo bar %}{% endcache %}'}) + @setup({"cache15": "{% load cache %}{% cache foo bar %}{% endcache %}"}) def test_cache15(self): with self.assertRaises(TemplateSyntaxError): - self.engine.render_to_string('cache15', {'foo': []}) + self.engine.render_to_string("cache15", {"foo": []}) - @setup({'cache16': '{% load cache %}{% cache 1 foo bar %}{% endcache %}'}) + @setup({"cache16": "{% load cache %}{% cache 1 foo bar %}{% endcache %}"}) def test_cache16(self): """ Regression test for #7460. """ - output = self.engine.render_to_string('cache16', {'foo': 'foo', 'bar': 'with spaces'}) - self.assertEqual(output, '') + output = self.engine.render_to_string( + "cache16", {"foo": "foo", "bar": "with spaces"} + ) + self.assertEqual(output, "") - @setup({'cache17': '{% load cache %}{% cache 10 long_cache_key poem %}Some Content{% endcache %}'}) + @setup( + { + "cache17": "{% load cache %}{% cache 10 long_cache_key poem %}Some Content{% endcache %}" + } + ) def test_cache17(self): """ Regression test for #11270. """ output = self.engine.render_to_string( - 'cache17', + "cache17", { - 'poem': ( - 'Oh freddled gruntbuggly/Thy micturations are to me/' - 'As plurdled gabbleblotchits/On a lurgid bee/' - 'That mordiously hath bitled out/Its earted jurtles/' - 'Into a rancid festering/Or else I shall rend thee in the gobberwarts' - 'with my blurglecruncheon/See if I don\'t.' + "poem": ( + "Oh freddled gruntbuggly/Thy micturations are to me/" + "As plurdled gabbleblotchits/On a lurgid bee/" + "That mordiously hath bitled out/Its earted jurtles/" + "Into a rancid festering/Or else I shall rend thee in the gobberwarts" + "with my blurglecruncheon/See if I don't." ), - } + }, ) - self.assertEqual(output, 'Some Content') + self.assertEqual(output, "Some Content") - @setup({'cache18': '{% load cache custom %}{% cache 2|noop:"x y" cache18 %}cache18{% endcache %}'}) + @setup( + { + "cache18": '{% load cache custom %}{% cache 2|noop:"x y" cache18 %}cache18{% endcache %}' + } + ) def test_cache18(self): """ Test whitespace in filter arguments """ - output = self.engine.render_to_string('cache18') - self.assertEqual(output, 'cache18') + output = self.engine.render_to_string("cache18") + self.assertEqual(output, "cache18") - @setup({ - 'first': '{% load cache %}{% cache None fragment19 %}content{% endcache %}', - 'second': '{% load cache %}{% cache None fragment19 %}not rendered{% endcache %}' - }) + @setup( + { + "first": "{% load cache %}{% cache None fragment19 %}content{% endcache %}", + "second": "{% load cache %}{% cache None fragment19 %}not rendered{% endcache %}", + } + ) def test_none_timeout(self): """A timeout of None means "cache forever".""" - output = self.engine.render_to_string('first') - self.assertEqual(output, 'content') - output = self.engine.render_to_string('second') - self.assertEqual(output, 'content') + output = self.engine.render_to_string("first") + self.assertEqual(output, "content") + output = self.engine.render_to_string("second") + self.assertEqual(output, "content") class CacheTests(SimpleTestCase): - @classmethod def setUpClass(cls): - cls.engine = Engine(libraries={'cache': 'django.templatetags.cache'}) + cls.engine = Engine(libraries={"cache": "django.templatetags.cache"}) super().setUpClass() def test_cache_regression_20130(self): - t = self.engine.from_string('{% load cache %}{% cache 1 regression_20130 %}foo{% endcache %}') + t = self.engine.from_string( + "{% load cache %}{% cache 1 regression_20130 %}foo{% endcache %}" + ) cachenode = t.nodelist[1] - self.assertEqual(cachenode.fragment_name, 'regression_20130') + self.assertEqual(cachenode.fragment_name, "regression_20130") - @override_settings(CACHES={ - 'default': { - 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', - 'LOCATION': 'default', - }, - 'template_fragments': { - 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', - 'LOCATION': 'fragments', - }, - }) + @override_settings( + CACHES={ + "default": { + "BACKEND": "django.core.cache.backends.locmem.LocMemCache", + "LOCATION": "default", + }, + "template_fragments": { + "BACKEND": "django.core.cache.backends.locmem.LocMemCache", + "LOCATION": "fragments", + }, + } + ) def test_cache_fragment_cache(self): """ When a cache called "template_fragments" is present, the cache tag will use it in preference to 'default' """ - t1 = self.engine.from_string('{% load cache %}{% cache 1 fragment %}foo{% endcache %}') - t2 = self.engine.from_string('{% load cache %}{% cache 1 fragment using="default" %}bar{% endcache %}') + t1 = self.engine.from_string( + "{% load cache %}{% cache 1 fragment %}foo{% endcache %}" + ) + t2 = self.engine.from_string( + '{% load cache %}{% cache 1 fragment using="default" %}bar{% endcache %}' + ) ctx = Context() o1 = t1.render(ctx) o2 = t2.render(ctx) - self.assertEqual(o1, 'foo') - self.assertEqual(o2, 'bar') + self.assertEqual(o1, "foo") + self.assertEqual(o2, "bar") def test_cache_missing_backend(self): """ When a cache that doesn't exist is specified, the cache tag will raise a TemplateSyntaxError '""" - t = self.engine.from_string('{% load cache %}{% cache 1 backend using="unknown" %}bar{% endcache %}') + t = self.engine.from_string( + '{% load cache %}{% cache 1 backend using="unknown" %}bar{% endcache %}' + ) ctx = Context() with self.assertRaises(TemplateSyntaxError): diff --git a/tests/template_tests/syntax_tests/test_comment.py b/tests/template_tests/syntax_tests/test_comment.py index d1b4dcf147..58dbe88b36 100644 --- a/tests/template_tests/syntax_tests/test_comment.py +++ b/tests/template_tests/syntax_tests/test_comment.py @@ -4,89 +4,92 @@ from ..utils import setup class CommentSyntaxTests(SimpleTestCase): - - @setup({'comment-syntax01': '{# this is hidden #}hello'}) + @setup({"comment-syntax01": "{# this is hidden #}hello"}) def test_comment_syntax01(self): - output = self.engine.render_to_string('comment-syntax01') - self.assertEqual(output, 'hello') + output = self.engine.render_to_string("comment-syntax01") + self.assertEqual(output, "hello") - @setup({'comment-syntax02': '{# this is hidden #}hello{# foo #}'}) + @setup({"comment-syntax02": "{# this is hidden #}hello{# foo #}"}) def test_comment_syntax02(self): - output = self.engine.render_to_string('comment-syntax02') - self.assertEqual(output, 'hello') + output = self.engine.render_to_string("comment-syntax02") + self.assertEqual(output, "hello") - @setup({'comment-syntax03': 'foo{# {% if %} #}'}) + @setup({"comment-syntax03": "foo{# {% if %} #}"}) def test_comment_syntax03(self): - output = self.engine.render_to_string('comment-syntax03') - self.assertEqual(output, 'foo') + output = self.engine.render_to_string("comment-syntax03") + self.assertEqual(output, "foo") - @setup({'comment-syntax04': 'foo{# {% endblock %} #}'}) + @setup({"comment-syntax04": "foo{# {% endblock %} #}"}) def test_comment_syntax04(self): - output = self.engine.render_to_string('comment-syntax04') - self.assertEqual(output, 'foo') + output = self.engine.render_to_string("comment-syntax04") + self.assertEqual(output, "foo") - @setup({'comment-syntax05': 'foo{# {% somerandomtag %} #}'}) + @setup({"comment-syntax05": "foo{# {% somerandomtag %} #}"}) def test_comment_syntax05(self): - output = self.engine.render_to_string('comment-syntax05') - self.assertEqual(output, 'foo') + output = self.engine.render_to_string("comment-syntax05") + self.assertEqual(output, "foo") - @setup({'comment-syntax06': 'foo{# {% #}'}) + @setup({"comment-syntax06": "foo{# {% #}"}) def test_comment_syntax06(self): - output = self.engine.render_to_string('comment-syntax06') - self.assertEqual(output, 'foo') + output = self.engine.render_to_string("comment-syntax06") + self.assertEqual(output, "foo") - @setup({'comment-syntax07': 'foo{# %} #}'}) + @setup({"comment-syntax07": "foo{# %} #}"}) def test_comment_syntax07(self): - output = self.engine.render_to_string('comment-syntax07') - self.assertEqual(output, 'foo') + output = self.engine.render_to_string("comment-syntax07") + self.assertEqual(output, "foo") - @setup({'comment-syntax08': 'foo{# %} #}bar'}) + @setup({"comment-syntax08": "foo{# %} #}bar"}) def test_comment_syntax08(self): - output = self.engine.render_to_string('comment-syntax08') - self.assertEqual(output, 'foobar') + output = self.engine.render_to_string("comment-syntax08") + self.assertEqual(output, "foobar") - @setup({'comment-syntax09': 'foo{# {{ #}'}) + @setup({"comment-syntax09": "foo{# {{ #}"}) def test_comment_syntax09(self): - output = self.engine.render_to_string('comment-syntax09') - self.assertEqual(output, 'foo') + output = self.engine.render_to_string("comment-syntax09") + self.assertEqual(output, "foo") - @setup({'comment-syntax10': 'foo{# }} #}'}) + @setup({"comment-syntax10": "foo{# }} #}"}) def test_comment_syntax10(self): - output = self.engine.render_to_string('comment-syntax10') - self.assertEqual(output, 'foo') + output = self.engine.render_to_string("comment-syntax10") + self.assertEqual(output, "foo") - @setup({'comment-syntax11': 'foo{# { #}'}) + @setup({"comment-syntax11": "foo{# { #}"}) def test_comment_syntax11(self): - output = self.engine.render_to_string('comment-syntax11') - self.assertEqual(output, 'foo') + output = self.engine.render_to_string("comment-syntax11") + self.assertEqual(output, "foo") - @setup({'comment-syntax12': 'foo{# } #}'}) + @setup({"comment-syntax12": "foo{# } #}"}) def test_comment_syntax12(self): - output = self.engine.render_to_string('comment-syntax12') - self.assertEqual(output, 'foo') + output = self.engine.render_to_string("comment-syntax12") + self.assertEqual(output, "foo") - @setup({'comment-tag01': '{% comment %}this is hidden{% endcomment %}hello'}) + @setup({"comment-tag01": "{% comment %}this is hidden{% endcomment %}hello"}) def test_comment_tag01(self): - output = self.engine.render_to_string('comment-tag01') - self.assertEqual(output, 'hello') + output = self.engine.render_to_string("comment-tag01") + self.assertEqual(output, "hello") - @setup({'comment-tag02': '{% comment %}this is hidden{% endcomment %}' - 'hello{% comment %}foo{% endcomment %}'}) + @setup( + { + "comment-tag02": "{% comment %}this is hidden{% endcomment %}" + "hello{% comment %}foo{% endcomment %}" + } + ) def test_comment_tag02(self): - output = self.engine.render_to_string('comment-tag02') - self.assertEqual(output, 'hello') + output = self.engine.render_to_string("comment-tag02") + self.assertEqual(output, "hello") - @setup({'comment-tag03': 'foo{% comment %} {% if %} {% endcomment %}'}) + @setup({"comment-tag03": "foo{% comment %} {% if %} {% endcomment %}"}) def test_comment_tag03(self): - output = self.engine.render_to_string('comment-tag03') - self.assertEqual(output, 'foo') + output = self.engine.render_to_string("comment-tag03") + self.assertEqual(output, "foo") - @setup({'comment-tag04': 'foo{% comment %} {% endblock %} {% endcomment %}'}) + @setup({"comment-tag04": "foo{% comment %} {% endblock %} {% endcomment %}"}) def test_comment_tag04(self): - output = self.engine.render_to_string('comment-tag04') - self.assertEqual(output, 'foo') + output = self.engine.render_to_string("comment-tag04") + self.assertEqual(output, "foo") - @setup({'comment-tag05': 'foo{% comment %} {% somerandomtag %} {% endcomment %}'}) + @setup({"comment-tag05": "foo{% comment %} {% somerandomtag %} {% endcomment %}"}) def test_comment_tag05(self): - output = self.engine.render_to_string('comment-tag05') - self.assertEqual(output, 'foo') + output = self.engine.render_to_string("comment-tag05") + self.assertEqual(output, "foo") diff --git a/tests/template_tests/syntax_tests/test_cycle.py b/tests/template_tests/syntax_tests/test_cycle.py index 12bf66e117..d4233fac3e 100644 --- a/tests/template_tests/syntax_tests/test_cycle.py +++ b/tests/template_tests/syntax_tests/test_cycle.py @@ -5,175 +5,214 @@ from ..utils import setup class CycleTagTests(SimpleTestCase): - - @setup({'cycle01': '{% cycle a %}'}) + @setup({"cycle01": "{% cycle a %}"}) def test_cycle01(self): msg = "No named cycles in template. 'a' is not defined" with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.get_template('cycle01') + self.engine.get_template("cycle01") - @setup({'cycle05': '{% cycle %}'}) + @setup({"cycle05": "{% cycle %}"}) def test_cycle05(self): msg = "'cycle' tag requires at least two arguments" with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.get_template('cycle05') + self.engine.get_template("cycle05") - @setup({'cycle07': '{% cycle a,b,c as foo %}{% cycle bar %}'}) + @setup({"cycle07": "{% cycle a,b,c as foo %}{% cycle bar %}"}) def test_cycle07(self): msg = "Could not parse the remainder: ',b,c' from 'a,b,c'" with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.get_template('cycle07') + self.engine.get_template("cycle07") - @setup({'cycle10': "{% cycle 'a' 'b' 'c' as abc %}{% cycle abc %}"}) + @setup({"cycle10": "{% cycle 'a' 'b' 'c' as abc %}{% cycle abc %}"}) def test_cycle10(self): - output = self.engine.render_to_string('cycle10') - self.assertEqual(output, 'ab') + output = self.engine.render_to_string("cycle10") + self.assertEqual(output, "ab") - @setup({'cycle11': "{% cycle 'a' 'b' 'c' as abc %}{% cycle abc %}{% cycle abc %}"}) + @setup({"cycle11": "{% cycle 'a' 'b' 'c' as abc %}{% cycle abc %}{% cycle abc %}"}) def test_cycle11(self): - output = self.engine.render_to_string('cycle11') - self.assertEqual(output, 'abc') + output = self.engine.render_to_string("cycle11") + self.assertEqual(output, "abc") - @setup({'cycle12': "{% cycle 'a' 'b' 'c' as abc %}{% cycle abc %}{% cycle abc %}{% cycle abc %}"}) + @setup( + { + "cycle12": "{% cycle 'a' 'b' 'c' as abc %}{% cycle abc %}{% cycle abc %}{% cycle abc %}" + } + ) def test_cycle12(self): - output = self.engine.render_to_string('cycle12') - self.assertEqual(output, 'abca') + output = self.engine.render_to_string("cycle12") + self.assertEqual(output, "abca") - @setup({'cycle13': "{% for i in test %}{% cycle 'a' 'b' %}{{ i }},{% endfor %}"}) + @setup({"cycle13": "{% for i in test %}{% cycle 'a' 'b' %}{{ i }},{% endfor %}"}) def test_cycle13(self): - output = self.engine.render_to_string('cycle13', {'test': list(range(5))}) - self.assertEqual(output, 'a0,b1,a2,b3,a4,') + output = self.engine.render_to_string("cycle13", {"test": list(range(5))}) + self.assertEqual(output, "a0,b1,a2,b3,a4,") - @setup({'cycle14': '{% cycle one two as foo %}{% cycle foo %}'}) + @setup({"cycle14": "{% cycle one two as foo %}{% cycle foo %}"}) def test_cycle14(self): - output = self.engine.render_to_string('cycle14', {'one': '1', 'two': '2'}) - self.assertEqual(output, '12') + output = self.engine.render_to_string("cycle14", {"one": "1", "two": "2"}) + self.assertEqual(output, "12") - @setup({'cycle15': '{% for i in test %}{% cycle aye bee %}{{ i }},{% endfor %}'}) + @setup({"cycle15": "{% for i in test %}{% cycle aye bee %}{{ i }},{% endfor %}"}) def test_cycle15(self): - output = self.engine.render_to_string('cycle15', {'test': list(range(5)), 'aye': 'a', 'bee': 'b'}) - self.assertEqual(output, 'a0,b1,a2,b3,a4,') + output = self.engine.render_to_string( + "cycle15", {"test": list(range(5)), "aye": "a", "bee": "b"} + ) + self.assertEqual(output, "a0,b1,a2,b3,a4,") - @setup({'cycle16': '{% cycle one|lower two as foo %}{% cycle foo %}'}) + @setup({"cycle16": "{% cycle one|lower two as foo %}{% cycle foo %}"}) def test_cycle16(self): - output = self.engine.render_to_string('cycle16', {'one': 'A', 'two': '2'}) - self.assertEqual(output, 'a2') + output = self.engine.render_to_string("cycle16", {"one": "A", "two": "2"}) + self.assertEqual(output, "a2") - @setup({'cycle17': "{% cycle 'a' 'b' 'c' as abc silent %}" - "{% cycle abc %}{% cycle abc %}{% cycle abc %}{% cycle abc %}"}) + @setup( + { + "cycle17": "{% cycle 'a' 'b' 'c' as abc silent %}" + "{% cycle abc %}{% cycle abc %}{% cycle abc %}{% cycle abc %}" + } + ) def test_cycle17(self): - output = self.engine.render_to_string('cycle17') - self.assertEqual(output, '') + output = self.engine.render_to_string("cycle17") + self.assertEqual(output, "") - @setup({'cycle18': "{% cycle 'a' 'b' 'c' as foo invalid_flag %}"}) + @setup({"cycle18": "{% cycle 'a' 'b' 'c' as foo invalid_flag %}"}) def test_cycle18(self): msg = "Only 'silent' flag is allowed after cycle's name, not 'invalid_flag'." with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.get_template('cycle18') + self.engine.get_template("cycle18") - @setup({'cycle19': "{% cycle 'a' 'b' as silent %}{% cycle silent %}"}) + @setup({"cycle19": "{% cycle 'a' 'b' as silent %}{% cycle silent %}"}) def test_cycle19(self): - output = self.engine.render_to_string('cycle19') - self.assertEqual(output, 'ab') + output = self.engine.render_to_string("cycle19") + self.assertEqual(output, "ab") - @setup({'cycle20': '{% cycle one two as foo %} & {% cycle foo %}'}) + @setup({"cycle20": "{% cycle one two as foo %} & {% cycle foo %}"}) def test_cycle20(self): - output = self.engine.render_to_string('cycle20', {'two': 'C & D', 'one': 'A & B'}) - self.assertEqual(output, 'A & B & C & D') + output = self.engine.render_to_string( + "cycle20", {"two": "C & D", "one": "A & B"} + ) + self.assertEqual(output, "A & B & C & D") - @setup({'cycle21': '{% filter force_escape %}' - '{% cycle one two as foo %} & {% cycle foo %}{% endfilter %}'}) + @setup( + { + "cycle21": "{% filter force_escape %}" + "{% cycle one two as foo %} & {% cycle foo %}{% endfilter %}" + } + ) def test_cycle21(self): - output = self.engine.render_to_string('cycle21', {'two': 'C & D', 'one': 'A & B'}) - self.assertEqual(output, 'A &amp; B & C &amp; D') + output = self.engine.render_to_string( + "cycle21", {"two": "C & D", "one": "A & B"} + ) + self.assertEqual(output, "A &amp; B & C &amp; D") - @setup({'cycle22': "{% for x in values %}{% cycle 'a' 'b' 'c' as abc silent %}{{ x }}{% endfor %}"}) + @setup( + { + "cycle22": "{% for x in values %}{% cycle 'a' 'b' 'c' as abc silent %}{{ x }}{% endfor %}" + } + ) def test_cycle22(self): - output = self.engine.render_to_string('cycle22', {'values': [1, 2, 3, 4]}) - self.assertEqual(output, '1234') + output = self.engine.render_to_string("cycle22", {"values": [1, 2, 3, 4]}) + self.assertEqual(output, "1234") - @setup({'cycle23': "{% for x in values %}" - "{% cycle 'a' 'b' 'c' as abc silent %}{{ abc }}{{ x }}{% endfor %}"}) + @setup( + { + "cycle23": "{% for x in values %}" + "{% cycle 'a' 'b' 'c' as abc silent %}{{ abc }}{{ x }}{% endfor %}" + } + ) def test_cycle23(self): - output = self.engine.render_to_string('cycle23', {'values': [1, 2, 3, 4]}) - self.assertEqual(output, 'a1b2c3a4') + output = self.engine.render_to_string("cycle23", {"values": [1, 2, 3, 4]}) + self.assertEqual(output, "a1b2c3a4") - @setup({ - 'cycle24': "{% for x in values %}" - "{% cycle 'a' 'b' 'c' as abc silent %}{% include 'included-cycle' %}{% endfor %}", - 'included-cycle': '{{ abc }}', - }) + @setup( + { + "cycle24": "{% for x in values %}" + "{% cycle 'a' 'b' 'c' as abc silent %}{% include 'included-cycle' %}{% endfor %}", + "included-cycle": "{{ abc }}", + } + ) def test_cycle24(self): - output = self.engine.render_to_string('cycle24', {'values': [1, 2, 3, 4]}) - self.assertEqual(output, 'abca') + output = self.engine.render_to_string("cycle24", {"values": [1, 2, 3, 4]}) + self.assertEqual(output, "abca") - @setup({'cycle25': '{% cycle a as abc %}'}) + @setup({"cycle25": "{% cycle a as abc %}"}) def test_cycle25(self): - output = self.engine.render_to_string('cycle25', {'a': '<'}) - self.assertEqual(output, '<') + output = self.engine.render_to_string("cycle25", {"a": "<"}) + self.assertEqual(output, "<") - @setup({'cycle26': '{% cycle a b as ab %}{% cycle ab %}'}) + @setup({"cycle26": "{% cycle a b as ab %}{% cycle ab %}"}) def test_cycle26(self): - output = self.engine.render_to_string('cycle26', {'a': '<', 'b': '>'}) - self.assertEqual(output, '<>') + output = self.engine.render_to_string("cycle26", {"a": "<", "b": ">"}) + self.assertEqual(output, "<>") - @setup({'cycle27': '{% autoescape off %}{% cycle a b as ab %}{% cycle ab %}{% endautoescape %}'}) + @setup( + { + "cycle27": "{% autoescape off %}{% cycle a b as ab %}{% cycle ab %}{% endautoescape %}" + } + ) def test_cycle27(self): - output = self.engine.render_to_string('cycle27', {'a': '<', 'b': '>'}) - self.assertEqual(output, '<>') + output = self.engine.render_to_string("cycle27", {"a": "<", "b": ">"}) + self.assertEqual(output, "<>") - @setup({'cycle28': '{% cycle a|safe b as ab %}{% cycle ab %}'}) + @setup({"cycle28": "{% cycle a|safe b as ab %}{% cycle ab %}"}) def test_cycle28(self): - output = self.engine.render_to_string('cycle28', {'a': '<', 'b': '>'}) - self.assertEqual(output, '<>') + output = self.engine.render_to_string("cycle28", {"a": "<", "b": ">"}) + self.assertEqual(output, "<>") - @setup({ - 'cycle29': "{% cycle 'a' 'b' 'c' as cycler silent %}" - "{% for x in values %}" - "{% ifchanged x %}" - "{% cycle cycler %}{{ cycler }}" - "{% else %}" - "{{ cycler }}" - "{% endifchanged %}" - "{% endfor %}" - }) + @setup( + { + "cycle29": "{% cycle 'a' 'b' 'c' as cycler silent %}" + "{% for x in values %}" + "{% ifchanged x %}" + "{% cycle cycler %}{{ cycler }}" + "{% else %}" + "{{ cycler }}" + "{% endifchanged %}" + "{% endfor %}" + } + ) def test_cycle29(self): """ A named {% cycle %} tag works inside an {% ifchanged %} block and a {% for %} loop. """ - output = self.engine.render_to_string('cycle29', {'values': [1, 2, 3, 4, 5, 6, 7, 8, 8, 8, 9, 9]}) - self.assertEqual(output, 'bcabcabcccaa') + output = self.engine.render_to_string( + "cycle29", {"values": [1, 2, 3, 4, 5, 6, 7, 8, 8, 8, 9, 9]} + ) + self.assertEqual(output, "bcabcabcccaa") - @setup({ - 'cycle30': "{% cycle 'a' 'b' 'c' as cycler silent %}" - "{% for x in values %}" - "{% with doesnothing=irrelevant %}" - "{% ifchanged x %}" - "{% cycle cycler %}{{ cycler }}" - "{% else %}" - "{{ cycler }}" - "{% endifchanged %}" - "{% endwith %}" - "{% endfor %}"}) + @setup( + { + "cycle30": "{% cycle 'a' 'b' 'c' as cycler silent %}" + "{% for x in values %}" + "{% with doesnothing=irrelevant %}" + "{% ifchanged x %}" + "{% cycle cycler %}{{ cycler }}" + "{% else %}" + "{{ cycler }}" + "{% endifchanged %}" + "{% endwith %}" + "{% endfor %}" + } + ) def test_cycle30(self): """ A {% with %} tag shouldn't reset the {% cycle %} variable. """ output = self.engine.render_to_string( - 'cycle30', { - 'irrelevant': 1, - 'values': [1, 2, 3, 4, 5, 6, 7, 8, 8, 8, 9, 9] - }) - self.assertEqual(output, 'bcabcabcccaa') + "cycle30", {"irrelevant": 1, "values": [1, 2, 3, 4, 5, 6, 7, 8, 8, 8, 9, 9]} + ) + self.assertEqual(output, "bcabcabcccaa") - @setup({ - 'undefined_cycle': - "{% cycle 'a' 'b' 'c' as cycler silent %}" + @setup( + { + "undefined_cycle": "{% cycle 'a' 'b' 'c' as cycler silent %}" "{% for x in values %}" "{% cycle undefined %}{{ cycler }}" "{% endfor %}" - }) + } + ) def test_cycle_undefined(self): - with self.assertRaisesMessage(TemplateSyntaxError, "Named cycle 'undefined' does not exist"): - self.engine.render_to_string('undefined_cycle') + with self.assertRaisesMessage( + TemplateSyntaxError, "Named cycle 'undefined' does not exist" + ): + self.engine.render_to_string("undefined_cycle") diff --git a/tests/template_tests/syntax_tests/test_debug.py b/tests/template_tests/syntax_tests/test_debug.py index 2f527b44ae..cbd71fa51a 100644 --- a/tests/template_tests/syntax_tests/test_debug.py +++ b/tests/template_tests/syntax_tests/test_debug.py @@ -6,41 +6,40 @@ from ..utils import setup @override_settings(DEBUG=True) class DebugTests(SimpleTestCase): - @override_settings(DEBUG=False) - @setup({'non_debug': '{% debug %}'}) + @setup({"non_debug": "{% debug %}"}) def test_non_debug(self): - output = self.engine.render_to_string('non_debug', {}) - self.assertEqual(output, '') + output = self.engine.render_to_string("non_debug", {}) + self.assertEqual(output, "") - @setup({'modules': '{% debug %}'}) + @setup({"modules": "{% debug %}"}) def test_modules(self): - output = self.engine.render_to_string('modules', {}) + output = self.engine.render_to_string("modules", {}) self.assertIn( - ''django': <module 'django' ', + "'django': <module 'django' ", output, ) - @setup({'plain': '{% debug %}'}) + @setup({"plain": "{% debug %}"}) def test_plain(self): - output = self.engine.render_to_string('plain', {'a': 1}) - self.assertTrue(output.startswith( - '{'a': 1}' - '{'False': False, 'None': None, ' - ''True': True}\n\n{' - )) + output = self.engine.render_to_string("plain", {"a": 1}) + self.assertTrue( + output.startswith( + "{'a': 1}" + "{'False': False, 'None': None, " + "'True': True}\n\n{" + ) + ) - @setup({'non_ascii': '{% debug %}'}) + @setup({"non_ascii": "{% debug %}"}) def test_non_ascii(self): group = Group(name="清風") - output = self.engine.render_to_string('non_ascii', {'group': group}) - self.assertTrue(output.startswith( - '{'group': <Group: 清風>}' - )) + output = self.engine.render_to_string("non_ascii", {"group": group}) + self.assertTrue(output.startswith("{'group': <Group: 清風>}")) - @setup({'script': '{% debug %}'}) + @setup({"script": "{% debug %}"}) def test_script(self): - output = self.engine.render_to_string('script', {'frag': '<script>'}) - self.assertTrue(output.startswith( - '{'frag': '<script>'}' - )) + output = self.engine.render_to_string("script", {"frag": "<script>"}) + self.assertTrue( + output.startswith("{'frag': '<script>'}") + ) diff --git a/tests/template_tests/syntax_tests/test_exceptions.py b/tests/template_tests/syntax_tests/test_exceptions.py index db1e0f9f5f..7000b45afd 100644 --- a/tests/template_tests/syntax_tests/test_exceptions.py +++ b/tests/template_tests/syntax_tests/test_exceptions.py @@ -6,30 +6,31 @@ from .test_extends import inheritance_templates class ExceptionsTests(SimpleTestCase): - - @setup({'exception01': "{% extends 'nonexistent' %}"}) + @setup({"exception01": "{% extends 'nonexistent' %}"}) def test_exception01(self): """ Raise exception for invalid template name """ with self.assertRaises(TemplateDoesNotExist): - self.engine.render_to_string('exception01') + self.engine.render_to_string("exception01") - @setup({'exception02': '{% extends nonexistent %}'}) + @setup({"exception02": "{% extends nonexistent %}"}) def test_exception02(self): """ Raise exception for invalid variable template name """ if self.engine.string_if_invalid: with self.assertRaises(TemplateDoesNotExist): - self.engine.render_to_string('exception02') + self.engine.render_to_string("exception02") else: with self.assertRaises(TemplateSyntaxError): - self.engine.render_to_string('exception02') + self.engine.render_to_string("exception02") @setup( - {'exception03': "{% extends 'inheritance01' %}" - "{% block first %}2{% endblock %}{% extends 'inheritance16' %}"}, + { + "exception03": "{% extends 'inheritance01' %}" + "{% block first %}2{% endblock %}{% extends 'inheritance16' %}" + }, inheritance_templates, ) def test_exception03(self): @@ -37,10 +38,12 @@ class ExceptionsTests(SimpleTestCase): Raise exception for extra {% extends %} tags """ with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('exception03') + self.engine.get_template("exception03") @setup( - {'exception04': "{% extends 'inheritance17' %}{% block first %}{% echo 400 %}5678{% endblock %}"}, + { + "exception04": "{% extends 'inheritance17' %}{% block first %}{% echo 400 %}5678{% endblock %}" + }, inheritance_templates, ) def test_exception04(self): @@ -48,12 +51,12 @@ class ExceptionsTests(SimpleTestCase): Raise exception for custom tags used in child with {% load %} tag in parent, not in child """ with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('exception04') + self.engine.get_template("exception04") - @setup({'exception05': '{% block first %}{{ block.super }}{% endblock %}'}) + @setup({"exception05": "{% block first %}{{ block.super }}{% endblock %}"}) def test_exception05(self): """ Raise exception for block.super used in base template """ with self.assertRaises(TemplateSyntaxError): - self.engine.render_to_string('exception05') + self.engine.render_to_string("exception05") diff --git a/tests/template_tests/syntax_tests/test_extends.py b/tests/template_tests/syntax_tests/test_extends.py index 0689838ae8..ce073fb909 100644 --- a/tests/template_tests/syntax_tests/test_extends.py +++ b/tests/template_tests/syntax_tests/test_extends.py @@ -6,119 +6,119 @@ from django.test import SimpleTestCase from ..utils import setup inheritance_templates = { - 'inheritance01': "1{% block first %}&{% endblock %}3{% block second %}_{% endblock %}", - 'inheritance02': "{% extends 'inheritance01' %}" - "{% block first %}2{% endblock %}{% block second %}4{% endblock %}", - 'inheritance03': "{% extends 'inheritance02' %}", - 'inheritance04': "{% extends 'inheritance01' %}", - 'inheritance05': "{% extends 'inheritance02' %}", - 'inheritance06': "{% extends foo %}", - 'inheritance07': "{% extends 'inheritance01' %}{% block second %}5{% endblock %}", - 'inheritance08': "{% extends 'inheritance02' %}{% block second %}5{% endblock %}", - 'inheritance09': "{% extends 'inheritance04' %}", - 'inheritance10': "{% extends 'inheritance04' %} ", - 'inheritance11': "{% extends 'inheritance04' %}" - "{% block first %}2{% endblock %}{% block second %}4{% endblock %}", - 'inheritance12': "{% extends 'inheritance07' %}{% block first %}2{% endblock %}", - 'inheritance13': "{% extends 'inheritance02' %}" - "{% block first %}a{% endblock %}{% block second %}b{% endblock %}", - 'inheritance14': "{% extends 'inheritance01' %}{% block newblock %}NO DISPLAY{% endblock %}", - 'inheritance15': "{% extends 'inheritance01' %}" - "{% block first %}2{% block inner %}inner{% endblock %}{% endblock %}", - 'inheritance16': "{% extends 'inheritance15' %}{% block inner %}out{% endblock %}", - 'inheritance17': "{% load testtags %}{% block first %}1234{% endblock %}", - 'inheritance18': "{% load testtags %}{% echo this that theother %}5678", - 'inheritance19': "{% extends 'inheritance01' %}" - "{% block first %}{% load testtags %}{% echo 400 %}5678{% endblock %}", - 'inheritance20': "{% extends 'inheritance01' %}{% block first %}{{ block.super }}a{% endblock %}", - 'inheritance21': "{% extends 'inheritance02' %}{% block first %}{{ block.super }}a{% endblock %}", - 'inheritance22': "{% extends 'inheritance04' %}{% block first %}{{ block.super }}a{% endblock %}", - 'inheritance23': "{% extends 'inheritance20' %}{% block first %}{{ block.super }}b{% endblock %}", - 'inheritance24': "{% extends context_template %}" - "{% block first %}2{% endblock %}{% block second %}4{% endblock %}", - 'inheritance25': "{% extends context_template.1 %}" - "{% block first %}2{% endblock %}{% block second %}4{% endblock %}", - 'inheritance26': "no tags", - 'inheritance27': "{% extends 'inheritance26' %}", - 'inheritance 28': "{% block first %}!{% endblock %}", - 'inheritance29': "{% extends 'inheritance 28' %}", - 'inheritance30': "1{% if optional %}{% block opt %}2{% endblock %}{% endif %}3", - 'inheritance31': "{% extends 'inheritance30' %}{% block opt %}two{% endblock %}", - 'inheritance32': "{% extends 'inheritance30' %}{% block opt %}two{% endblock %}", - 'inheritance33': "1{% if optional == 1 %}{% block opt %}2{% endblock %}{% endif %}3", - 'inheritance34': "{% extends 'inheritance33' %}{% block opt %}two{% endblock %}", - 'inheritance35': "{% extends 'inheritance33' %}{% block opt %}two{% endblock %}", - 'inheritance36': "{% for n in numbers %}_{% block opt %}{{ n }}{% endblock %}{% endfor %}_", - 'inheritance37': "{% extends 'inheritance36' %}{% block opt %}X{% endblock %}", - 'inheritance38': "{% extends 'inheritance36' %}{% block opt %}X{% endblock %}", - 'inheritance39': "{% extends 'inheritance30' %}{% block opt %}new{{ block.super }}{% endblock %}", - 'inheritance40': "{% extends 'inheritance33' %}{% block opt %}new{{ block.super }}{% endblock %}", - 'inheritance41': "{% extends 'inheritance36' %}{% block opt %}new{{ block.super }}{% endblock %}", - 'inheritance42': "{% extends 'inheritance02'|cut:' ' %}", - 'inheritance_empty': "{% extends %}", - 'extends_duplicate': "{% extends 'base.html' %}{% extends 'base.html' %}", - 'duplicate_block': "{% extends 'base.html' %}{% block content %}2{% endblock %}{% block content %}4{% endblock %}", + "inheritance01": "1{% block first %}&{% endblock %}3{% block second %}_{% endblock %}", + "inheritance02": "{% extends 'inheritance01' %}" + "{% block first %}2{% endblock %}{% block second %}4{% endblock %}", + "inheritance03": "{% extends 'inheritance02' %}", + "inheritance04": "{% extends 'inheritance01' %}", + "inheritance05": "{% extends 'inheritance02' %}", + "inheritance06": "{% extends foo %}", + "inheritance07": "{% extends 'inheritance01' %}{% block second %}5{% endblock %}", + "inheritance08": "{% extends 'inheritance02' %}{% block second %}5{% endblock %}", + "inheritance09": "{% extends 'inheritance04' %}", + "inheritance10": "{% extends 'inheritance04' %} ", + "inheritance11": "{% extends 'inheritance04' %}" + "{% block first %}2{% endblock %}{% block second %}4{% endblock %}", + "inheritance12": "{% extends 'inheritance07' %}{% block first %}2{% endblock %}", + "inheritance13": "{% extends 'inheritance02' %}" + "{% block first %}a{% endblock %}{% block second %}b{% endblock %}", + "inheritance14": "{% extends 'inheritance01' %}{% block newblock %}NO DISPLAY{% endblock %}", + "inheritance15": "{% extends 'inheritance01' %}" + "{% block first %}2{% block inner %}inner{% endblock %}{% endblock %}", + "inheritance16": "{% extends 'inheritance15' %}{% block inner %}out{% endblock %}", + "inheritance17": "{% load testtags %}{% block first %}1234{% endblock %}", + "inheritance18": "{% load testtags %}{% echo this that theother %}5678", + "inheritance19": "{% extends 'inheritance01' %}" + "{% block first %}{% load testtags %}{% echo 400 %}5678{% endblock %}", + "inheritance20": "{% extends 'inheritance01' %}{% block first %}{{ block.super }}a{% endblock %}", + "inheritance21": "{% extends 'inheritance02' %}{% block first %}{{ block.super }}a{% endblock %}", + "inheritance22": "{% extends 'inheritance04' %}{% block first %}{{ block.super }}a{% endblock %}", + "inheritance23": "{% extends 'inheritance20' %}{% block first %}{{ block.super }}b{% endblock %}", + "inheritance24": "{% extends context_template %}" + "{% block first %}2{% endblock %}{% block second %}4{% endblock %}", + "inheritance25": "{% extends context_template.1 %}" + "{% block first %}2{% endblock %}{% block second %}4{% endblock %}", + "inheritance26": "no tags", + "inheritance27": "{% extends 'inheritance26' %}", + "inheritance 28": "{% block first %}!{% endblock %}", + "inheritance29": "{% extends 'inheritance 28' %}", + "inheritance30": "1{% if optional %}{% block opt %}2{% endblock %}{% endif %}3", + "inheritance31": "{% extends 'inheritance30' %}{% block opt %}two{% endblock %}", + "inheritance32": "{% extends 'inheritance30' %}{% block opt %}two{% endblock %}", + "inheritance33": "1{% if optional == 1 %}{% block opt %}2{% endblock %}{% endif %}3", + "inheritance34": "{% extends 'inheritance33' %}{% block opt %}two{% endblock %}", + "inheritance35": "{% extends 'inheritance33' %}{% block opt %}two{% endblock %}", + "inheritance36": "{% for n in numbers %}_{% block opt %}{{ n }}{% endblock %}{% endfor %}_", + "inheritance37": "{% extends 'inheritance36' %}{% block opt %}X{% endblock %}", + "inheritance38": "{% extends 'inheritance36' %}{% block opt %}X{% endblock %}", + "inheritance39": "{% extends 'inheritance30' %}{% block opt %}new{{ block.super }}{% endblock %}", + "inheritance40": "{% extends 'inheritance33' %}{% block opt %}new{{ block.super }}{% endblock %}", + "inheritance41": "{% extends 'inheritance36' %}{% block opt %}new{{ block.super }}{% endblock %}", + "inheritance42": "{% extends 'inheritance02'|cut:' ' %}", + "inheritance_empty": "{% extends %}", + "extends_duplicate": "{% extends 'base.html' %}{% extends 'base.html' %}", + "duplicate_block": "{% extends 'base.html' %}{% block content %}2{% endblock %}{% block content %}4{% endblock %}", } class InheritanceTests(SimpleTestCase): - libraries = {'testtags': 'template_tests.templatetags.testtags'} + libraries = {"testtags": "template_tests.templatetags.testtags"} @setup(inheritance_templates) def test_inheritance01(self): """ Standard template with no inheritance """ - output = self.engine.render_to_string('inheritance01') - self.assertEqual(output, '1&3_') + output = self.engine.render_to_string("inheritance01") + self.assertEqual(output, "1&3_") @setup(inheritance_templates) def test_inheritance02(self): """ Standard two-level inheritance """ - output = self.engine.render_to_string('inheritance02') - self.assertEqual(output, '1234') + output = self.engine.render_to_string("inheritance02") + self.assertEqual(output, "1234") @setup(inheritance_templates) def test_inheritance03(self): """ Three-level with no redefinitions on third level """ - output = self.engine.render_to_string('inheritance03') - self.assertEqual(output, '1234') + output = self.engine.render_to_string("inheritance03") + self.assertEqual(output, "1234") @setup(inheritance_templates) def test_inheritance04(self): """ Two-level with no redefinitions on second level """ - output = self.engine.render_to_string('inheritance04') - self.assertEqual(output, '1&3_') + output = self.engine.render_to_string("inheritance04") + self.assertEqual(output, "1&3_") @setup(inheritance_templates) def test_inheritance05(self): """ Two-level with double quotes instead of single quotes """ - output = self.engine.render_to_string('inheritance05') - self.assertEqual(output, '1234') + output = self.engine.render_to_string("inheritance05") + self.assertEqual(output, "1234") @setup(inheritance_templates) def test_inheritance06(self): """ Three-level with variable parent-template name """ - output = self.engine.render_to_string('inheritance06', {'foo': 'inheritance02'}) - self.assertEqual(output, '1234') + output = self.engine.render_to_string("inheritance06", {"foo": "inheritance02"}) + self.assertEqual(output, "1234") @setup(inheritance_templates) def test_inheritance07(self): """ Two-level with one block defined, one block not defined """ - output = self.engine.render_to_string('inheritance07') - self.assertEqual(output, '1&35') + output = self.engine.render_to_string("inheritance07") + self.assertEqual(output, "1&35") @setup(inheritance_templates) def test_inheritance08(self): @@ -126,24 +126,24 @@ class InheritanceTests(SimpleTestCase): Three-level with one block defined on this level, two blocks defined next level """ - output = self.engine.render_to_string('inheritance08') - self.assertEqual(output, '1235') + output = self.engine.render_to_string("inheritance08") + self.assertEqual(output, "1235") @setup(inheritance_templates) def test_inheritance09(self): """ Three-level with second and third levels blank """ - output = self.engine.render_to_string('inheritance09') - self.assertEqual(output, '1&3_') + output = self.engine.render_to_string("inheritance09") + self.assertEqual(output, "1&3_") @setup(inheritance_templates) def test_inheritance10(self): """ Three-level with space NOT in a block -- should be ignored """ - output = self.engine.render_to_string('inheritance10') - self.assertEqual(output, '1&3_') + output = self.engine.render_to_string("inheritance10") + self.assertEqual(output, "1&3_") @setup(inheritance_templates) def test_inheritance11(self): @@ -151,8 +151,8 @@ class InheritanceTests(SimpleTestCase): Three-level with both blocks defined on this level, but none on second level """ - output = self.engine.render_to_string('inheritance11') - self.assertEqual(output, '1234') + output = self.engine.render_to_string("inheritance11") + self.assertEqual(output, "1234") @setup(inheritance_templates) def test_inheritance12(self): @@ -160,88 +160,88 @@ class InheritanceTests(SimpleTestCase): Three-level with this level providing one and second level providing the other """ - output = self.engine.render_to_string('inheritance12') - self.assertEqual(output, '1235') + output = self.engine.render_to_string("inheritance12") + self.assertEqual(output, "1235") @setup(inheritance_templates) def test_inheritance13(self): """ Three-level with this level overriding second level """ - output = self.engine.render_to_string('inheritance13') - self.assertEqual(output, '1a3b') + output = self.engine.render_to_string("inheritance13") + self.assertEqual(output, "1a3b") @setup(inheritance_templates) def test_inheritance14(self): """ A block defined only in a child template shouldn't be displayed """ - output = self.engine.render_to_string('inheritance14') - self.assertEqual(output, '1&3_') + output = self.engine.render_to_string("inheritance14") + self.assertEqual(output, "1&3_") @setup(inheritance_templates) def test_inheritance15(self): """ A block within another block """ - output = self.engine.render_to_string('inheritance15') - self.assertEqual(output, '12inner3_') + output = self.engine.render_to_string("inheritance15") + self.assertEqual(output, "12inner3_") @setup(inheritance_templates) def test_inheritance16(self): """ A block within another block (level 2) """ - output = self.engine.render_to_string('inheritance16') - self.assertEqual(output, '12out3_') + output = self.engine.render_to_string("inheritance16") + self.assertEqual(output, "12out3_") @setup(inheritance_templates) def test_inheritance17(self): """ {% load %} tag (parent -- setup for exception04) """ - output = self.engine.render_to_string('inheritance17') - self.assertEqual(output, '1234') + output = self.engine.render_to_string("inheritance17") + self.assertEqual(output, "1234") @setup(inheritance_templates) def test_inheritance18(self): """ {% load %} tag (standard usage, without inheritance) """ - output = self.engine.render_to_string('inheritance18') - self.assertEqual(output, 'this that theother5678') + output = self.engine.render_to_string("inheritance18") + self.assertEqual(output, "this that theother5678") @setup(inheritance_templates) def test_inheritance19(self): """ {% load %} tag (within a child template) """ - output = self.engine.render_to_string('inheritance19') - self.assertEqual(output, '140056783_') + output = self.engine.render_to_string("inheritance19") + self.assertEqual(output, "140056783_") @setup(inheritance_templates) def test_inheritance20(self): """ Two-level inheritance with {{ block.super }} """ - output = self.engine.render_to_string('inheritance20') - self.assertEqual(output, '1&a3_') + output = self.engine.render_to_string("inheritance20") + self.assertEqual(output, "1&a3_") @setup(inheritance_templates) def test_inheritance21(self): """ Three-level inheritance with {{ block.super }} from parent """ - output = self.engine.render_to_string('inheritance21') - self.assertEqual(output, '12a34') + output = self.engine.render_to_string("inheritance21") + self.assertEqual(output, "12a34") @setup(inheritance_templates) def test_inheritance22(self): """ Three-level inheritance with {{ block.super }} from grandparent """ - output = self.engine.render_to_string('inheritance22') - self.assertEqual(output, '1&a3_') + output = self.engine.render_to_string("inheritance22") + self.assertEqual(output, "1&a3_") @setup(inheritance_templates) def test_inheritance23(self): @@ -249,8 +249,8 @@ class InheritanceTests(SimpleTestCase): Three-level inheritance with {{ block.super }} from parent and grandparent """ - output = self.engine.render_to_string('inheritance23') - self.assertEqual(output, '1&ab3_') + output = self.engine.render_to_string("inheritance23") + self.assertEqual(output, "1&ab3_") @setup(inheritance_templates) def test_inheritance24(self): @@ -260,8 +260,10 @@ class InheritanceTests(SimpleTestCase): context_template = self.engine.from_string( "1{% block first %}_{% endblock %}3{% block second %}_{% endblock %}" ) - output = self.engine.render_to_string('inheritance24', {'context_template': context_template}) - self.assertEqual(output, '1234') + output = self.engine.render_to_string( + "inheritance24", {"context_template": context_template} + ) + self.assertEqual(output, "1234") @setup(inheritance_templates) def test_inheritance25(self): @@ -270,70 +272,74 @@ class InheritanceTests(SimpleTestCase): """ context_template = [ self.engine.from_string("Wrong"), - self.engine.from_string("1{% block first %}_{% endblock %}3{% block second %}_{% endblock %}"), + self.engine.from_string( + "1{% block first %}_{% endblock %}3{% block second %}_{% endblock %}" + ), ] - output = self.engine.render_to_string('inheritance25', {'context_template': context_template}) - self.assertEqual(output, '1234') + output = self.engine.render_to_string( + "inheritance25", {"context_template": context_template} + ) + self.assertEqual(output, "1234") @setup(inheritance_templates) def test_inheritance26(self): """ Set up a base template to extend """ - output = self.engine.render_to_string('inheritance26') - self.assertEqual(output, 'no tags') + output = self.engine.render_to_string("inheritance26") + self.assertEqual(output, "no tags") @setup(inheritance_templates) def test_inheritance27(self): """ Inheritance from a template that doesn't have any blocks """ - output = self.engine.render_to_string('inheritance27') - self.assertEqual(output, 'no tags') + output = self.engine.render_to_string("inheritance27") + self.assertEqual(output, "no tags") @setup(inheritance_templates) def test_inheritance_28(self): """ Set up a base template with a space in it. """ - output = self.engine.render_to_string('inheritance 28') - self.assertEqual(output, '!') + output = self.engine.render_to_string("inheritance 28") + self.assertEqual(output, "!") @setup(inheritance_templates) def test_inheritance29(self): """ Inheritance from a template with a space in its name should work. """ - output = self.engine.render_to_string('inheritance29') - self.assertEqual(output, '!') + output = self.engine.render_to_string("inheritance29") + self.assertEqual(output, "!") @setup(inheritance_templates) def test_inheritance30(self): """ Base template, putting block in a conditional {% if %} tag """ - output = self.engine.render_to_string('inheritance30', {'optional': True}) - self.assertEqual(output, '123') + output = self.engine.render_to_string("inheritance30", {"optional": True}) + self.assertEqual(output, "123") # Inherit from a template with block wrapped in an {% if %} tag # (in parent), still gets overridden @setup(inheritance_templates) def test_inheritance31(self): - output = self.engine.render_to_string('inheritance31', {'optional': True}) - self.assertEqual(output, '1two3') + output = self.engine.render_to_string("inheritance31", {"optional": True}) + self.assertEqual(output, "1two3") @setup(inheritance_templates) def test_inheritance32(self): - output = self.engine.render_to_string('inheritance32') - self.assertEqual(output, '13') + output = self.engine.render_to_string("inheritance32") + self.assertEqual(output, "13") @setup(inheritance_templates) def test_inheritance33(self): """ Base template, putting block in a conditional {% if %} tag """ - output = self.engine.render_to_string('inheritance33', {'optional': 1}) - self.assertEqual(output, '123') + output = self.engine.render_to_string("inheritance33", {"optional": 1}) + self.assertEqual(output, "123") @setup(inheritance_templates) def test_inheritance34(self): @@ -341,8 +347,8 @@ class InheritanceTests(SimpleTestCase): Inherit from a template with block wrapped in an {% if %} tag (in parent), still gets overridden """ - output = self.engine.render_to_string('inheritance34', {'optional': 1}) - self.assertEqual(output, '1two3') + output = self.engine.render_to_string("inheritance34", {"optional": 1}) + self.assertEqual(output, "1two3") @setup(inheritance_templates) def test_inheritance35(self): @@ -350,16 +356,16 @@ class InheritanceTests(SimpleTestCase): Inherit from a template with block wrapped in an {% if %} tag (in parent), still gets overridden """ - output = self.engine.render_to_string('inheritance35', {'optional': 2}) - self.assertEqual(output, '13') + output = self.engine.render_to_string("inheritance35", {"optional": 2}) + self.assertEqual(output, "13") @setup(inheritance_templates) def test_inheritance36(self): """ Base template, putting block in a {% for %} tag """ - output = self.engine.render_to_string('inheritance36', {'numbers': '123'}) - self.assertEqual(output, '_1_2_3_') + output = self.engine.render_to_string("inheritance36", {"numbers": "123"}) + self.assertEqual(output, "_1_2_3_") @setup(inheritance_templates) def test_inheritance37(self): @@ -367,8 +373,8 @@ class InheritanceTests(SimpleTestCase): Inherit from a template with block wrapped in an {% for %} tag (in parent), still gets overridden """ - output = self.engine.render_to_string('inheritance37', {'numbers': '123'}) - self.assertEqual(output, '_X_X_X_') + output = self.engine.render_to_string("inheritance37", {"numbers": "123"}) + self.assertEqual(output, "_X_X_X_") @setup(inheritance_templates) def test_inheritance38(self): @@ -376,49 +382,51 @@ class InheritanceTests(SimpleTestCase): Inherit from a template with block wrapped in an {% for %} tag (in parent), still gets overridden """ - output = self.engine.render_to_string('inheritance38') - self.assertEqual(output, '_') + output = self.engine.render_to_string("inheritance38") + self.assertEqual(output, "_") # The super block will still be found. @setup(inheritance_templates) def test_inheritance39(self): - output = self.engine.render_to_string('inheritance39', {'optional': True}) - self.assertEqual(output, '1new23') + output = self.engine.render_to_string("inheritance39", {"optional": True}) + self.assertEqual(output, "1new23") @setup(inheritance_templates) def test_inheritance40(self): - output = self.engine.render_to_string('inheritance40', {'optional': 1}) - self.assertEqual(output, '1new23') + output = self.engine.render_to_string("inheritance40", {"optional": 1}) + self.assertEqual(output, "1new23") @setup(inheritance_templates) def test_inheritance41(self): - output = self.engine.render_to_string('inheritance41', {'numbers': '123'}) - self.assertEqual(output, '_new1_new2_new3_') + output = self.engine.render_to_string("inheritance41", {"numbers": "123"}) + self.assertEqual(output, "_new1_new2_new3_") @setup(inheritance_templates) def test_inheritance42(self): """ Expression starting and ending with a quote """ - output = self.engine.render_to_string('inheritance42') - self.assertEqual(output, '1234') + output = self.engine.render_to_string("inheritance42") + self.assertEqual(output, "1234") @setup(inheritance_templates) def test_inheritance_empty(self): - with self.assertRaisesMessage(TemplateSyntaxError, "'extends' takes one argument"): - self.engine.render_to_string('inheritance_empty') + with self.assertRaisesMessage( + TemplateSyntaxError, "'extends' takes one argument" + ): + self.engine.render_to_string("inheritance_empty") @setup(inheritance_templates) def test_extends_duplicate(self): msg = "'extends' cannot appear more than once in the same template" with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('extends_duplicate') + self.engine.render_to_string("extends_duplicate") @setup(inheritance_templates) def test_duplicate_block(self): msg = "'block' tag with name 'content' appears more than once" with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('duplicate_block') + self.engine.render_to_string("duplicate_block") class ExtendsNodeTests(SimpleTestCase): @@ -428,4 +436,4 @@ class ExtendsNodeTests(SimpleTestCase): parent_name=Node(), template_dirs=[], ) - self.assertEqual(repr(extends_node), '<ExtendsNode: extends None>') + self.assertEqual(repr(extends_node), "<ExtendsNode: extends None>") diff --git a/tests/template_tests/syntax_tests/test_filter_syntax.py b/tests/template_tests/syntax_tests/test_filter_syntax.py index 1d37163d60..5c9128aad8 100644 --- a/tests/template_tests/syntax_tests/test_filter_syntax.py +++ b/tests/template_tests/syntax_tests/test_filter_syntax.py @@ -5,58 +5,65 @@ from ..utils import SomeClass, SomeOtherException, UTF8Class, setup class FilterSyntaxTests(SimpleTestCase): - - @setup({'filter-syntax01': '{{ var|upper }}'}) + @setup({"filter-syntax01": "{{ var|upper }}"}) def test_filter_syntax01(self): """ Basic filter usage """ - output = self.engine.render_to_string('filter-syntax01', {"var": "Django is the greatest!"}) + output = self.engine.render_to_string( + "filter-syntax01", {"var": "Django is the greatest!"} + ) self.assertEqual(output, "DJANGO IS THE GREATEST!") - @setup({'filter-syntax02': '{{ var|upper|lower }}'}) + @setup({"filter-syntax02": "{{ var|upper|lower }}"}) def test_filter_syntax02(self): """ Chained filters """ - output = self.engine.render_to_string('filter-syntax02', {"var": "Django is the greatest!"}) + output = self.engine.render_to_string( + "filter-syntax02", {"var": "Django is the greatest!"} + ) self.assertEqual(output, "django is the greatest!") - @setup({'filter-syntax03': '{{ var |upper }}'}) + @setup({"filter-syntax03": "{{ var |upper }}"}) def test_filter_syntax03(self): """ Allow spaces before the filter pipe """ - output = self.engine.render_to_string('filter-syntax03', {'var': 'Django is the greatest!'}) - self.assertEqual(output, 'DJANGO IS THE GREATEST!') + output = self.engine.render_to_string( + "filter-syntax03", {"var": "Django is the greatest!"} + ) + self.assertEqual(output, "DJANGO IS THE GREATEST!") - @setup({'filter-syntax04': '{{ var| upper }}'}) + @setup({"filter-syntax04": "{{ var| upper }}"}) def test_filter_syntax04(self): """ Allow spaces after the filter pipe """ - output = self.engine.render_to_string('filter-syntax04', {'var': 'Django is the greatest!'}) - self.assertEqual(output, 'DJANGO IS THE GREATEST!') + output = self.engine.render_to_string( + "filter-syntax04", {"var": "Django is the greatest!"} + ) + self.assertEqual(output, "DJANGO IS THE GREATEST!") - @setup({'filter-syntax05': '{{ var|does_not_exist }}'}) + @setup({"filter-syntax05": "{{ var|does_not_exist }}"}) def test_filter_syntax05(self): """ Raise TemplateSyntaxError for a nonexistent filter """ msg = "Invalid filter: 'does_not_exist'" with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.get_template('filter-syntax05') + self.engine.get_template("filter-syntax05") - @setup({'filter-syntax06': '{{ var|fil(ter) }}'}) + @setup({"filter-syntax06": "{{ var|fil(ter) }}"}) def test_filter_syntax06(self): """ Raise TemplateSyntaxError when trying to access a filter containing an illegal character """ with self.assertRaisesMessage(TemplateSyntaxError, "Invalid filter: 'fil'"): - self.engine.get_template('filter-syntax06') + self.engine.get_template("filter-syntax06") - @setup({'filter-syntax07': "{% nothing_to_see_here %}"}) + @setup({"filter-syntax07": "{% nothing_to_see_here %}"}) def test_filter_syntax07(self): """ Raise TemplateSyntaxError for invalid block tags @@ -66,143 +73,149 @@ class FilterSyntaxTests(SimpleTestCase): "forget to register or load this tag?" ) with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.get_template('filter-syntax07') + self.engine.get_template("filter-syntax07") - @setup({'filter-syntax08': "{% %}"}) + @setup({"filter-syntax08": "{% %}"}) def test_filter_syntax08(self): """ Raise TemplateSyntaxError for empty block tags """ - with self.assertRaisesMessage(TemplateSyntaxError, 'Empty block tag on line 1'): - self.engine.get_template('filter-syntax08') + with self.assertRaisesMessage(TemplateSyntaxError, "Empty block tag on line 1"): + self.engine.get_template("filter-syntax08") - @setup({'filter-syntax08-multi-line': "line 1\nline 2\nline 3{% %}\nline 4\nline 5"}) + @setup( + {"filter-syntax08-multi-line": "line 1\nline 2\nline 3{% %}\nline 4\nline 5"} + ) def test_filter_syntax08_multi_line(self): """ Raise TemplateSyntaxError for empty block tags in templates with multiple lines. """ - with self.assertRaisesMessage(TemplateSyntaxError, 'Empty block tag on line 3'): - self.engine.get_template('filter-syntax08-multi-line') + with self.assertRaisesMessage(TemplateSyntaxError, "Empty block tag on line 3"): + self.engine.get_template("filter-syntax08-multi-line") - @setup({'filter-syntax09': '{{ var|cut:"o"|upper|lower }}'}) + @setup({"filter-syntax09": '{{ var|cut:"o"|upper|lower }}'}) def test_filter_syntax09(self): """ Chained filters, with an argument to the first one """ - output = self.engine.render_to_string('filter-syntax09', {'var': 'Foo'}) - self.assertEqual(output, 'f') + output = self.engine.render_to_string("filter-syntax09", {"var": "Foo"}) + self.assertEqual(output, "f") - @setup({'filter-syntax10': r'{{ var|default_if_none:" endquote\" hah" }}'}) + @setup({"filter-syntax10": r'{{ var|default_if_none:" endquote\" hah" }}'}) def test_filter_syntax10(self): """ Literal string as argument is always "safe" from auto-escaping. """ - output = self.engine.render_to_string('filter-syntax10', {"var": None}) + output = self.engine.render_to_string("filter-syntax10", {"var": None}) self.assertEqual(output, ' endquote" hah') - @setup({'filter-syntax11': r'{{ var|default_if_none:var2 }}'}) + @setup({"filter-syntax11": r"{{ var|default_if_none:var2 }}"}) def test_filter_syntax11(self): """ Variable as argument """ - output = self.engine.render_to_string('filter-syntax11', {"var": None, "var2": "happy"}) - self.assertEqual(output, 'happy') + output = self.engine.render_to_string( + "filter-syntax11", {"var": None, "var2": "happy"} + ) + self.assertEqual(output, "happy") - @setup({'filter-syntax13': r'1{{ var.method3 }}2'}) + @setup({"filter-syntax13": r"1{{ var.method3 }}2"}) def test_filter_syntax13(self): """ Fail silently for methods that raise an exception with a `silent_variable_failure` attribute """ - output = self.engine.render_to_string('filter-syntax13', {"var": SomeClass()}) + output = self.engine.render_to_string("filter-syntax13", {"var": SomeClass()}) if self.engine.string_if_invalid: self.assertEqual(output, "1INVALID2") else: self.assertEqual(output, "12") - @setup({'filter-syntax14': r'1{{ var.method4 }}2'}) + @setup({"filter-syntax14": r"1{{ var.method4 }}2"}) def test_filter_syntax14(self): """ In methods that raise an exception without a `silent_variable_attribute` set to True, the exception propagates """ with self.assertRaises(SomeOtherException): - self.engine.render_to_string('filter-syntax14', {"var": SomeClass()}) + self.engine.render_to_string("filter-syntax14", {"var": SomeClass()}) - @setup({'filter-syntax15': r'{{ var|default_if_none:"foo\bar" }}'}) + @setup({"filter-syntax15": r'{{ var|default_if_none:"foo\bar" }}'}) def test_filter_syntax15(self): """ Escaped backslash in argument """ - output = self.engine.render_to_string('filter-syntax15', {"var": None}) - self.assertEqual(output, r'foo\bar') + output = self.engine.render_to_string("filter-syntax15", {"var": None}) + self.assertEqual(output, r"foo\bar") - @setup({'filter-syntax16': r'{{ var|default_if_none:"foo\now" }}'}) + @setup({"filter-syntax16": r'{{ var|default_if_none:"foo\now" }}'}) def test_filter_syntax16(self): """ Escaped backslash using known escape char """ - output = self.engine.render_to_string('filter-syntax16', {"var": None}) - self.assertEqual(output, r'foo\now') + output = self.engine.render_to_string("filter-syntax16", {"var": None}) + self.assertEqual(output, r"foo\now") - @setup({'filter-syntax17': r'{{ var|join:"" }}'}) + @setup({"filter-syntax17": r'{{ var|join:"" }}'}) def test_filter_syntax17(self): """ Empty strings can be passed as arguments to filters """ - output = self.engine.render_to_string('filter-syntax17', {'var': ['a', 'b', 'c']}) - self.assertEqual(output, 'abc') + output = self.engine.render_to_string( + "filter-syntax17", {"var": ["a", "b", "c"]} + ) + self.assertEqual(output, "abc") - @setup({'filter-syntax18': r'{{ var }}'}) + @setup({"filter-syntax18": r"{{ var }}"}) def test_filter_syntax18(self): """ Strings are converted to bytestrings in the final output. """ - output = self.engine.render_to_string('filter-syntax18', {'var': UTF8Class()}) - self.assertEqual(output, '\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111') + output = self.engine.render_to_string("filter-syntax18", {"var": UTF8Class()}) + self.assertEqual(output, "\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111") - @setup({'filter-syntax19': '{{ var|truncatewords:1 }}'}) + @setup({"filter-syntax19": "{{ var|truncatewords:1 }}"}) def test_filter_syntax19(self): """ Numbers as filter arguments should work """ - output = self.engine.render_to_string('filter-syntax19', {"var": "hello world"}) + output = self.engine.render_to_string("filter-syntax19", {"var": "hello world"}) self.assertEqual(output, "hello …") - @setup({'filter-syntax20': '{{ ""|default_if_none:"was none" }}'}) + @setup({"filter-syntax20": '{{ ""|default_if_none:"was none" }}'}) def test_filter_syntax20(self): """ Filters should accept empty string constants """ - output = self.engine.render_to_string('filter-syntax20') + output = self.engine.render_to_string("filter-syntax20") self.assertEqual(output, "") - @setup({'filter-syntax21': r'1{{ var.silent_fail_key }}2'}) + @setup({"filter-syntax21": r"1{{ var.silent_fail_key }}2"}) def test_filter_syntax21(self): """ Fail silently for non-callable attribute and dict lookups which raise an exception with a "silent_variable_failure" attribute """ - output = self.engine.render_to_string('filter-syntax21', {"var": SomeClass()}) + output = self.engine.render_to_string("filter-syntax21", {"var": SomeClass()}) if self.engine.string_if_invalid: self.assertEqual(output, "1INVALID2") else: self.assertEqual(output, "12") - @setup({'filter-syntax22': r'1{{ var.silent_fail_attribute }}2'}) + @setup({"filter-syntax22": r"1{{ var.silent_fail_attribute }}2"}) def test_filter_syntax22(self): """ Fail silently for non-callable attribute and dict lookups which raise an exception with a `silent_variable_failure` attribute """ - output = self.engine.render_to_string('filter-syntax22', {"var": SomeClass()}) + output = self.engine.render_to_string("filter-syntax22", {"var": SomeClass()}) if self.engine.string_if_invalid: self.assertEqual(output, "1INVALID2") else: self.assertEqual(output, "12") - @setup({'filter-syntax23': r'1{{ var.noisy_fail_key }}2'}) + @setup({"filter-syntax23": r"1{{ var.noisy_fail_key }}2"}) def test_filter_syntax23(self): """ In attribute and dict lookups that raise an unexpected exception @@ -210,9 +223,9 @@ class FilterSyntaxTests(SimpleTestCase): propagates """ with self.assertRaises(SomeOtherException): - self.engine.render_to_string('filter-syntax23', {"var": SomeClass()}) + self.engine.render_to_string("filter-syntax23", {"var": SomeClass()}) - @setup({'filter-syntax24': r'1{{ var.noisy_fail_attribute }}2'}) + @setup({"filter-syntax24": r"1{{ var.noisy_fail_attribute }}2"}) def test_filter_syntax24(self): """ In attribute and dict lookups that raise an unexpected exception @@ -220,18 +233,18 @@ class FilterSyntaxTests(SimpleTestCase): propagates """ with self.assertRaises(SomeOtherException): - self.engine.render_to_string('filter-syntax24', {"var": SomeClass()}) + self.engine.render_to_string("filter-syntax24", {"var": SomeClass()}) - @setup({'filter-syntax25': '{{ var.attribute_error_attribute }}'}) + @setup({"filter-syntax25": "{{ var.attribute_error_attribute }}"}) def test_filter_syntax25(self): """ #16383 - Attribute errors from an @property value should be reraised. """ with self.assertRaises(AttributeError): - self.engine.render_to_string('filter-syntax25', {'var': SomeClass()}) + self.engine.render_to_string("filter-syntax25", {"var": SomeClass()}) - @setup({'template': '{{ var.type_error_attribute }}'}) + @setup({"template": "{{ var.type_error_attribute }}"}) def test_type_error_attribute(self): with self.assertRaises(TypeError): - self.engine.render_to_string('template', {'var': SomeClass()}) + self.engine.render_to_string("template", {"var": SomeClass()}) diff --git a/tests/template_tests/syntax_tests/test_filter_tag.py b/tests/template_tests/syntax_tests/test_filter_tag.py index 003140a105..0722fd8b27 100644 --- a/tests/template_tests/syntax_tests/test_filter_tag.py +++ b/tests/template_tests/syntax_tests/test_filter_tag.py @@ -5,43 +5,42 @@ from ..utils import setup class FilterTagTests(SimpleTestCase): - - @setup({'filter01': '{% filter upper %}{% endfilter %}'}) + @setup({"filter01": "{% filter upper %}{% endfilter %}"}) def test_filter01(self): - output = self.engine.render_to_string('filter01') - self.assertEqual(output, '') + output = self.engine.render_to_string("filter01") + self.assertEqual(output, "") - @setup({'filter02': '{% filter upper %}django{% endfilter %}'}) + @setup({"filter02": "{% filter upper %}django{% endfilter %}"}) def test_filter02(self): - output = self.engine.render_to_string('filter02') - self.assertEqual(output, 'DJANGO') + output = self.engine.render_to_string("filter02") + self.assertEqual(output, "DJANGO") - @setup({'filter03': '{% filter upper|lower %}django{% endfilter %}'}) + @setup({"filter03": "{% filter upper|lower %}django{% endfilter %}"}) def test_filter03(self): - output = self.engine.render_to_string('filter03') - self.assertEqual(output, 'django') + output = self.engine.render_to_string("filter03") + self.assertEqual(output, "django") - @setup({'filter04': '{% filter cut:remove %}djangospam{% endfilter %}'}) + @setup({"filter04": "{% filter cut:remove %}djangospam{% endfilter %}"}) def test_filter04(self): - output = self.engine.render_to_string('filter04', {'remove': 'spam'}) - self.assertEqual(output, 'django') + output = self.engine.render_to_string("filter04", {"remove": "spam"}) + self.assertEqual(output, "django") - @setup({'filter05': '{% filter safe %}fail{% endfilter %}'}) + @setup({"filter05": "{% filter safe %}fail{% endfilter %}"}) def test_filter05(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('filter05') + self.engine.get_template("filter05") - @setup({'filter05bis': '{% filter upper|safe %}fail{% endfilter %}'}) + @setup({"filter05bis": "{% filter upper|safe %}fail{% endfilter %}"}) def test_filter05bis(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('filter05bis') + self.engine.get_template("filter05bis") - @setup({'filter06': '{% filter escape %}fail{% endfilter %}'}) + @setup({"filter06": "{% filter escape %}fail{% endfilter %}"}) def test_filter06(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('filter06') + self.engine.get_template("filter06") - @setup({'filter06bis': '{% filter upper|escape %}fail{% endfilter %}'}) + @setup({"filter06bis": "{% filter upper|escape %}fail{% endfilter %}"}) def test_filter06bis(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('filter06bis') + self.engine.get_template("filter06bis") diff --git a/tests/template_tests/syntax_tests/test_firstof.py b/tests/template_tests/syntax_tests/test_firstof.py index cc8df211eb..72f0223d5d 100644 --- a/tests/template_tests/syntax_tests/test_firstof.py +++ b/tests/template_tests/syntax_tests/test_firstof.py @@ -5,87 +5,86 @@ from ..utils import setup class FirstOfTagTests(SimpleTestCase): - - @setup({'firstof01': '{% firstof a b c %}'}) + @setup({"firstof01": "{% firstof a b c %}"}) def test_firstof01(self): - output = self.engine.render_to_string('firstof01', {'a': 0, 'c': 0, 'b': 0}) - self.assertEqual(output, '') + output = self.engine.render_to_string("firstof01", {"a": 0, "c": 0, "b": 0}) + self.assertEqual(output, "") - @setup({'firstof02': '{% firstof a b c %}'}) + @setup({"firstof02": "{% firstof a b c %}"}) def test_firstof02(self): - output = self.engine.render_to_string('firstof02', {'a': 1, 'c': 0, 'b': 0}) - self.assertEqual(output, '1') + output = self.engine.render_to_string("firstof02", {"a": 1, "c": 0, "b": 0}) + self.assertEqual(output, "1") - @setup({'firstof03': '{% firstof a b c %}'}) + @setup({"firstof03": "{% firstof a b c %}"}) def test_firstof03(self): - output = self.engine.render_to_string('firstof03', {'a': 0, 'c': 0, 'b': 2}) - self.assertEqual(output, '2') + output = self.engine.render_to_string("firstof03", {"a": 0, "c": 0, "b": 2}) + self.assertEqual(output, "2") - @setup({'firstof04': '{% firstof a b c %}'}) + @setup({"firstof04": "{% firstof a b c %}"}) def test_firstof04(self): - output = self.engine.render_to_string('firstof04', {'a': 0, 'c': 3, 'b': 0}) - self.assertEqual(output, '3') + output = self.engine.render_to_string("firstof04", {"a": 0, "c": 3, "b": 0}) + self.assertEqual(output, "3") - @setup({'firstof05': '{% firstof a b c %}'}) + @setup({"firstof05": "{% firstof a b c %}"}) def test_firstof05(self): - output = self.engine.render_to_string('firstof05', {'a': 1, 'c': 3, 'b': 2}) - self.assertEqual(output, '1') + output = self.engine.render_to_string("firstof05", {"a": 1, "c": 3, "b": 2}) + self.assertEqual(output, "1") - @setup({'firstof06': '{% firstof a b c %}'}) + @setup({"firstof06": "{% firstof a b c %}"}) def test_firstof06(self): - output = self.engine.render_to_string('firstof06', {'c': 3, 'b': 0}) - self.assertEqual(output, '3') + output = self.engine.render_to_string("firstof06", {"c": 3, "b": 0}) + self.assertEqual(output, "3") - @setup({'firstof07': '{% firstof a b "c" %}'}) + @setup({"firstof07": '{% firstof a b "c" %}'}) def test_firstof07(self): - output = self.engine.render_to_string('firstof07', {'a': 0}) - self.assertEqual(output, 'c') + output = self.engine.render_to_string("firstof07", {"a": 0}) + self.assertEqual(output, "c") - @setup({'firstof08': '{% firstof a b "c and d" %}'}) + @setup({"firstof08": '{% firstof a b "c and d" %}'}) def test_firstof08(self): - output = self.engine.render_to_string('firstof08', {'a': 0, 'b': 0}) - self.assertEqual(output, 'c and d') + output = self.engine.render_to_string("firstof08", {"a": 0, "b": 0}) + self.assertEqual(output, "c and d") - @setup({'firstof09': '{% firstof %}'}) + @setup({"firstof09": "{% firstof %}"}) def test_firstof09(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('firstof09') + self.engine.get_template("firstof09") - @setup({'firstof10': '{% firstof a %}'}) + @setup({"firstof10": "{% firstof a %}"}) def test_firstof10(self): - output = self.engine.render_to_string('firstof10', {'a': '<'}) - self.assertEqual(output, '<') + output = self.engine.render_to_string("firstof10", {"a": "<"}) + self.assertEqual(output, "<") - @setup({'firstof11': '{% firstof a b %}'}) + @setup({"firstof11": "{% firstof a b %}"}) def test_firstof11(self): - output = self.engine.render_to_string('firstof11', {'a': '<', 'b': '>'}) - self.assertEqual(output, '<') + output = self.engine.render_to_string("firstof11", {"a": "<", "b": ">"}) + self.assertEqual(output, "<") - @setup({'firstof12': '{% firstof a b %}'}) + @setup({"firstof12": "{% firstof a b %}"}) def test_firstof12(self): - output = self.engine.render_to_string('firstof12', {'a': '', 'b': '>'}) - self.assertEqual(output, '>') + output = self.engine.render_to_string("firstof12", {"a": "", "b": ">"}) + self.assertEqual(output, ">") - @setup({'firstof13': '{% autoescape off %}{% firstof a %}{% endautoescape %}'}) + @setup({"firstof13": "{% autoescape off %}{% firstof a %}{% endautoescape %}"}) def test_firstof13(self): - output = self.engine.render_to_string('firstof13', {'a': '<'}) - self.assertEqual(output, '<') + output = self.engine.render_to_string("firstof13", {"a": "<"}) + self.assertEqual(output, "<") - @setup({'firstof14': '{% firstof a|safe b %}'}) + @setup({"firstof14": "{% firstof a|safe b %}"}) def test_firstof14(self): - output = self.engine.render_to_string('firstof14', {'a': '<'}) - self.assertEqual(output, '<') + output = self.engine.render_to_string("firstof14", {"a": "<"}) + self.assertEqual(output, "<") - @setup({'firstof15': '{% firstof a b c as myvar %}'}) + @setup({"firstof15": "{% firstof a b c as myvar %}"}) def test_firstof15(self): - ctx = {'a': 0, 'b': 2, 'c': 3} - output = self.engine.render_to_string('firstof15', ctx) - self.assertEqual(ctx['myvar'], '2') - self.assertEqual(output, '') + ctx = {"a": 0, "b": 2, "c": 3} + output = self.engine.render_to_string("firstof15", ctx) + self.assertEqual(ctx["myvar"], "2") + self.assertEqual(output, "") - @setup({'firstof16': '{% firstof a b c as myvar %}'}) + @setup({"firstof16": "{% firstof a b c as myvar %}"}) def test_all_false_arguments_asvar(self): - ctx = {'a': 0, 'b': 0, 'c': 0} - output = self.engine.render_to_string('firstof16', ctx) - self.assertEqual(ctx['myvar'], '') - self.assertEqual(output, '') + ctx = {"a": 0, "b": 0, "c": 0} + output = self.engine.render_to_string("firstof16", ctx) + self.assertEqual(ctx["myvar"], "") + self.assertEqual(output, "") diff --git a/tests/template_tests/syntax_tests/test_for.py b/tests/template_tests/syntax_tests/test_for.py index d7db6108a2..ad1d158f9b 100644 --- a/tests/template_tests/syntax_tests/test_for.py +++ b/tests/template_tests/syntax_tests/test_for.py @@ -6,213 +6,333 @@ from ..utils import setup class ForTagTests(SimpleTestCase): - libraries = {'custom': 'template_tests.templatetags.custom'} + libraries = {"custom": "template_tests.templatetags.custom"} - @setup({'for-tag01': '{% for val in values %}{{ val }}{% endfor %}'}) + @setup({"for-tag01": "{% for val in values %}{{ val }}{% endfor %}"}) def test_for_tag01(self): - output = self.engine.render_to_string('for-tag01', {'values': [1, 2, 3]}) - self.assertEqual(output, '123') + output = self.engine.render_to_string("for-tag01", {"values": [1, 2, 3]}) + self.assertEqual(output, "123") - @setup({'for-tag02': '{% for val in values reversed %}{{ val }}{% endfor %}'}) + @setup({"for-tag02": "{% for val in values reversed %}{{ val }}{% endfor %}"}) def test_for_tag02(self): - output = self.engine.render_to_string('for-tag02', {'values': [1, 2, 3]}) - self.assertEqual(output, '321') + output = self.engine.render_to_string("for-tag02", {"values": [1, 2, 3]}) + self.assertEqual(output, "321") - @setup({'for-tag-vars01': '{% for val in values %}{{ forloop.counter }}{% endfor %}'}) + @setup( + {"for-tag-vars01": "{% for val in values %}{{ forloop.counter }}{% endfor %}"} + ) def test_for_tag_vars01(self): - output = self.engine.render_to_string('for-tag-vars01', {'values': [6, 6, 6]}) - self.assertEqual(output, '123') + output = self.engine.render_to_string("for-tag-vars01", {"values": [6, 6, 6]}) + self.assertEqual(output, "123") - @setup({'for-tag-vars02': '{% for val in values %}{{ forloop.counter0 }}{% endfor %}'}) + @setup( + {"for-tag-vars02": "{% for val in values %}{{ forloop.counter0 }}{% endfor %}"} + ) def test_for_tag_vars02(self): - output = self.engine.render_to_string('for-tag-vars02', {'values': [6, 6, 6]}) - self.assertEqual(output, '012') + output = self.engine.render_to_string("for-tag-vars02", {"values": [6, 6, 6]}) + self.assertEqual(output, "012") - @setup({'for-tag-vars03': '{% for val in values %}{{ forloop.revcounter }}{% endfor %}'}) + @setup( + { + "for-tag-vars03": "{% for val in values %}{{ forloop.revcounter }}{% endfor %}" + } + ) def test_for_tag_vars03(self): - output = self.engine.render_to_string('for-tag-vars03', {'values': [6, 6, 6]}) - self.assertEqual(output, '321') + output = self.engine.render_to_string("for-tag-vars03", {"values": [6, 6, 6]}) + self.assertEqual(output, "321") - @setup({'for-tag-vars04': '{% for val in values %}{{ forloop.revcounter0 }}{% endfor %}'}) + @setup( + { + "for-tag-vars04": "{% for val in values %}{{ forloop.revcounter0 }}{% endfor %}" + } + ) def test_for_tag_vars04(self): - output = self.engine.render_to_string('for-tag-vars04', {'values': [6, 6, 6]}) - self.assertEqual(output, '210') + output = self.engine.render_to_string("for-tag-vars04", {"values": [6, 6, 6]}) + self.assertEqual(output, "210") - @setup({'for-tag-vars05': '{% for val in values %}' - '{% if forloop.first %}f{% else %}x{% endif %}{% endfor %}'}) + @setup( + { + "for-tag-vars05": "{% for val in values %}" + "{% if forloop.first %}f{% else %}x{% endif %}{% endfor %}" + } + ) def test_for_tag_vars05(self): - output = self.engine.render_to_string('for-tag-vars05', {'values': [6, 6, 6]}) - self.assertEqual(output, 'fxx') + output = self.engine.render_to_string("for-tag-vars05", {"values": [6, 6, 6]}) + self.assertEqual(output, "fxx") - @setup({'for-tag-vars06': '{% for val in values %}' - '{% if forloop.last %}l{% else %}x{% endif %}{% endfor %}'}) + @setup( + { + "for-tag-vars06": "{% for val in values %}" + "{% if forloop.last %}l{% else %}x{% endif %}{% endfor %}" + } + ) def test_for_tag_vars06(self): - output = self.engine.render_to_string('for-tag-vars06', {'values': [6, 6, 6]}) - self.assertEqual(output, 'xxl') + output = self.engine.render_to_string("for-tag-vars06", {"values": [6, 6, 6]}) + self.assertEqual(output, "xxl") - @setup({'for-tag-unpack01': '{% for key,value in items %}{{ key }}:{{ value }}/{% endfor %}'}) + @setup( + { + "for-tag-unpack01": "{% for key,value in items %}{{ key }}:{{ value }}/{% endfor %}" + } + ) def test_for_tag_unpack01(self): - output = self.engine.render_to_string('for-tag-unpack01', {'items': (('one', 1), ('two', 2))}) - self.assertEqual(output, 'one:1/two:2/') + output = self.engine.render_to_string( + "for-tag-unpack01", {"items": (("one", 1), ("two", 2))} + ) + self.assertEqual(output, "one:1/two:2/") - @setup({'for-tag-unpack03': '{% for key, value in items %}{{ key }}:{{ value }}/{% endfor %}'}) + @setup( + { + "for-tag-unpack03": "{% for key, value in items %}{{ key }}:{{ value }}/{% endfor %}" + } + ) def test_for_tag_unpack03(self): - output = self.engine.render_to_string('for-tag-unpack03', {'items': (('one', 1), ('two', 2))}) - self.assertEqual(output, 'one:1/two:2/') + output = self.engine.render_to_string( + "for-tag-unpack03", {"items": (("one", 1), ("two", 2))} + ) + self.assertEqual(output, "one:1/two:2/") - @setup({'for-tag-unpack04': '{% for key , value in items %}{{ key }}:{{ value }}/{% endfor %}'}) + @setup( + { + "for-tag-unpack04": "{% for key , value in items %}{{ key }}:{{ value }}/{% endfor %}" + } + ) def test_for_tag_unpack04(self): - output = self.engine.render_to_string('for-tag-unpack04', {'items': (('one', 1), ('two', 2))}) - self.assertEqual(output, 'one:1/two:2/') + output = self.engine.render_to_string( + "for-tag-unpack04", {"items": (("one", 1), ("two", 2))} + ) + self.assertEqual(output, "one:1/two:2/") - @setup({'for-tag-unpack05': '{% for key ,value in items %}{{ key }}:{{ value }}/{% endfor %}'}) + @setup( + { + "for-tag-unpack05": "{% for key ,value in items %}{{ key }}:{{ value }}/{% endfor %}" + } + ) def test_for_tag_unpack05(self): - output = self.engine.render_to_string('for-tag-unpack05', {'items': (('one', 1), ('two', 2))}) - self.assertEqual(output, 'one:1/two:2/') + output = self.engine.render_to_string( + "for-tag-unpack05", {"items": (("one", 1), ("two", 2))} + ) + self.assertEqual(output, "one:1/two:2/") - @setup({'for-tag-unpack06': '{% for key value in items %}{{ key }}:{{ value }}/{% endfor %}'}) + @setup( + { + "for-tag-unpack06": "{% for key value in items %}{{ key }}:{{ value }}/{% endfor %}" + } + ) def test_for_tag_unpack06(self): msg = "'for' tag received an invalid argument: for key value in items" with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('for-tag-unpack06', {'items': (('one', 1), ('two', 2))}) + self.engine.render_to_string( + "for-tag-unpack06", {"items": (("one", 1), ("two", 2))} + ) - @setup({'for-tag-unpack07': '{% for key,,value in items %}{{ key }}:{{ value }}/{% endfor %}'}) + @setup( + { + "for-tag-unpack07": "{% for key,,value in items %}{{ key }}:{{ value }}/{% endfor %}" + } + ) def test_for_tag_unpack07(self): msg = "'for' tag received an invalid argument: for key,,value in items" with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('for-tag-unpack07', {'items': (('one', 1), ('two', 2))}) + self.engine.render_to_string( + "for-tag-unpack07", {"items": (("one", 1), ("two", 2))} + ) - @setup({'for-tag-unpack08': '{% for key,value, in items %}{{ key }}:{{ value }}/{% endfor %}'}) + @setup( + { + "for-tag-unpack08": "{% for key,value, in items %}{{ key }}:{{ value }}/{% endfor %}" + } + ) def test_for_tag_unpack08(self): msg = "'for' tag received an invalid argument: for key,value, in items" with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('for-tag-unpack08', {'items': (('one', 1), ('two', 2))}) + self.engine.render_to_string( + "for-tag-unpack08", {"items": (("one", 1), ("two", 2))} + ) - @setup({'double-quote': '{% for "k" in items %}{{ "k" }}/{% endfor %}'}) + @setup({"double-quote": '{% for "k" in items %}{{ "k" }}/{% endfor %}'}) def test_unpack_double_quote(self): msg = """'for' tag received an invalid argument: for "k" in items""" with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('double-quote', {'items': (1, 2)}) + self.engine.render_to_string("double-quote", {"items": (1, 2)}) - @setup({'single-quote': "{% for 'k' in items %}{{ k }}/{% endfor %}"}) + @setup({"single-quote": "{% for 'k' in items %}{{ k }}/{% endfor %}"}) def test_unpack_single_quote(self): msg = """'for' tag received an invalid argument: for 'k' in items""" with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('single-quote', {'items': (1, 2)}) + self.engine.render_to_string("single-quote", {"items": (1, 2)}) - @setup({'vertical-bar': '{% for k|upper in items %}{{ k|upper }}/{% endfor %}'}) + @setup({"vertical-bar": "{% for k|upper in items %}{{ k|upper }}/{% endfor %}"}) def test_unpack_vertical_bar(self): msg = "'for' tag received an invalid argument: for k|upper in items" with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('vertical-bar', {'items': (1, 2)}) + self.engine.render_to_string("vertical-bar", {"items": (1, 2)}) - @setup({'for-tag-unpack09': '{% for val in items %}{{ val.0 }}:{{ val.1 }}/{% endfor %}'}) + @setup( + { + "for-tag-unpack09": "{% for val in items %}{{ val.0 }}:{{ val.1 }}/{% endfor %}" + } + ) def test_for_tag_unpack09(self): """ A single loopvar doesn't truncate the list in val. """ - output = self.engine.render_to_string('for-tag-unpack09', {'items': (('one', 1), ('two', 2))}) - self.assertEqual(output, 'one:1/two:2/') + output = self.engine.render_to_string( + "for-tag-unpack09", {"items": (("one", 1), ("two", 2))} + ) + self.assertEqual(output, "one:1/two:2/") - @setup({'for-tag-unpack13': '{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}'}) + @setup( + { + "for-tag-unpack13": "{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}" + } + ) def test_for_tag_unpack13(self): output = self.engine.render_to_string( - 'for-tag-unpack13', {'items': (('one', 1, 'carrot'), ('two', 2, 'cheese'))} + "for-tag-unpack13", {"items": (("one", 1, "carrot"), ("two", 2, "cheese"))} ) if self.engine.string_if_invalid: - self.assertEqual(output, 'one:1,carrot/two:2,cheese/') + self.assertEqual(output, "one:1,carrot/two:2,cheese/") else: - self.assertEqual(output, 'one:1,carrot/two:2,cheese/') + self.assertEqual(output, "one:1,carrot/two:2,cheese/") - @setup({'for-tag-empty01': '{% for val in values %}{{ val }}{% empty %}empty text{% endfor %}'}) + @setup( + { + "for-tag-empty01": "{% for val in values %}{{ val }}{% empty %}empty text{% endfor %}" + } + ) def test_for_tag_empty01(self): - output = self.engine.render_to_string('for-tag-empty01', {'values': [1, 2, 3]}) - self.assertEqual(output, '123') + output = self.engine.render_to_string("for-tag-empty01", {"values": [1, 2, 3]}) + self.assertEqual(output, "123") - @setup({'for-tag-empty02': '{% for val in values %}{{ val }}{% empty %}values array empty{% endfor %}'}) + @setup( + { + "for-tag-empty02": "{% for val in values %}{{ val }}{% empty %}values array empty{% endfor %}" + } + ) def test_for_tag_empty02(self): - output = self.engine.render_to_string('for-tag-empty02', {'values': []}) - self.assertEqual(output, 'values array empty') + output = self.engine.render_to_string("for-tag-empty02", {"values": []}) + self.assertEqual(output, "values array empty") - @setup({'for-tag-empty03': '{% for val in values %}' - '{{ val }}{% empty %}values array not found{% endfor %}'}) + @setup( + { + "for-tag-empty03": "{% for val in values %}" + "{{ val }}{% empty %}values array not found{% endfor %}" + } + ) def test_for_tag_empty03(self): - output = self.engine.render_to_string('for-tag-empty03') - self.assertEqual(output, 'values array not found') + output = self.engine.render_to_string("for-tag-empty03") + self.assertEqual(output, "values array not found") - @setup({'for-tag-filter-ws': "{% load custom %}{% for x in s|noop:'x y' %}{{ x }}{% endfor %}"}) + @setup( + { + "for-tag-filter-ws": "{% load custom %}{% for x in s|noop:'x y' %}{{ x }}{% endfor %}" + } + ) def test_for_tag_filter_ws(self): """ #19882 """ - output = self.engine.render_to_string('for-tag-filter-ws', {'s': 'abc'}) - self.assertEqual(output, 'abc') + output = self.engine.render_to_string("for-tag-filter-ws", {"s": "abc"}) + self.assertEqual(output, "abc") - @setup({'for-tag-unpack-strs': '{% for x,y in items %}{{ x }}:{{ y }}/{% endfor %}'}) + @setup( + {"for-tag-unpack-strs": "{% for x,y in items %}{{ x }}:{{ y }}/{% endfor %}"} + ) def test_for_tag_unpack_strs(self): - output = self.engine.render_to_string('for-tag-unpack-strs', {'items': ('ab', 'ac')}) - self.assertEqual(output, 'a:b/a:c/') + output = self.engine.render_to_string( + "for-tag-unpack-strs", {"items": ("ab", "ac")} + ) + self.assertEqual(output, "a:b/a:c/") - @setup({'for-tag-unpack10': '{% for x,y in items %}{{ x }}:{{ y }}/{% endfor %}'}) + @setup({"for-tag-unpack10": "{% for x,y in items %}{{ x }}:{{ y }}/{% endfor %}"}) def test_for_tag_unpack10(self): - with self.assertRaisesMessage(ValueError, 'Need 2 values to unpack in for loop; got 3.'): + with self.assertRaisesMessage( + ValueError, "Need 2 values to unpack in for loop; got 3." + ): self.engine.render_to_string( - 'for-tag-unpack10', - {'items': (('one', 1, 'carrot'), ('two', 2, 'orange'))}, + "for-tag-unpack10", + {"items": (("one", 1, "carrot"), ("two", 2, "orange"))}, ) - @setup({'for-tag-unpack11': '{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}'}) + @setup( + { + "for-tag-unpack11": "{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}" + } + ) def test_for_tag_unpack11(self): - with self.assertRaisesMessage(ValueError, 'Need 3 values to unpack in for loop; got 2.'): + with self.assertRaisesMessage( + ValueError, "Need 3 values to unpack in for loop; got 2." + ): self.engine.render_to_string( - 'for-tag-unpack11', - {'items': (('one', 1), ('two', 2))}, + "for-tag-unpack11", + {"items": (("one", 1), ("two", 2))}, ) - @setup({'for-tag-unpack12': '{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}'}) + @setup( + { + "for-tag-unpack12": "{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}" + } + ) def test_for_tag_unpack12(self): - with self.assertRaisesMessage(ValueError, 'Need 3 values to unpack in for loop; got 2.'): + with self.assertRaisesMessage( + ValueError, "Need 3 values to unpack in for loop; got 2." + ): self.engine.render_to_string( - 'for-tag-unpack12', - {'items': (('one', 1, 'carrot'), ('two', 2))} + "for-tag-unpack12", {"items": (("one", 1, "carrot"), ("two", 2))} ) - @setup({'for-tag-unpack14': '{% for x,y in items %}{{ x }}:{{ y }}/{% endfor %}'}) + @setup({"for-tag-unpack14": "{% for x,y in items %}{{ x }}:{{ y }}/{% endfor %}"}) def test_for_tag_unpack14(self): - with self.assertRaisesMessage(ValueError, 'Need 2 values to unpack in for loop; got 1.'): - self.engine.render_to_string('for-tag-unpack14', {'items': (1, 2)}) + with self.assertRaisesMessage( + ValueError, "Need 2 values to unpack in for loop; got 1." + ): + self.engine.render_to_string("for-tag-unpack14", {"items": (1, 2)}) - @setup({ - 'main': '{% with alpha=alpha.values %}{% include "base" %}{% endwith %}_' - '{% with alpha=alpha.extra %}{% include "base" %}{% endwith %}', - 'base': '{% for x, y in alpha %}{{ x }}:{{ y }},{% endfor %}' - }) + @setup( + { + "main": '{% with alpha=alpha.values %}{% include "base" %}{% endwith %}_' + '{% with alpha=alpha.extra %}{% include "base" %}{% endwith %}', + "base": "{% for x, y in alpha %}{{ x }}:{{ y }},{% endfor %}", + } + ) def test_for_tag_context(self): """ ForNode.render() pops the values it pushes to the context (#28001). """ - output = self.engine.render_to_string('main', { - 'alpha': { - 'values': [('two', 2), ('four', 4)], - 'extra': [('six', 6), ('eight', 8)], + output = self.engine.render_to_string( + "main", + { + "alpha": { + "values": [("two", 2), ("four", 4)], + "extra": [("six", 6), ("eight", 8)], + }, }, - }) - self.assertEqual(output, 'two:2,four:4,_six:6,eight:8,') + ) + self.assertEqual(output, "two:2,four:4,_six:6,eight:8,") - @setup({'invalid_for_loop': '{% for x items %}{{ x }}{% endfor %}'}) + @setup({"invalid_for_loop": "{% for x items %}{{ x }}{% endfor %}"}) def test_invalid_arg(self): msg = "'for' statements should have at least four words: for x items" with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('invalid_for_loop', {'items': (1, 2)}) + self.engine.render_to_string("invalid_for_loop", {"items": (1, 2)}) - @setup({'invalid_for_loop': '{% for x from items %}{{ x }}{% endfor %}'}) + @setup({"invalid_for_loop": "{% for x from items %}{{ x }}{% endfor %}"}) def test_invalid_in_keyword(self): msg = "'for' statements should use the format 'for x in y': for x from items" with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('invalid_for_loop', {'items': (1, 2)}) + self.engine.render_to_string("invalid_for_loop", {"items": (1, 2)}) class ForNodeTests(SimpleTestCase): def test_repr(self): - node = ForNode('x', 'sequence', is_reversed=True, nodelist_loop=['val'], nodelist_empty=['val2']) - self.assertEqual(repr(node), '<ForNode: for x in sequence, tail_len: 1 reversed>') + node = ForNode( + "x", + "sequence", + is_reversed=True, + nodelist_loop=["val"], + nodelist_empty=["val2"], + ) + self.assertEqual( + repr(node), "<ForNode: for x in sequence, tail_len: 1 reversed>" + ) diff --git a/tests/template_tests/syntax_tests/test_if.py b/tests/template_tests/syntax_tests/test_if.py index 711f871af9..fda44b0672 100644 --- a/tests/template_tests/syntax_tests/test_if.py +++ b/tests/template_tests/syntax_tests/test_if.py @@ -6,603 +6,694 @@ from ..utils import TestObj, setup class IfTagTests(SimpleTestCase): - - @setup({'if-tag01': '{% if foo %}yes{% else %}no{% endif %}'}) + @setup({"if-tag01": "{% if foo %}yes{% else %}no{% endif %}"}) def test_if_tag01(self): - output = self.engine.render_to_string('if-tag01', {'foo': True}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string("if-tag01", {"foo": True}) + self.assertEqual(output, "yes") - @setup({'if-tag02': '{% if foo %}yes{% else %}no{% endif %}'}) + @setup({"if-tag02": "{% if foo %}yes{% else %}no{% endif %}"}) def test_if_tag02(self): - output = self.engine.render_to_string('if-tag02', {'foo': False}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string("if-tag02", {"foo": False}) + self.assertEqual(output, "no") - @setup({'if-tag03': '{% if foo %}yes{% else %}no{% endif %}'}) + @setup({"if-tag03": "{% if foo %}yes{% else %}no{% endif %}"}) def test_if_tag03(self): - output = self.engine.render_to_string('if-tag03') - self.assertEqual(output, 'no') + output = self.engine.render_to_string("if-tag03") + self.assertEqual(output, "no") - @setup({'if-tag04': '{% if foo %}foo{% elif bar %}bar{% endif %}'}) + @setup({"if-tag04": "{% if foo %}foo{% elif bar %}bar{% endif %}"}) def test_if_tag04(self): - output = self.engine.render_to_string('if-tag04', {'foo': True}) - self.assertEqual(output, 'foo') + output = self.engine.render_to_string("if-tag04", {"foo": True}) + self.assertEqual(output, "foo") - @setup({'if-tag05': '{% if foo %}foo{% elif bar %}bar{% endif %}'}) + @setup({"if-tag05": "{% if foo %}foo{% elif bar %}bar{% endif %}"}) def test_if_tag05(self): - output = self.engine.render_to_string('if-tag05', {'bar': True}) - self.assertEqual(output, 'bar') + output = self.engine.render_to_string("if-tag05", {"bar": True}) + self.assertEqual(output, "bar") - @setup({'if-tag06': '{% if foo %}foo{% elif bar %}bar{% endif %}'}) + @setup({"if-tag06": "{% if foo %}foo{% elif bar %}bar{% endif %}"}) def test_if_tag06(self): - output = self.engine.render_to_string('if-tag06') - self.assertEqual(output, '') + output = self.engine.render_to_string("if-tag06") + self.assertEqual(output, "") - @setup({'if-tag07': '{% if foo %}foo{% elif bar %}bar{% else %}nothing{% endif %}'}) + @setup({"if-tag07": "{% if foo %}foo{% elif bar %}bar{% else %}nothing{% endif %}"}) def test_if_tag07(self): - output = self.engine.render_to_string('if-tag07', {'foo': True}) - self.assertEqual(output, 'foo') + output = self.engine.render_to_string("if-tag07", {"foo": True}) + self.assertEqual(output, "foo") - @setup({'if-tag08': '{% if foo %}foo{% elif bar %}bar{% else %}nothing{% endif %}'}) + @setup({"if-tag08": "{% if foo %}foo{% elif bar %}bar{% else %}nothing{% endif %}"}) def test_if_tag08(self): - output = self.engine.render_to_string('if-tag08', {'bar': True}) - self.assertEqual(output, 'bar') + output = self.engine.render_to_string("if-tag08", {"bar": True}) + self.assertEqual(output, "bar") - @setup({'if-tag09': '{% if foo %}foo{% elif bar %}bar{% else %}nothing{% endif %}'}) + @setup({"if-tag09": "{% if foo %}foo{% elif bar %}bar{% else %}nothing{% endif %}"}) def test_if_tag09(self): - output = self.engine.render_to_string('if-tag09') - self.assertEqual(output, 'nothing') + output = self.engine.render_to_string("if-tag09") + self.assertEqual(output, "nothing") - @setup({'if-tag10': '{% if foo %}foo{% elif bar %}bar{% elif baz %}baz{% else %}nothing{% endif %}'}) + @setup( + { + "if-tag10": "{% if foo %}foo{% elif bar %}bar{% elif baz %}baz{% else %}nothing{% endif %}" + } + ) def test_if_tag10(self): - output = self.engine.render_to_string('if-tag10', {'foo': True}) - self.assertEqual(output, 'foo') + output = self.engine.render_to_string("if-tag10", {"foo": True}) + self.assertEqual(output, "foo") - @setup({'if-tag11': '{% if foo %}foo{% elif bar %}bar{% elif baz %}baz{% else %}nothing{% endif %}'}) + @setup( + { + "if-tag11": "{% if foo %}foo{% elif bar %}bar{% elif baz %}baz{% else %}nothing{% endif %}" + } + ) def test_if_tag11(self): - output = self.engine.render_to_string('if-tag11', {'bar': True}) - self.assertEqual(output, 'bar') + output = self.engine.render_to_string("if-tag11", {"bar": True}) + self.assertEqual(output, "bar") - @setup({'if-tag12': '{% if foo %}foo{% elif bar %}bar{% elif baz %}baz{% else %}nothing{% endif %}'}) + @setup( + { + "if-tag12": "{% if foo %}foo{% elif bar %}bar{% elif baz %}baz{% else %}nothing{% endif %}" + } + ) def test_if_tag12(self): - output = self.engine.render_to_string('if-tag12', {'baz': True}) - self.assertEqual(output, 'baz') + output = self.engine.render_to_string("if-tag12", {"baz": True}) + self.assertEqual(output, "baz") - @setup({'if-tag13': '{% if foo %}foo{% elif bar %}bar{% elif baz %}baz{% else %}nothing{% endif %}'}) + @setup( + { + "if-tag13": "{% if foo %}foo{% elif bar %}bar{% elif baz %}baz{% else %}nothing{% endif %}" + } + ) def test_if_tag13(self): - output = self.engine.render_to_string('if-tag13') - self.assertEqual(output, 'nothing') + output = self.engine.render_to_string("if-tag13") + self.assertEqual(output, "nothing") # Filters - @setup({'if-tag-filter01': '{% if foo|length == 5 %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-filter01": "{% if foo|length == 5 %}yes{% else %}no{% endif %}"}) def test_if_tag_filter01(self): - output = self.engine.render_to_string('if-tag-filter01', {'foo': 'abcde'}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string("if-tag-filter01", {"foo": "abcde"}) + self.assertEqual(output, "yes") - @setup({'if-tag-filter02': '{% if foo|upper == \'ABC\' %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-filter02": "{% if foo|upper == 'ABC' %}yes{% else %}no{% endif %}"}) def test_if_tag_filter02(self): - output = self.engine.render_to_string('if-tag-filter02') - self.assertEqual(output, 'no') + output = self.engine.render_to_string("if-tag-filter02") + self.assertEqual(output, "no") # Equality - @setup({'if-tag-eq01': '{% if foo == bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-eq01": "{% if foo == bar %}yes{% else %}no{% endif %}"}) def test_if_tag_eq01(self): - output = self.engine.render_to_string('if-tag-eq01') - self.assertEqual(output, 'yes') + output = self.engine.render_to_string("if-tag-eq01") + self.assertEqual(output, "yes") - @setup({'if-tag-eq02': '{% if foo == bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-eq02": "{% if foo == bar %}yes{% else %}no{% endif %}"}) def test_if_tag_eq02(self): - output = self.engine.render_to_string('if-tag-eq02', {'foo': 1}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string("if-tag-eq02", {"foo": 1}) + self.assertEqual(output, "no") - @setup({'if-tag-eq03': '{% if foo == bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-eq03": "{% if foo == bar %}yes{% else %}no{% endif %}"}) def test_if_tag_eq03(self): - output = self.engine.render_to_string('if-tag-eq03', {'foo': 1, 'bar': 1}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string("if-tag-eq03", {"foo": 1, "bar": 1}) + self.assertEqual(output, "yes") - @setup({'if-tag-eq04': '{% if foo == bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-eq04": "{% if foo == bar %}yes{% else %}no{% endif %}"}) def test_if_tag_eq04(self): - output = self.engine.render_to_string('if-tag-eq04', {'foo': 1, 'bar': 2}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string("if-tag-eq04", {"foo": 1, "bar": 2}) + self.assertEqual(output, "no") - @setup({'if-tag-eq05': '{% if foo == \'\' %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-eq05": "{% if foo == '' %}yes{% else %}no{% endif %}"}) def test_if_tag_eq05(self): - output = self.engine.render_to_string('if-tag-eq05') - self.assertEqual(output, 'no') + output = self.engine.render_to_string("if-tag-eq05") + self.assertEqual(output, "no") # Inequality - @setup({'if-tag-noteq01': '{% if foo != bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-noteq01": "{% if foo != bar %}yes{% else %}no{% endif %}"}) def test_if_tag_noteq01(self): - output = self.engine.render_to_string('if-tag-noteq01') - self.assertEqual(output, 'no') + output = self.engine.render_to_string("if-tag-noteq01") + self.assertEqual(output, "no") - @setup({'if-tag-noteq02': '{% if foo != bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-noteq02": "{% if foo != bar %}yes{% else %}no{% endif %}"}) def test_if_tag_noteq02(self): - output = self.engine.render_to_string('if-tag-noteq02', {'foo': 1}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string("if-tag-noteq02", {"foo": 1}) + self.assertEqual(output, "yes") - @setup({'if-tag-noteq03': '{% if foo != bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-noteq03": "{% if foo != bar %}yes{% else %}no{% endif %}"}) def test_if_tag_noteq03(self): - output = self.engine.render_to_string('if-tag-noteq03', {'foo': 1, 'bar': 1}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string("if-tag-noteq03", {"foo": 1, "bar": 1}) + self.assertEqual(output, "no") - @setup({'if-tag-noteq04': '{% if foo != bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-noteq04": "{% if foo != bar %}yes{% else %}no{% endif %}"}) def test_if_tag_noteq04(self): - output = self.engine.render_to_string('if-tag-noteq04', {'foo': 1, 'bar': 2}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string("if-tag-noteq04", {"foo": 1, "bar": 2}) + self.assertEqual(output, "yes") - @setup({'if-tag-noteq05': '{% if foo != "" %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-noteq05": '{% if foo != "" %}yes{% else %}no{% endif %}'}) def test_if_tag_noteq05(self): - output = self.engine.render_to_string('if-tag-noteq05') - self.assertEqual(output, 'yes') + output = self.engine.render_to_string("if-tag-noteq05") + self.assertEqual(output, "yes") # Comparison - @setup({'if-tag-gt-01': '{% if 2 > 1 %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-gt-01": "{% if 2 > 1 %}yes{% else %}no{% endif %}"}) def test_if_tag_gt_01(self): - output = self.engine.render_to_string('if-tag-gt-01') - self.assertEqual(output, 'yes') + output = self.engine.render_to_string("if-tag-gt-01") + self.assertEqual(output, "yes") - @setup({'if-tag-gt-02': '{% if 1 > 1 %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-gt-02": "{% if 1 > 1 %}yes{% else %}no{% endif %}"}) def test_if_tag_gt_02(self): - output = self.engine.render_to_string('if-tag-gt-02') - self.assertEqual(output, 'no') + output = self.engine.render_to_string("if-tag-gt-02") + self.assertEqual(output, "no") - @setup({'if-tag-gte-01': '{% if 1 >= 1 %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-gte-01": "{% if 1 >= 1 %}yes{% else %}no{% endif %}"}) def test_if_tag_gte_01(self): - output = self.engine.render_to_string('if-tag-gte-01') - self.assertEqual(output, 'yes') + output = self.engine.render_to_string("if-tag-gte-01") + self.assertEqual(output, "yes") - @setup({'if-tag-gte-02': '{% if 1 >= 2 %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-gte-02": "{% if 1 >= 2 %}yes{% else %}no{% endif %}"}) def test_if_tag_gte_02(self): - output = self.engine.render_to_string('if-tag-gte-02') - self.assertEqual(output, 'no') + output = self.engine.render_to_string("if-tag-gte-02") + self.assertEqual(output, "no") - @setup({'if-tag-lt-01': '{% if 1 < 2 %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-lt-01": "{% if 1 < 2 %}yes{% else %}no{% endif %}"}) def test_if_tag_lt_01(self): - output = self.engine.render_to_string('if-tag-lt-01') - self.assertEqual(output, 'yes') + output = self.engine.render_to_string("if-tag-lt-01") + self.assertEqual(output, "yes") - @setup({'if-tag-lt-02': '{% if 1 < 1 %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-lt-02": "{% if 1 < 1 %}yes{% else %}no{% endif %}"}) def test_if_tag_lt_02(self): - output = self.engine.render_to_string('if-tag-lt-02') - self.assertEqual(output, 'no') + output = self.engine.render_to_string("if-tag-lt-02") + self.assertEqual(output, "no") - @setup({'if-tag-lte-01': '{% if 1 <= 1 %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-lte-01": "{% if 1 <= 1 %}yes{% else %}no{% endif %}"}) def test_if_tag_lte_01(self): - output = self.engine.render_to_string('if-tag-lte-01') - self.assertEqual(output, 'yes') + output = self.engine.render_to_string("if-tag-lte-01") + self.assertEqual(output, "yes") - @setup({'if-tag-lte-02': '{% if 2 <= 1 %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-lte-02": "{% if 2 <= 1 %}yes{% else %}no{% endif %}"}) def test_if_tag_lte_02(self): - output = self.engine.render_to_string('if-tag-lte-02') - self.assertEqual(output, 'no') + output = self.engine.render_to_string("if-tag-lte-02") + self.assertEqual(output, "no") # Contains - @setup({'if-tag-in-01': '{% if 1 in x %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-in-01": "{% if 1 in x %}yes{% else %}no{% endif %}"}) def test_if_tag_in_01(self): - output = self.engine.render_to_string('if-tag-in-01', {'x': [1]}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string("if-tag-in-01", {"x": [1]}) + self.assertEqual(output, "yes") - @setup({'if-tag-in-02': '{% if 2 in x %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-in-02": "{% if 2 in x %}yes{% else %}no{% endif %}"}) def test_if_tag_in_02(self): - output = self.engine.render_to_string('if-tag-in-02', {'x': [1]}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string("if-tag-in-02", {"x": [1]}) + self.assertEqual(output, "no") - @setup({'if-tag-not-in-01': '{% if 1 not in x %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-not-in-01": "{% if 1 not in x %}yes{% else %}no{% endif %}"}) def test_if_tag_not_in_01(self): - output = self.engine.render_to_string('if-tag-not-in-01', {'x': [1]}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string("if-tag-not-in-01", {"x": [1]}) + self.assertEqual(output, "no") - @setup({'if-tag-not-in-02': '{% if 2 not in x %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-not-in-02": "{% if 2 not in x %}yes{% else %}no{% endif %}"}) def test_if_tag_not_in_02(self): - output = self.engine.render_to_string('if-tag-not-in-02', {'x': [1]}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string("if-tag-not-in-02", {"x": [1]}) + self.assertEqual(output, "yes") # AND - @setup({'if-tag-and01': '{% if foo and bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-and01": "{% if foo and bar %}yes{% else %}no{% endif %}"}) def test_if_tag_and01(self): - output = self.engine.render_to_string('if-tag-and01', {'foo': True, 'bar': True}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string( + "if-tag-and01", {"foo": True, "bar": True} + ) + self.assertEqual(output, "yes") - @setup({'if-tag-and02': '{% if foo and bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-and02": "{% if foo and bar %}yes{% else %}no{% endif %}"}) def test_if_tag_and02(self): - output = self.engine.render_to_string('if-tag-and02', {'foo': True, 'bar': False}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string( + "if-tag-and02", {"foo": True, "bar": False} + ) + self.assertEqual(output, "no") - @setup({'if-tag-and03': '{% if foo and bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-and03": "{% if foo and bar %}yes{% else %}no{% endif %}"}) def test_if_tag_and03(self): - output = self.engine.render_to_string('if-tag-and03', {'foo': False, 'bar': True}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string( + "if-tag-and03", {"foo": False, "bar": True} + ) + self.assertEqual(output, "no") - @setup({'if-tag-and04': '{% if foo and bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-and04": "{% if foo and bar %}yes{% else %}no{% endif %}"}) def test_if_tag_and04(self): - output = self.engine.render_to_string('if-tag-and04', {'foo': False, 'bar': False}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string( + "if-tag-and04", {"foo": False, "bar": False} + ) + self.assertEqual(output, "no") - @setup({'if-tag-and05': '{% if foo and bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-and05": "{% if foo and bar %}yes{% else %}no{% endif %}"}) def test_if_tag_and05(self): - output = self.engine.render_to_string('if-tag-and05', {'foo': False}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string("if-tag-and05", {"foo": False}) + self.assertEqual(output, "no") - @setup({'if-tag-and06': '{% if foo and bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-and06": "{% if foo and bar %}yes{% else %}no{% endif %}"}) def test_if_tag_and06(self): - output = self.engine.render_to_string('if-tag-and06', {'bar': False}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string("if-tag-and06", {"bar": False}) + self.assertEqual(output, "no") - @setup({'if-tag-and07': '{% if foo and bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-and07": "{% if foo and bar %}yes{% else %}no{% endif %}"}) def test_if_tag_and07(self): - output = self.engine.render_to_string('if-tag-and07', {'foo': True}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string("if-tag-and07", {"foo": True}) + self.assertEqual(output, "no") - @setup({'if-tag-and08': '{% if foo and bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-and08": "{% if foo and bar %}yes{% else %}no{% endif %}"}) def test_if_tag_and08(self): - output = self.engine.render_to_string('if-tag-and08', {'bar': True}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string("if-tag-and08", {"bar": True}) + self.assertEqual(output, "no") # OR - @setup({'if-tag-or01': '{% if foo or bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-or01": "{% if foo or bar %}yes{% else %}no{% endif %}"}) def test_if_tag_or01(self): - output = self.engine.render_to_string('if-tag-or01', {'foo': True, 'bar': True}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string("if-tag-or01", {"foo": True, "bar": True}) + self.assertEqual(output, "yes") - @setup({'if-tag-or02': '{% if foo or bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-or02": "{% if foo or bar %}yes{% else %}no{% endif %}"}) def test_if_tag_or02(self): - output = self.engine.render_to_string('if-tag-or02', {'foo': True, 'bar': False}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string( + "if-tag-or02", {"foo": True, "bar": False} + ) + self.assertEqual(output, "yes") - @setup({'if-tag-or03': '{% if foo or bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-or03": "{% if foo or bar %}yes{% else %}no{% endif %}"}) def test_if_tag_or03(self): - output = self.engine.render_to_string('if-tag-or03', {'foo': False, 'bar': True}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string( + "if-tag-or03", {"foo": False, "bar": True} + ) + self.assertEqual(output, "yes") - @setup({'if-tag-or04': '{% if foo or bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-or04": "{% if foo or bar %}yes{% else %}no{% endif %}"}) def test_if_tag_or04(self): - output = self.engine.render_to_string('if-tag-or04', {'foo': False, 'bar': False}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string( + "if-tag-or04", {"foo": False, "bar": False} + ) + self.assertEqual(output, "no") - @setup({'if-tag-or05': '{% if foo or bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-or05": "{% if foo or bar %}yes{% else %}no{% endif %}"}) def test_if_tag_or05(self): - output = self.engine.render_to_string('if-tag-or05', {'foo': False}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string("if-tag-or05", {"foo": False}) + self.assertEqual(output, "no") - @setup({'if-tag-or06': '{% if foo or bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-or06": "{% if foo or bar %}yes{% else %}no{% endif %}"}) def test_if_tag_or06(self): - output = self.engine.render_to_string('if-tag-or06', {'bar': False}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string("if-tag-or06", {"bar": False}) + self.assertEqual(output, "no") - @setup({'if-tag-or07': '{% if foo or bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-or07": "{% if foo or bar %}yes{% else %}no{% endif %}"}) def test_if_tag_or07(self): - output = self.engine.render_to_string('if-tag-or07', {'foo': True}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string("if-tag-or07", {"foo": True}) + self.assertEqual(output, "yes") - @setup({'if-tag-or08': '{% if foo or bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-or08": "{% if foo or bar %}yes{% else %}no{% endif %}"}) def test_if_tag_or08(self): - output = self.engine.render_to_string('if-tag-or08', {'bar': True}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string("if-tag-or08", {"bar": True}) + self.assertEqual(output, "yes") - @setup({'if-tag-or09': '{% if foo or bar or baz %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-or09": "{% if foo or bar or baz %}yes{% else %}no{% endif %}"}) def test_if_tag_or09(self): """ multiple ORs """ - output = self.engine.render_to_string('if-tag-or09', {'baz': True}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string("if-tag-or09", {"baz": True}) + self.assertEqual(output, "yes") # NOT - @setup({'if-tag-not01': '{% if not foo %}no{% else %}yes{% endif %}'}) + @setup({"if-tag-not01": "{% if not foo %}no{% else %}yes{% endif %}"}) def test_if_tag_not01(self): - output = self.engine.render_to_string('if-tag-not01', {'foo': True}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string("if-tag-not01", {"foo": True}) + self.assertEqual(output, "yes") - @setup({'if-tag-not02': '{% if not not foo %}no{% else %}yes{% endif %}'}) + @setup({"if-tag-not02": "{% if not not foo %}no{% else %}yes{% endif %}"}) def test_if_tag_not02(self): - output = self.engine.render_to_string('if-tag-not02', {'foo': True}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string("if-tag-not02", {"foo": True}) + self.assertEqual(output, "no") - @setup({'if-tag-not06': '{% if foo and not bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-not06": "{% if foo and not bar %}yes{% else %}no{% endif %}"}) def test_if_tag_not06(self): - output = self.engine.render_to_string('if-tag-not06') - self.assertEqual(output, 'no') + output = self.engine.render_to_string("if-tag-not06") + self.assertEqual(output, "no") - @setup({'if-tag-not07': '{% if foo and not bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-not07": "{% if foo and not bar %}yes{% else %}no{% endif %}"}) def test_if_tag_not07(self): - output = self.engine.render_to_string('if-tag-not07', {'foo': True, 'bar': True}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string( + "if-tag-not07", {"foo": True, "bar": True} + ) + self.assertEqual(output, "no") - @setup({'if-tag-not08': '{% if foo and not bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-not08": "{% if foo and not bar %}yes{% else %}no{% endif %}"}) def test_if_tag_not08(self): - output = self.engine.render_to_string('if-tag-not08', {'foo': True, 'bar': False}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string( + "if-tag-not08", {"foo": True, "bar": False} + ) + self.assertEqual(output, "yes") - @setup({'if-tag-not09': '{% if foo and not bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-not09": "{% if foo and not bar %}yes{% else %}no{% endif %}"}) def test_if_tag_not09(self): - output = self.engine.render_to_string('if-tag-not09', {'foo': False, 'bar': True}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string( + "if-tag-not09", {"foo": False, "bar": True} + ) + self.assertEqual(output, "no") - @setup({'if-tag-not10': '{% if foo and not bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-not10": "{% if foo and not bar %}yes{% else %}no{% endif %}"}) def test_if_tag_not10(self): - output = self.engine.render_to_string('if-tag-not10', {'foo': False, 'bar': False}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string( + "if-tag-not10", {"foo": False, "bar": False} + ) + self.assertEqual(output, "no") - @setup({'if-tag-not11': '{% if not foo and bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-not11": "{% if not foo and bar %}yes{% else %}no{% endif %}"}) def test_if_tag_not11(self): - output = self.engine.render_to_string('if-tag-not11') - self.assertEqual(output, 'no') + output = self.engine.render_to_string("if-tag-not11") + self.assertEqual(output, "no") - @setup({'if-tag-not12': '{% if not foo and bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-not12": "{% if not foo and bar %}yes{% else %}no{% endif %}"}) def test_if_tag_not12(self): - output = self.engine.render_to_string('if-tag-not12', {'foo': True, 'bar': True}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string( + "if-tag-not12", {"foo": True, "bar": True} + ) + self.assertEqual(output, "no") - @setup({'if-tag-not13': '{% if not foo and bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-not13": "{% if not foo and bar %}yes{% else %}no{% endif %}"}) def test_if_tag_not13(self): - output = self.engine.render_to_string('if-tag-not13', {'foo': True, 'bar': False}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string( + "if-tag-not13", {"foo": True, "bar": False} + ) + self.assertEqual(output, "no") - @setup({'if-tag-not14': '{% if not foo and bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-not14": "{% if not foo and bar %}yes{% else %}no{% endif %}"}) def test_if_tag_not14(self): - output = self.engine.render_to_string('if-tag-not14', {'foo': False, 'bar': True}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string( + "if-tag-not14", {"foo": False, "bar": True} + ) + self.assertEqual(output, "yes") - @setup({'if-tag-not15': '{% if not foo and bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-not15": "{% if not foo and bar %}yes{% else %}no{% endif %}"}) def test_if_tag_not15(self): - output = self.engine.render_to_string('if-tag-not15', {'foo': False, 'bar': False}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string( + "if-tag-not15", {"foo": False, "bar": False} + ) + self.assertEqual(output, "no") - @setup({'if-tag-not16': '{% if foo or not bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-not16": "{% if foo or not bar %}yes{% else %}no{% endif %}"}) def test_if_tag_not16(self): - output = self.engine.render_to_string('if-tag-not16') - self.assertEqual(output, 'yes') + output = self.engine.render_to_string("if-tag-not16") + self.assertEqual(output, "yes") - @setup({'if-tag-not17': '{% if foo or not bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-not17": "{% if foo or not bar %}yes{% else %}no{% endif %}"}) def test_if_tag_not17(self): - output = self.engine.render_to_string('if-tag-not17', {'foo': True, 'bar': True}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string( + "if-tag-not17", {"foo": True, "bar": True} + ) + self.assertEqual(output, "yes") - @setup({'if-tag-not18': '{% if foo or not bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-not18": "{% if foo or not bar %}yes{% else %}no{% endif %}"}) def test_if_tag_not18(self): - output = self.engine.render_to_string('if-tag-not18', {'foo': True, 'bar': False}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string( + "if-tag-not18", {"foo": True, "bar": False} + ) + self.assertEqual(output, "yes") - @setup({'if-tag-not19': '{% if foo or not bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-not19": "{% if foo or not bar %}yes{% else %}no{% endif %}"}) def test_if_tag_not19(self): - output = self.engine.render_to_string('if-tag-not19', {'foo': False, 'bar': True}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string( + "if-tag-not19", {"foo": False, "bar": True} + ) + self.assertEqual(output, "no") - @setup({'if-tag-not20': '{% if foo or not bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-not20": "{% if foo or not bar %}yes{% else %}no{% endif %}"}) def test_if_tag_not20(self): - output = self.engine.render_to_string('if-tag-not20', {'foo': False, 'bar': False}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string( + "if-tag-not20", {"foo": False, "bar": False} + ) + self.assertEqual(output, "yes") - @setup({'if-tag-not21': '{% if not foo or bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-not21": "{% if not foo or bar %}yes{% else %}no{% endif %}"}) def test_if_tag_not21(self): - output = self.engine.render_to_string('if-tag-not21') - self.assertEqual(output, 'yes') + output = self.engine.render_to_string("if-tag-not21") + self.assertEqual(output, "yes") - @setup({'if-tag-not22': '{% if not foo or bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-not22": "{% if not foo or bar %}yes{% else %}no{% endif %}"}) def test_if_tag_not22(self): - output = self.engine.render_to_string('if-tag-not22', {'foo': True, 'bar': True}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string( + "if-tag-not22", {"foo": True, "bar": True} + ) + self.assertEqual(output, "yes") - @setup({'if-tag-not23': '{% if not foo or bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-not23": "{% if not foo or bar %}yes{% else %}no{% endif %}"}) def test_if_tag_not23(self): - output = self.engine.render_to_string('if-tag-not23', {'foo': True, 'bar': False}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string( + "if-tag-not23", {"foo": True, "bar": False} + ) + self.assertEqual(output, "no") - @setup({'if-tag-not24': '{% if not foo or bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-not24": "{% if not foo or bar %}yes{% else %}no{% endif %}"}) def test_if_tag_not24(self): - output = self.engine.render_to_string('if-tag-not24', {'foo': False, 'bar': True}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string( + "if-tag-not24", {"foo": False, "bar": True} + ) + self.assertEqual(output, "yes") - @setup({'if-tag-not25': '{% if not foo or bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-not25": "{% if not foo or bar %}yes{% else %}no{% endif %}"}) def test_if_tag_not25(self): - output = self.engine.render_to_string('if-tag-not25', {'foo': False, 'bar': False}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string( + "if-tag-not25", {"foo": False, "bar": False} + ) + self.assertEqual(output, "yes") - @setup({'if-tag-not26': '{% if not foo and not bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-not26": "{% if not foo and not bar %}yes{% else %}no{% endif %}"}) def test_if_tag_not26(self): - output = self.engine.render_to_string('if-tag-not26') - self.assertEqual(output, 'yes') + output = self.engine.render_to_string("if-tag-not26") + self.assertEqual(output, "yes") - @setup({'if-tag-not27': '{% if not foo and not bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-not27": "{% if not foo and not bar %}yes{% else %}no{% endif %}"}) def test_if_tag_not27(self): - output = self.engine.render_to_string('if-tag-not27', {'foo': True, 'bar': True}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string( + "if-tag-not27", {"foo": True, "bar": True} + ) + self.assertEqual(output, "no") - @setup({'if-tag-not28': '{% if not foo and not bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-not28": "{% if not foo and not bar %}yes{% else %}no{% endif %}"}) def test_if_tag_not28(self): - output = self.engine.render_to_string('if-tag-not28', {'foo': True, 'bar': False}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string( + "if-tag-not28", {"foo": True, "bar": False} + ) + self.assertEqual(output, "no") - @setup({'if-tag-not29': '{% if not foo and not bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-not29": "{% if not foo and not bar %}yes{% else %}no{% endif %}"}) def test_if_tag_not29(self): - output = self.engine.render_to_string('if-tag-not29', {'foo': False, 'bar': True}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string( + "if-tag-not29", {"foo": False, "bar": True} + ) + self.assertEqual(output, "no") - @setup({'if-tag-not30': '{% if not foo and not bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-not30": "{% if not foo and not bar %}yes{% else %}no{% endif %}"}) def test_if_tag_not30(self): - output = self.engine.render_to_string('if-tag-not30', {'foo': False, 'bar': False}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string( + "if-tag-not30", {"foo": False, "bar": False} + ) + self.assertEqual(output, "yes") - @setup({'if-tag-not31': '{% if not foo or not bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-not31": "{% if not foo or not bar %}yes{% else %}no{% endif %}"}) def test_if_tag_not31(self): - output = self.engine.render_to_string('if-tag-not31') - self.assertEqual(output, 'yes') + output = self.engine.render_to_string("if-tag-not31") + self.assertEqual(output, "yes") - @setup({'if-tag-not32': '{% if not foo or not bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-not32": "{% if not foo or not bar %}yes{% else %}no{% endif %}"}) def test_if_tag_not32(self): - output = self.engine.render_to_string('if-tag-not32', {'foo': True, 'bar': True}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string( + "if-tag-not32", {"foo": True, "bar": True} + ) + self.assertEqual(output, "no") - @setup({'if-tag-not33': '{% if not foo or not bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-not33": "{% if not foo or not bar %}yes{% else %}no{% endif %}"}) def test_if_tag_not33(self): - output = self.engine.render_to_string('if-tag-not33', {'foo': True, 'bar': False}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string( + "if-tag-not33", {"foo": True, "bar": False} + ) + self.assertEqual(output, "yes") - @setup({'if-tag-not34': '{% if not foo or not bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-not34": "{% if not foo or not bar %}yes{% else %}no{% endif %}"}) def test_if_tag_not34(self): - output = self.engine.render_to_string('if-tag-not34', {'foo': False, 'bar': True}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string( + "if-tag-not34", {"foo": False, "bar": True} + ) + self.assertEqual(output, "yes") - @setup({'if-tag-not35': '{% if not foo or not bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-not35": "{% if not foo or not bar %}yes{% else %}no{% endif %}"}) def test_if_tag_not35(self): - output = self.engine.render_to_string('if-tag-not35', {'foo': False, 'bar': False}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string( + "if-tag-not35", {"foo": False, "bar": False} + ) + self.assertEqual(output, "yes") # Various syntax errors - @setup({'if-tag-error01': '{% if %}yes{% endif %}'}) + @setup({"if-tag-error01": "{% if %}yes{% endif %}"}) def test_if_tag_error01(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('if-tag-error01') + self.engine.get_template("if-tag-error01") - @setup({'if-tag-error02': '{% if foo and %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-error02": "{% if foo and %}yes{% else %}no{% endif %}"}) def test_if_tag_error02(self): with self.assertRaises(TemplateSyntaxError): - self.engine.render_to_string('if-tag-error02', {'foo': True}) + self.engine.render_to_string("if-tag-error02", {"foo": True}) - @setup({'if-tag-error03': '{% if foo or %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-error03": "{% if foo or %}yes{% else %}no{% endif %}"}) def test_if_tag_error03(self): with self.assertRaises(TemplateSyntaxError): - self.engine.render_to_string('if-tag-error03', {'foo': True}) + self.engine.render_to_string("if-tag-error03", {"foo": True}) - @setup({'if-tag-error04': '{% if not foo and %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-error04": "{% if not foo and %}yes{% else %}no{% endif %}"}) def test_if_tag_error04(self): with self.assertRaises(TemplateSyntaxError): - self.engine.render_to_string('if-tag-error04', {'foo': True}) + self.engine.render_to_string("if-tag-error04", {"foo": True}) - @setup({'if-tag-error05': '{% if not foo or %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-error05": "{% if not foo or %}yes{% else %}no{% endif %}"}) def test_if_tag_error05(self): with self.assertRaises(TemplateSyntaxError): - self.engine.render_to_string('if-tag-error05', {'foo': True}) + self.engine.render_to_string("if-tag-error05", {"foo": True}) - @setup({'if-tag-error06': '{% if abc def %}yes{% endif %}'}) + @setup({"if-tag-error06": "{% if abc def %}yes{% endif %}"}) def test_if_tag_error06(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('if-tag-error06') + self.engine.get_template("if-tag-error06") - @setup({'if-tag-error07': '{% if not %}yes{% endif %}'}) + @setup({"if-tag-error07": "{% if not %}yes{% endif %}"}) def test_if_tag_error07(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('if-tag-error07') + self.engine.get_template("if-tag-error07") - @setup({'if-tag-error08': '{% if and %}yes{% endif %}'}) + @setup({"if-tag-error08": "{% if and %}yes{% endif %}"}) def test_if_tag_error08(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('if-tag-error08') + self.engine.get_template("if-tag-error08") - @setup({'if-tag-error09': '{% if or %}yes{% endif %}'}) + @setup({"if-tag-error09": "{% if or %}yes{% endif %}"}) def test_if_tag_error09(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('if-tag-error09') + self.engine.get_template("if-tag-error09") - @setup({'if-tag-error10': '{% if == %}yes{% endif %}'}) + @setup({"if-tag-error10": "{% if == %}yes{% endif %}"}) def test_if_tag_error10(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('if-tag-error10') + self.engine.get_template("if-tag-error10") - @setup({'if-tag-error11': '{% if 1 == %}yes{% endif %}'}) + @setup({"if-tag-error11": "{% if 1 == %}yes{% endif %}"}) def test_if_tag_error11(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('if-tag-error11') + self.engine.get_template("if-tag-error11") - @setup({'if-tag-error12': '{% if a not b %}yes{% endif %}'}) + @setup({"if-tag-error12": "{% if a not b %}yes{% endif %}"}) def test_if_tag_error12(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('if-tag-error12') + self.engine.get_template("if-tag-error12") - @setup({'else-if-tag-error01': '{% if foo is bar %} yes {% else if foo is not bar %} no {% endif %}'}) + @setup( + { + "else-if-tag-error01": "{% if foo is bar %} yes {% else if foo is not bar %} no {% endif %}" + } + ) def test_else_if_tag_error01(self): error_message = 'Malformed template tag at line 1: "else if foo is not bar"' with self.assertRaisesMessage(TemplateSyntaxError, error_message): - self.engine.get_template('else-if-tag-error01') + self.engine.get_template("else-if-tag-error01") - @setup({'if-tag-shortcircuit01': '{% if x.is_true or x.is_bad %}yes{% else %}no{% endif %}'}) + @setup( + { + "if-tag-shortcircuit01": "{% if x.is_true or x.is_bad %}yes{% else %}no{% endif %}" + } + ) def test_if_tag_shortcircuit01(self): """ If evaluations are shortcircuited where possible """ - output = self.engine.render_to_string('if-tag-shortcircuit01', {'x': TestObj()}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string("if-tag-shortcircuit01", {"x": TestObj()}) + self.assertEqual(output, "yes") - @setup({'if-tag-shortcircuit02': '{% if x.is_false and x.is_bad %}yes{% else %}no{% endif %}'}) + @setup( + { + "if-tag-shortcircuit02": "{% if x.is_false and x.is_bad %}yes{% else %}no{% endif %}" + } + ) def test_if_tag_shortcircuit02(self): """ The is_bad() function should not be evaluated. If it is, an exception is raised. """ - output = self.engine.render_to_string('if-tag-shortcircuit02', {'x': TestObj()}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string("if-tag-shortcircuit02", {"x": TestObj()}) + self.assertEqual(output, "no") - @setup({'if-tag-badarg01': '{% if x|default_if_none:y %}yes{% endif %}'}) + @setup({"if-tag-badarg01": "{% if x|default_if_none:y %}yes{% endif %}"}) def test_if_tag_badarg01(self): """Nonexistent args""" - output = self.engine.render_to_string('if-tag-badarg01') - self.assertEqual(output, '') + output = self.engine.render_to_string("if-tag-badarg01") + self.assertEqual(output, "") - @setup({'if-tag-badarg02': '{% if x|default_if_none:y %}yes{% endif %}'}) + @setup({"if-tag-badarg02": "{% if x|default_if_none:y %}yes{% endif %}"}) def test_if_tag_badarg02(self): - output = self.engine.render_to_string('if-tag-badarg02', {'y': 0}) - self.assertEqual(output, '') + output = self.engine.render_to_string("if-tag-badarg02", {"y": 0}) + self.assertEqual(output, "") - @setup({'if-tag-badarg03': '{% if x|default_if_none:y %}yes{% endif %}'}) + @setup({"if-tag-badarg03": "{% if x|default_if_none:y %}yes{% endif %}"}) def test_if_tag_badarg03(self): - output = self.engine.render_to_string('if-tag-badarg03', {'y': 1}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string("if-tag-badarg03", {"y": 1}) + self.assertEqual(output, "yes") - @setup({'if-tag-badarg04': '{% if x|default_if_none:y %}yes{% else %}no{% endif %}'}) + @setup( + {"if-tag-badarg04": "{% if x|default_if_none:y %}yes{% else %}no{% endif %}"} + ) def test_if_tag_badarg04(self): - output = self.engine.render_to_string('if-tag-badarg04') - self.assertEqual(output, 'no') + output = self.engine.render_to_string("if-tag-badarg04") + self.assertEqual(output, "no") - @setup({'if-tag-single-eq': '{% if foo = bar %}yes{% else %}no{% endif %}'}) + @setup({"if-tag-single-eq": "{% if foo = bar %}yes{% else %}no{% endif %}"}) def test_if_tag_single_eq(self): # A single equals sign is a syntax error. with self.assertRaises(TemplateSyntaxError): - self.engine.render_to_string('if-tag-single-eq', {'foo': 1}) + self.engine.render_to_string("if-tag-single-eq", {"foo": 1}) - @setup({'template': '{% if foo is True %}yes{% else %}no{% endif %}'}) + @setup({"template": "{% if foo is True %}yes{% else %}no{% endif %}"}) def test_if_is_match(self): - output = self.engine.render_to_string('template', {'foo': True}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string("template", {"foo": True}) + self.assertEqual(output, "yes") - @setup({'template': '{% if foo is True %}yes{% else %}no{% endif %}'}) + @setup({"template": "{% if foo is True %}yes{% else %}no{% endif %}"}) def test_if_is_no_match(self): - output = self.engine.render_to_string('template', {'foo': 1}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string("template", {"foo": 1}) + self.assertEqual(output, "no") - @setup({'template': '{% if foo is bar %}yes{% else %}no{% endif %}'}) + @setup({"template": "{% if foo is bar %}yes{% else %}no{% endif %}"}) def test_if_is_variable_missing(self): - output = self.engine.render_to_string('template', {'foo': 1}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string("template", {"foo": 1}) + self.assertEqual(output, "no") - @setup({'template': '{% if foo is bar %}yes{% else %}no{% endif %}'}) + @setup({"template": "{% if foo is bar %}yes{% else %}no{% endif %}"}) def test_if_is_both_variables_missing(self): - output = self.engine.render_to_string('template', {}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string("template", {}) + self.assertEqual(output, "yes") - @setup({'template': '{% if foo is not None %}yes{% else %}no{% endif %}'}) + @setup({"template": "{% if foo is not None %}yes{% else %}no{% endif %}"}) def test_if_is_not_match(self): # For this to act as a regression test, it's important not to use # foo=True because True is (not None) - output = self.engine.render_to_string('template', {'foo': False}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string("template", {"foo": False}) + self.assertEqual(output, "yes") - @setup({'template': '{% if foo is not None %}yes{% else %}no{% endif %}'}) + @setup({"template": "{% if foo is not None %}yes{% else %}no{% endif %}"}) def test_if_is_not_no_match(self): - output = self.engine.render_to_string('template', {'foo': None}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string("template", {"foo": None}) + self.assertEqual(output, "no") - @setup({'template': '{% if foo is not bar %}yes{% else %}no{% endif %}'}) + @setup({"template": "{% if foo is not bar %}yes{% else %}no{% endif %}"}) def test_if_is_not_variable_missing(self): - output = self.engine.render_to_string('template', {'foo': False}) - self.assertEqual(output, 'yes') + output = self.engine.render_to_string("template", {"foo": False}) + self.assertEqual(output, "yes") - @setup({'template': '{% if foo is not bar %}yes{% else %}no{% endif %}'}) + @setup({"template": "{% if foo is not bar %}yes{% else %}no{% endif %}"}) def test_if_is_not_both_variables_missing(self): - output = self.engine.render_to_string('template', {}) - self.assertEqual(output, 'no') + output = self.engine.render_to_string("template", {}) + self.assertEqual(output, "no") class IfNodeTests(SimpleTestCase): def test_repr(self): node = IfNode(conditions_nodelists=[]) - self.assertEqual(repr(node), '<IfNode>') + self.assertEqual(repr(node), "<IfNode>") diff --git a/tests/template_tests/syntax_tests/test_if_changed.py b/tests/template_tests/syntax_tests/test_if_changed.py index fd48a42389..3835e52d78 100644 --- a/tests/template_tests/syntax_tests/test_if_changed.py +++ b/tests/template_tests/syntax_tests/test_if_changed.py @@ -5,159 +5,255 @@ from ..utils import setup class IfChangedTagTests(SimpleTestCase): - libraries = {'custom': 'template_tests.templatetags.custom'} + libraries = {"custom": "template_tests.templatetags.custom"} - @setup({'ifchanged01': '{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}'}) + @setup( + { + "ifchanged01": "{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}" + } + ) def test_ifchanged01(self): - output = self.engine.render_to_string('ifchanged01', {'num': (1, 2, 3)}) - self.assertEqual(output, '123') + output = self.engine.render_to_string("ifchanged01", {"num": (1, 2, 3)}) + self.assertEqual(output, "123") - @setup({'ifchanged02': '{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}'}) + @setup( + { + "ifchanged02": "{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}" + } + ) def test_ifchanged02(self): - output = self.engine.render_to_string('ifchanged02', {'num': (1, 1, 3)}) - self.assertEqual(output, '13') + output = self.engine.render_to_string("ifchanged02", {"num": (1, 1, 3)}) + self.assertEqual(output, "13") - @setup({'ifchanged03': '{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}'}) + @setup( + { + "ifchanged03": "{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}" + } + ) def test_ifchanged03(self): - output = self.engine.render_to_string('ifchanged03', {'num': (1, 1, 1)}) - self.assertEqual(output, '1') + output = self.engine.render_to_string("ifchanged03", {"num": (1, 1, 1)}) + self.assertEqual(output, "1") - @setup({'ifchanged04': '{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}' - '{% for x in numx %}{% ifchanged %}{{ x }}{% endifchanged %}' - '{% endfor %}{% endfor %}'}) + @setup( + { + "ifchanged04": "{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}" + "{% for x in numx %}{% ifchanged %}{{ x }}{% endifchanged %}" + "{% endfor %}{% endfor %}" + } + ) def test_ifchanged04(self): - output = self.engine.render_to_string('ifchanged04', {'num': (1, 2, 3), 'numx': (2, 2, 2)}) - self.assertEqual(output, '122232') + output = self.engine.render_to_string( + "ifchanged04", {"num": (1, 2, 3), "numx": (2, 2, 2)} + ) + self.assertEqual(output, "122232") - @setup({'ifchanged05': '{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}' - '{% for x in numx %}{% ifchanged %}{{ x }}{% endifchanged %}' - '{% endfor %}{% endfor %}'}) + @setup( + { + "ifchanged05": "{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}" + "{% for x in numx %}{% ifchanged %}{{ x }}{% endifchanged %}" + "{% endfor %}{% endfor %}" + } + ) def test_ifchanged05(self): - output = self.engine.render_to_string('ifchanged05', {'num': (1, 1, 1), 'numx': (1, 2, 3)}) - self.assertEqual(output, '1123123123') + output = self.engine.render_to_string( + "ifchanged05", {"num": (1, 1, 1), "numx": (1, 2, 3)} + ) + self.assertEqual(output, "1123123123") - @setup({'ifchanged06': '{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}' - '{% for x in numx %}{% ifchanged %}{{ x }}{% endifchanged %}' - '{% endfor %}{% endfor %}'}) + @setup( + { + "ifchanged06": "{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}" + "{% for x in numx %}{% ifchanged %}{{ x }}{% endifchanged %}" + "{% endfor %}{% endfor %}" + } + ) def test_ifchanged06(self): - output = self.engine.render_to_string('ifchanged06', {'num': (1, 1, 1), 'numx': (2, 2, 2)}) - self.assertEqual(output, '1222') + output = self.engine.render_to_string( + "ifchanged06", {"num": (1, 1, 1), "numx": (2, 2, 2)} + ) + self.assertEqual(output, "1222") - @setup({'ifchanged07': '{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}' - '{% for x in numx %}{% ifchanged %}{{ x }}{% endifchanged %}' - '{% for y in numy %}{% ifchanged %}{{ y }}{% endifchanged %}' - '{% endfor %}{% endfor %}{% endfor %}'}) + @setup( + { + "ifchanged07": "{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}" + "{% for x in numx %}{% ifchanged %}{{ x }}{% endifchanged %}" + "{% for y in numy %}{% ifchanged %}{{ y }}{% endifchanged %}" + "{% endfor %}{% endfor %}{% endfor %}" + } + ) def test_ifchanged07(self): - output = self.engine.render_to_string('ifchanged07', {'num': (1, 1, 1), 'numx': (2, 2, 2), 'numy': (3, 3, 3)}) - self.assertEqual(output, '1233323332333') + output = self.engine.render_to_string( + "ifchanged07", {"num": (1, 1, 1), "numx": (2, 2, 2), "numy": (3, 3, 3)} + ) + self.assertEqual(output, "1233323332333") - @setup({'ifchanged08': '{% for data in datalist %}{% for c,d in data %}' - '{% if c %}{% ifchanged %}{{ d }}{% endifchanged %}' - '{% endif %}{% endfor %}{% endfor %}'}) + @setup( + { + "ifchanged08": "{% for data in datalist %}{% for c,d in data %}" + "{% if c %}{% ifchanged %}{{ d }}{% endifchanged %}" + "{% endif %}{% endfor %}{% endfor %}" + } + ) def test_ifchanged08(self): - output = self.engine.render_to_string('ifchanged08', {'datalist': [ - [(1, 'a'), (1, 'a'), (0, 'b'), (1, 'c')], - [(0, 'a'), (1, 'c'), (1, 'd'), (1, 'd'), (0, 'e')] - ]}) - self.assertEqual(output, 'accd') + output = self.engine.render_to_string( + "ifchanged08", + { + "datalist": [ + [(1, "a"), (1, "a"), (0, "b"), (1, "c")], + [(0, "a"), (1, "c"), (1, "d"), (1, "d"), (0, "e")], + ] + }, + ) + self.assertEqual(output, "accd") - @setup({'ifchanged-param01': '{% for n in num %}{% ifchanged n %}..{% endifchanged %}' - '{{ n }}{% endfor %}'}) + @setup( + { + "ifchanged-param01": "{% for n in num %}{% ifchanged n %}..{% endifchanged %}" + "{{ n }}{% endfor %}" + } + ) def test_ifchanged_param01(self): """ Test one parameter given to ifchanged. """ - output = self.engine.render_to_string('ifchanged-param01', {'num': (1, 2, 3)}) - self.assertEqual(output, '..1..2..3') + output = self.engine.render_to_string("ifchanged-param01", {"num": (1, 2, 3)}) + self.assertEqual(output, "..1..2..3") - @setup({'ifchanged-param02': '{% for n in num %}{% for x in numx %}{% ifchanged n %}..{% endifchanged %}' - '{{ x }}{% endfor %}{% endfor %}'}) + @setup( + { + "ifchanged-param02": "{% for n in num %}{% for x in numx %}{% ifchanged n %}..{% endifchanged %}" + "{{ x }}{% endfor %}{% endfor %}" + } + ) def test_ifchanged_param02(self): - output = self.engine.render_to_string('ifchanged-param02', {'num': (1, 2, 3), 'numx': (5, 6, 7)}) - self.assertEqual(output, '..567..567..567') + output = self.engine.render_to_string( + "ifchanged-param02", {"num": (1, 2, 3), "numx": (5, 6, 7)} + ) + self.assertEqual(output, "..567..567..567") - @setup({'ifchanged-param03': '{% for n in num %}{{ n }}{% for x in numx %}' - '{% ifchanged x n %}{{ x }}{% endifchanged %}' - '{% endfor %}{% endfor %}'}) + @setup( + { + "ifchanged-param03": "{% for n in num %}{{ n }}{% for x in numx %}" + "{% ifchanged x n %}{{ x }}{% endifchanged %}" + "{% endfor %}{% endfor %}" + } + ) def test_ifchanged_param03(self): """ Test multiple parameters to ifchanged. """ - output = self.engine.render_to_string('ifchanged-param03', {'num': (1, 1, 2), 'numx': (5, 6, 6)}) - self.assertEqual(output, '156156256') + output = self.engine.render_to_string( + "ifchanged-param03", {"num": (1, 1, 2), "numx": (5, 6, 6)} + ) + self.assertEqual(output, "156156256") - @setup({'ifchanged-param04': '{% for d in days %}{% ifchanged %}{{ d.day }}{% endifchanged %}' - '{% for h in d.hours %}{% ifchanged d h %}{{ h }}{% endifchanged %}' - '{% endfor %}{% endfor %}'}) + @setup( + { + "ifchanged-param04": "{% for d in days %}{% ifchanged %}{{ d.day }}{% endifchanged %}" + "{% for h in d.hours %}{% ifchanged d h %}{{ h }}{% endifchanged %}" + "{% endfor %}{% endfor %}" + } + ) def test_ifchanged_param04(self): """ Test a date+hour like construct, where the hour of the last day is the same but the date had changed, so print the hour anyway. """ output = self.engine.render_to_string( - 'ifchanged-param04', - {'days': [{'hours': [1, 2, 3], 'day': 1}, {'hours': [3], 'day': 2}]}, + "ifchanged-param04", + {"days": [{"hours": [1, 2, 3], "day": 1}, {"hours": [3], "day": 2}]}, ) - self.assertEqual(output, '112323') + self.assertEqual(output, "112323") - @setup({'ifchanged-param05': '{% for d in days %}{% ifchanged d.day %}{{ d.day }}{% endifchanged %}' - '{% for h in d.hours %}{% ifchanged d.day h %}{{ h }}{% endifchanged %}' - '{% endfor %}{% endfor %}'}) + @setup( + { + "ifchanged-param05": "{% for d in days %}{% ifchanged d.day %}{{ d.day }}{% endifchanged %}" + "{% for h in d.hours %}{% ifchanged d.day h %}{{ h }}{% endifchanged %}" + "{% endfor %}{% endfor %}" + } + ) def test_ifchanged_param05(self): """ Logically the same as above, just written with explicit ifchanged for the day. """ output = self.engine.render_to_string( - 'ifchanged-param05', - {'days': [{'hours': [1, 2, 3], 'day': 1}, {'hours': [3], 'day': 2}]}, + "ifchanged-param05", + {"days": [{"hours": [1, 2, 3], "day": 1}, {"hours": [3], "day": 2}]}, ) - self.assertEqual(output, '112323') + self.assertEqual(output, "112323") - @setup({'ifchanged-else01': '{% for id in ids %}{{ id }}' - '{% ifchanged id %}-first{% else %}-other{% endifchanged %}' - ',{% endfor %}'}) + @setup( + { + "ifchanged-else01": "{% for id in ids %}{{ id }}" + "{% ifchanged id %}-first{% else %}-other{% endifchanged %}" + ",{% endfor %}" + } + ) def test_ifchanged_else01(self): """ Test the else clause of ifchanged. """ - output = self.engine.render_to_string('ifchanged-else01', {'ids': [1, 1, 2, 2, 2, 3]}) - self.assertEqual(output, '1-first,1-other,2-first,2-other,2-other,3-first,') + output = self.engine.render_to_string( + "ifchanged-else01", {"ids": [1, 1, 2, 2, 2, 3]} + ) + self.assertEqual(output, "1-first,1-other,2-first,2-other,2-other,3-first,") - @setup({'ifchanged-else02': '{% for id in ids %}{{ id }}-' - '{% ifchanged id %}{% cycle "red" "blue" %}{% else %}gray{% endifchanged %}' - ',{% endfor %}'}) + @setup( + { + "ifchanged-else02": "{% for id in ids %}{{ id }}-" + '{% ifchanged id %}{% cycle "red" "blue" %}{% else %}gray{% endifchanged %}' + ",{% endfor %}" + } + ) def test_ifchanged_else02(self): - output = self.engine.render_to_string('ifchanged-else02', {'ids': [1, 1, 2, 2, 2, 3]}) - self.assertEqual(output, '1-red,1-gray,2-blue,2-gray,2-gray,3-red,') + output = self.engine.render_to_string( + "ifchanged-else02", {"ids": [1, 1, 2, 2, 2, 3]} + ) + self.assertEqual(output, "1-red,1-gray,2-blue,2-gray,2-gray,3-red,") - @setup({'ifchanged-else03': '{% for id in ids %}{{ id }}' - '{% ifchanged id %}-{% cycle "red" "blue" %}{% else %}{% endifchanged %}' - ',{% endfor %}'}) + @setup( + { + "ifchanged-else03": "{% for id in ids %}{{ id }}" + '{% ifchanged id %}-{% cycle "red" "blue" %}{% else %}{% endifchanged %}' + ",{% endfor %}" + } + ) def test_ifchanged_else03(self): - output = self.engine.render_to_string('ifchanged-else03', {'ids': [1, 1, 2, 2, 2, 3]}) - self.assertEqual(output, '1-red,1,2-blue,2,2,3-red,') + output = self.engine.render_to_string( + "ifchanged-else03", {"ids": [1, 1, 2, 2, 2, 3]} + ) + self.assertEqual(output, "1-red,1,2-blue,2,2,3-red,") - @setup({'ifchanged-else04': '{% for id in ids %}' - '{% ifchanged %}***{{ id }}*{% else %}...{% endifchanged %}' - '{{ forloop.counter }}{% endfor %}'}) + @setup( + { + "ifchanged-else04": "{% for id in ids %}" + "{% ifchanged %}***{{ id }}*{% else %}...{% endifchanged %}" + "{{ forloop.counter }}{% endfor %}" + } + ) def test_ifchanged_else04(self): - output = self.engine.render_to_string('ifchanged-else04', {'ids': [1, 1, 2, 2, 2, 3, 4]}) - self.assertEqual(output, '***1*1...2***2*3...4...5***3*6***4*7') + output = self.engine.render_to_string( + "ifchanged-else04", {"ids": [1, 1, 2, 2, 2, 3, 4]} + ) + self.assertEqual(output, "***1*1...2***2*3...4...5***3*6***4*7") - @setup({'ifchanged-filter-ws': '{% load custom %}{% for n in num %}' - '{% ifchanged n|noop:"x y" %}..{% endifchanged %}{{ n }}' - '{% endfor %}'}) + @setup( + { + "ifchanged-filter-ws": "{% load custom %}{% for n in num %}" + '{% ifchanged n|noop:"x y" %}..{% endifchanged %}{{ n }}' + "{% endfor %}" + } + ) def test_ifchanged_filter_ws(self): """ Test whitespace in filter arguments """ - output = self.engine.render_to_string('ifchanged-filter-ws', {'num': (1, 2, 3)}) - self.assertEqual(output, '..1..2..3') + output = self.engine.render_to_string("ifchanged-filter-ws", {"num": (1, 2, 3)}) + self.assertEqual(output, "..1..2..3") class IfChangedTests(SimpleTestCase): - @classmethod def setUpClass(cls): cls.engine = Engine() @@ -168,8 +264,8 @@ class IfChangedTests(SimpleTestCase): #15849 -- ifchanged should be thread-safe. """ template = self.engine.from_string( - '[0{% for x in foo %},{% with var=get_value %}{% ifchanged %}' - '{{ var }}{% endifchanged %}{% endwith %}{% endfor %}]' + "[0{% for x in foo %},{% with var=get_value %}{% ifchanged %}" + "{{ var }}{% endifchanged %}{% endwith %}{% endfor %}]" ) # Using generator to mimic concurrency. @@ -181,45 +277,69 @@ class IfChangedTests(SimpleTestCase): # Simulate that another thread is now rendering. # When the IfChangeNode stores state at 'self' it stays at '3' and skip the last yielded value below. iter2 = iter([1, 2, 3]) - output2 = template.render(Context({'foo': range(3), 'get_value': lambda: next(iter2)})) + output2 = template.render( + Context({"foo": range(3), "get_value": lambda: next(iter2)}) + ) self.assertEqual( - output2, '[0,1,2,3]', 'Expected [0,1,2,3] in second parallel template, got {}'.format(output2) + output2, + "[0,1,2,3]", + "Expected [0,1,2,3] in second parallel template, got {}".format( + output2 + ), ) yield 3 gen1 = gen() - output1 = template.render(Context({'foo': range(3), 'get_value': lambda: next(gen1)})) - self.assertEqual(output1, '[0,1,2,3]', 'Expected [0,1,2,3] in first template, got {}'.format(output1)) + output1 = template.render( + Context({"foo": range(3), "get_value": lambda: next(gen1)}) + ) + self.assertEqual( + output1, + "[0,1,2,3]", + "Expected [0,1,2,3] in first template, got {}".format(output1), + ) def test_ifchanged_render_once(self): """ #19890. The content of ifchanged template tag was rendered twice. """ - template = self.engine.from_string('{% ifchanged %}{% cycle "1st time" "2nd time" %}{% endifchanged %}') + template = self.engine.from_string( + '{% ifchanged %}{% cycle "1st time" "2nd time" %}{% endifchanged %}' + ) output = template.render(Context({})) - self.assertEqual(output, '1st time') + self.assertEqual(output, "1st time") def test_include(self): """ #23516 -- This works as a regression test only if the cached loader isn't used. Hence we don't use the @setup decorator. """ - engine = Engine(loaders=[ - ('django.template.loaders.locmem.Loader', { - 'template': '{% for x in vars %}{% include "include" %}{% endfor %}', - 'include': '{% ifchanged %}{{ x }}{% endifchanged %}', - }), - ]) - output = engine.render_to_string('template', {'vars': [1, 1, 2, 2, 3, 3]}) + engine = Engine( + loaders=[ + ( + "django.template.loaders.locmem.Loader", + { + "template": '{% for x in vars %}{% include "include" %}{% endfor %}', + "include": "{% ifchanged %}{{ x }}{% endifchanged %}", + }, + ), + ] + ) + output = engine.render_to_string("template", {"vars": [1, 1, 2, 2, 3, 3]}) self.assertEqual(output, "123") def test_include_state(self): """Tests the node state for different IncludeNodes (#27974).""" - engine = Engine(loaders=[ - ('django.template.loaders.locmem.Loader', { - 'template': '{% for x in vars %}{% include "include" %}{% include "include" %}{% endfor %}', - 'include': '{% ifchanged %}{{ x }}{% endifchanged %}', - }), - ]) - output = engine.render_to_string('template', {'vars': [1, 1, 2, 2, 3, 3]}) - self.assertEqual(output, '112233') + engine = Engine( + loaders=[ + ( + "django.template.loaders.locmem.Loader", + { + "template": '{% for x in vars %}{% include "include" %}{% include "include" %}{% endfor %}', + "include": "{% ifchanged %}{{ x }}{% endifchanged %}", + }, + ), + ] + ) + output = engine.render_to_string("template", {"vars": [1, 1, 2, 2, 3, 3]}) + self.assertEqual(output, "112233") diff --git a/tests/template_tests/syntax_tests/test_include.py b/tests/template_tests/syntax_tests/test_include.py index 6dac87b7f2..add2ca139f 100644 --- a/tests/template_tests/syntax_tests/test_include.py +++ b/tests/template_tests/syntax_tests/test_include.py @@ -1,5 +1,9 @@ from django.template import ( - Context, Engine, TemplateDoesNotExist, TemplateSyntaxError, loader, + Context, + Engine, + TemplateDoesNotExist, + TemplateSyntaxError, + loader, ) from django.template.loader_tags import IncludeNode from django.test import SimpleTestCase @@ -8,201 +12,227 @@ from ..utils import setup from .test_basic import basic_templates include_fail_templates = { - 'include-fail1': '{% load bad_tag %}{% badtag %}', - 'include-fail2': '{% load broken_tag %}', + "include-fail1": "{% load bad_tag %}{% badtag %}", + "include-fail2": "{% load broken_tag %}", } class IncludeTagTests(SimpleTestCase): - libraries = {'bad_tag': 'template_tests.templatetags.bad_tag'} + libraries = {"bad_tag": "template_tests.templatetags.bad_tag"} - @setup({'include01': '{% include "basic-syntax01" %}'}, basic_templates) + @setup({"include01": '{% include "basic-syntax01" %}'}, basic_templates) def test_include01(self): - output = self.engine.render_to_string('include01') - self.assertEqual(output, 'something cool') + output = self.engine.render_to_string("include01") + self.assertEqual(output, "something cool") - @setup({'include02': '{% include "basic-syntax02" %}'}, basic_templates) + @setup({"include02": '{% include "basic-syntax02" %}'}, basic_templates) def test_include02(self): - output = self.engine.render_to_string('include02', {'headline': 'Included'}) - self.assertEqual(output, 'Included') + output = self.engine.render_to_string("include02", {"headline": "Included"}) + self.assertEqual(output, "Included") - @setup({'include03': '{% include template_name %}'}, basic_templates) + @setup({"include03": "{% include template_name %}"}, basic_templates) def test_include03(self): output = self.engine.render_to_string( - 'include03', - {'template_name': 'basic-syntax02', 'headline': 'Included'}, + "include03", + {"template_name": "basic-syntax02", "headline": "Included"}, ) - self.assertEqual(output, 'Included') + self.assertEqual(output, "Included") - @setup({'include04': 'a{% include "nonexistent" %}b'}) + @setup({"include04": 'a{% include "nonexistent" %}b'}) def test_include04(self): - template = self.engine.get_template('include04') + template = self.engine.get_template("include04") with self.assertRaises(TemplateDoesNotExist): template.render(Context({})) - @setup({ - 'include 05': 'template with a space', - 'include06': '{% include "include 05"%}', - }) + @setup( + { + "include 05": "template with a space", + "include06": '{% include "include 05"%}', + } + ) def test_include06(self): - output = self.engine.render_to_string('include06') + output = self.engine.render_to_string("include06") self.assertEqual(output, "template with a space") - @setup({'include07': '{% include "basic-syntax02" with headline="Inline" %}'}, basic_templates) + @setup( + {"include07": '{% include "basic-syntax02" with headline="Inline" %}'}, + basic_templates, + ) def test_include07(self): - output = self.engine.render_to_string('include07', {'headline': 'Included'}) - self.assertEqual(output, 'Inline') + output = self.engine.render_to_string("include07", {"headline": "Included"}) + self.assertEqual(output, "Inline") - @setup({'include08': '{% include headline with headline="Dynamic" %}'}, basic_templates) + @setup( + {"include08": '{% include headline with headline="Dynamic" %}'}, basic_templates + ) def test_include08(self): - output = self.engine.render_to_string('include08', {'headline': 'basic-syntax02'}) - self.assertEqual(output, 'Dynamic') + output = self.engine.render_to_string( + "include08", {"headline": "basic-syntax02"} + ) + self.assertEqual(output, "Dynamic") @setup( - {'include09': '{{ first }}--' - '{% include "basic-syntax03" with first=second|lower|upper second=first|upper %}' - '--{{ second }}'}, + { + "include09": "{{ first }}--" + '{% include "basic-syntax03" with first=second|lower|upper second=first|upper %}' + "--{{ second }}" + }, basic_templates, ) def test_include09(self): - output = self.engine.render_to_string('include09', {'first': 'Ul', 'second': 'lU'}) - self.assertEqual(output, 'Ul--LU --- UL--lU') + output = self.engine.render_to_string( + "include09", {"first": "Ul", "second": "lU"} + ) + self.assertEqual(output, "Ul--LU --- UL--lU") - @setup({'include10': '{% include "basic-syntax03" only %}'}, basic_templates) + @setup({"include10": '{% include "basic-syntax03" only %}'}, basic_templates) def test_include10(self): - output = self.engine.render_to_string('include10', {'first': '1'}) + output = self.engine.render_to_string("include10", {"first": "1"}) if self.engine.string_if_invalid: - self.assertEqual(output, 'INVALID --- INVALID') + self.assertEqual(output, "INVALID --- INVALID") else: - self.assertEqual(output, ' --- ') + self.assertEqual(output, " --- ") - @setup({'include11': '{% include "basic-syntax03" only with second=2 %}'}, basic_templates) + @setup( + {"include11": '{% include "basic-syntax03" only with second=2 %}'}, + basic_templates, + ) def test_include11(self): - output = self.engine.render_to_string('include11', {'first': '1'}) + output = self.engine.render_to_string("include11", {"first": "1"}) if self.engine.string_if_invalid: - self.assertEqual(output, 'INVALID --- 2') + self.assertEqual(output, "INVALID --- 2") else: - self.assertEqual(output, ' --- 2') + self.assertEqual(output, " --- 2") - @setup({'include12': '{% include "basic-syntax03" with first=1 only %}'}, basic_templates) + @setup( + {"include12": '{% include "basic-syntax03" with first=1 only %}'}, + basic_templates, + ) def test_include12(self): - output = self.engine.render_to_string('include12', {'second': '2'}) + output = self.engine.render_to_string("include12", {"second": "2"}) if self.engine.string_if_invalid: - self.assertEqual(output, '1 --- INVALID') + self.assertEqual(output, "1 --- INVALID") else: - self.assertEqual(output, '1 --- ') + self.assertEqual(output, "1 --- ") @setup( - {'include13': '{% autoescape off %}{% include "basic-syntax03" %}{% endautoescape %}'}, + { + "include13": '{% autoescape off %}{% include "basic-syntax03" %}{% endautoescape %}' + }, basic_templates, ) def test_include13(self): - output = self.engine.render_to_string('include13', {'first': '&'}) + output = self.engine.render_to_string("include13", {"first": "&"}) if self.engine.string_if_invalid: - self.assertEqual(output, '& --- INVALID') + self.assertEqual(output, "& --- INVALID") else: - self.assertEqual(output, '& --- ') + self.assertEqual(output, "& --- ") @setup( - {'include14': '{% autoescape off %}' - '{% include "basic-syntax03" with first=var1 only %}' - '{% endautoescape %}'}, + { + "include14": "{% autoescape off %}" + '{% include "basic-syntax03" with first=var1 only %}' + "{% endautoescape %}" + }, basic_templates, ) def test_include14(self): - output = self.engine.render_to_string('include14', {'var1': '&'}) + output = self.engine.render_to_string("include14", {"var1": "&"}) if self.engine.string_if_invalid: - self.assertEqual(output, '& --- INVALID') + self.assertEqual(output, "& --- INVALID") else: - self.assertEqual(output, '& --- ') + self.assertEqual(output, "& --- ") # Include syntax errors - @setup({'include-error01': '{% include "basic-syntax01" with %}'}) + @setup({"include-error01": '{% include "basic-syntax01" with %}'}) def test_include_error01(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('include-error01') + self.engine.get_template("include-error01") - @setup({'include-error02': '{% include "basic-syntax01" with "no key" %}'}) + @setup({"include-error02": '{% include "basic-syntax01" with "no key" %}'}) def test_include_error02(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('include-error02') + self.engine.get_template("include-error02") - @setup({'include-error03': '{% include "basic-syntax01" with dotted.arg="error" %}'}) + @setup( + {"include-error03": '{% include "basic-syntax01" with dotted.arg="error" %}'} + ) def test_include_error03(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('include-error03') + self.engine.get_template("include-error03") - @setup({'include-error04': '{% include "basic-syntax01" something_random %}'}) + @setup({"include-error04": '{% include "basic-syntax01" something_random %}'}) def test_include_error04(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('include-error04') + self.engine.get_template("include-error04") - @setup({'include-error05': '{% include "basic-syntax01" foo="duplicate" foo="key" %}'}) + @setup( + {"include-error05": '{% include "basic-syntax01" foo="duplicate" foo="key" %}'} + ) def test_include_error05(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('include-error05') + self.engine.get_template("include-error05") - @setup({'include-error06': '{% include "basic-syntax01" only only %}'}) + @setup({"include-error06": '{% include "basic-syntax01" only only %}'}) def test_include_error06(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('include-error06') + self.engine.get_template("include-error06") @setup(include_fail_templates) def test_include_fail1(self): with self.assertRaises(RuntimeError): - self.engine.get_template('include-fail1') + self.engine.get_template("include-fail1") @setup(include_fail_templates) def test_include_fail2(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('include-fail2') + self.engine.get_template("include-fail2") - @setup({'include-error07': '{% include "include-fail1" %}'}, include_fail_templates) + @setup({"include-error07": '{% include "include-fail1" %}'}, include_fail_templates) def test_include_error07(self): - template = self.engine.get_template('include-error07') + template = self.engine.get_template("include-error07") with self.assertRaises(RuntimeError): template.render(Context()) - @setup({'include-error08': '{% include "include-fail2" %}'}, include_fail_templates) + @setup({"include-error08": '{% include "include-fail2" %}'}, include_fail_templates) def test_include_error08(self): - template = self.engine.get_template('include-error08') + template = self.engine.get_template("include-error08") with self.assertRaises(TemplateSyntaxError): template.render(Context()) - @setup({'include-error09': '{% include failed_include %}'}, include_fail_templates) + @setup({"include-error09": "{% include failed_include %}"}, include_fail_templates) def test_include_error09(self): - context = Context({'failed_include': 'include-fail1'}) - template = self.engine.get_template('include-error09') + context = Context({"failed_include": "include-fail1"}) + template = self.engine.get_template("include-error09") with self.assertRaises(RuntimeError): template.render(context) - @setup({'include-error10': '{% include failed_include %}'}, include_fail_templates) + @setup({"include-error10": "{% include failed_include %}"}, include_fail_templates) def test_include_error10(self): - context = Context({'failed_include': 'include-fail2'}) - template = self.engine.get_template('include-error10') + context = Context({"failed_include": "include-fail2"}) + template = self.engine.get_template("include-error10") with self.assertRaises(TemplateSyntaxError): template.render(context) - @setup({'include_empty': '{% include %}'}) + @setup({"include_empty": "{% include %}"}) def test_include_empty(self): msg = ( "'include' tag takes at least one argument: the name of the " "template to be included." ) with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.get_template('include_empty') + self.engine.get_template("include_empty") class IncludeTests(SimpleTestCase): - def test_include_missing_template(self): """ The correct template is identified as not existing when {% include %} specifies a template that does not exist. """ engine = Engine(app_dirs=True, debug=True) - template = engine.get_template('test_include_error.html') - with self.assertRaisesMessage(TemplateDoesNotExist, 'missing.html'): + template = engine.get_template("test_include_error.html") + with self.assertRaisesMessage(TemplateDoesNotExist, "missing.html"): template.render(Context()) def test_extends_include_missing_baseloader(self): @@ -212,24 +242,30 @@ class IncludeTests(SimpleTestCase): template has an {% include %} of something that does not exist. """ engine = Engine(app_dirs=True, debug=True) - template = engine.get_template('test_extends_error.html') - with self.assertRaisesMessage(TemplateDoesNotExist, 'missing.html'): + template = engine.get_template("test_extends_error.html") + with self.assertRaisesMessage(TemplateDoesNotExist, "missing.html"): template.render(Context()) def test_extends_include_missing_cachedloader(self): - engine = Engine(debug=True, loaders=[ - ('django.template.loaders.cached.Loader', [ - 'django.template.loaders.app_directories.Loader', - ]), - ]) + engine = Engine( + debug=True, + loaders=[ + ( + "django.template.loaders.cached.Loader", + [ + "django.template.loaders.app_directories.Loader", + ], + ), + ], + ) - template = engine.get_template('test_extends_error.html') - with self.assertRaisesMessage(TemplateDoesNotExist, 'missing.html'): + template = engine.get_template("test_extends_error.html") + with self.assertRaisesMessage(TemplateDoesNotExist, "missing.html"): template.render(Context()) # Repeat to ensure it still works when loading from the cache - template = engine.get_template('test_extends_error.html') - with self.assertRaisesMessage(TemplateDoesNotExist, 'missing.html'): + template = engine.get_template("test_extends_error.html") + with self.assertRaisesMessage(TemplateDoesNotExist, "missing.html"): template.render(Context()) def test_include_template_argument(self): @@ -237,37 +273,39 @@ class IncludeTests(SimpleTestCase): Support any render() supporting object """ engine = Engine() - ctx = Context({ - 'tmpl': engine.from_string('This worked!'), - }) - outer_tmpl = engine.from_string('{% include tmpl %}') + ctx = Context( + { + "tmpl": engine.from_string("This worked!"), + } + ) + outer_tmpl = engine.from_string("{% include tmpl %}") output = outer_tmpl.render(ctx) - self.assertEqual(output, 'This worked!') + self.assertEqual(output, "This worked!") def test_include_template_iterable(self): engine = Engine.get_default() - outer_temp = engine.from_string('{% include var %}') + outer_temp = engine.from_string("{% include var %}") tests = [ - ('admin/fail.html', 'index.html'), - ['admin/fail.html', 'index.html'], + ("admin/fail.html", "index.html"), + ["admin/fail.html", "index.html"], ] for template_names in tests: with self.subTest(template_names): - output = outer_temp.render(Context({'var': template_names})) - self.assertEqual(output, 'index\n') + output = outer_temp.render(Context({"var": template_names})) + self.assertEqual(output, "index\n") def test_include_template_none(self): engine = Engine.get_default() - outer_temp = engine.from_string('{% include var %}') - ctx = Context({'var': None}) - msg = 'No template names provided' + outer_temp = engine.from_string("{% include var %}") + ctx = Context({"var": None}) + msg = "No template names provided" with self.assertRaisesMessage(TemplateDoesNotExist, msg): outer_temp.render(ctx) def test_include_from_loader_get_template(self): - tmpl = loader.get_template('include_tpl.html') # {% include tmpl %} - output = tmpl.render({'tmpl': loader.get_template('index.html')}) - self.assertEqual(output, 'index\n\n') + tmpl = loader.get_template("include_tpl.html") # {% include tmpl %} + output = tmpl.render({"tmpl": loader.get_template("index.html")}) + self.assertEqual(output, "index\n\n") def test_include_immediate_missing(self): """ @@ -279,21 +317,22 @@ class IncludeTests(SimpleTestCase): def test_include_recursive(self): comments = [ { - 'comment': 'A1', - 'children': [ - {'comment': 'B1', 'children': []}, - {'comment': 'B2', 'children': []}, - {'comment': 'B3', 'children': [ - {'comment': 'C1', 'children': []} - ]}, - ] + "comment": "A1", + "children": [ + {"comment": "B1", "children": []}, + {"comment": "B2", "children": []}, + {"comment": "B3", "children": [{"comment": "C1", "children": []}]}, + ], } ] engine = Engine(app_dirs=True) - t = engine.get_template('recursive_include.html') + t = engine.get_template("recursive_include.html") self.assertEqual( "Recursion! A1 Recursion! B1 B2 B3 Recursion! C1", - t.render(Context({'comments': comments})).replace(' ', '').replace('\n', ' ').strip(), + t.render(Context({"comments": comments})) + .replace(" ", "") + .replace("\n", " ") + .strip(), ) def test_include_cache(self): @@ -306,20 +345,26 @@ class IncludeTests(SimpleTestCase): This works as a regression test only if the cached loader isn't used, so the @setup decorator isn't used. """ - engine = Engine(loaders=[ - ('django.template.loaders.locmem.Loader', { - 'template': '{% for x in vars %}{% include "include" %}{% endfor %}', - 'include': '{% include "next" %}', - 'next': '{% load custom %}{% counter %}' - }), - ], libraries={'custom': 'template_tests.templatetags.custom'}) - output = engine.render_to_string('template', {'vars': range(9)}) - self.assertEqual(output, '012345678') + engine = Engine( + loaders=[ + ( + "django.template.loaders.locmem.Loader", + { + "template": '{% for x in vars %}{% include "include" %}{% endfor %}', + "include": '{% include "next" %}', + "next": "{% load custom %}{% counter %}", + }, + ), + ], + libraries={"custom": "template_tests.templatetags.custom"}, + ) + output = engine.render_to_string("template", {"vars": range(9)}) + self.assertEqual(output, "012345678") class IncludeNodeTests(SimpleTestCase): def test_repr(self): - include_node = IncludeNode('app/template.html') + include_node = IncludeNode("app/template.html") self.assertEqual( repr(include_node), "<IncludeNode: template='app/template.html'>", diff --git a/tests/template_tests/syntax_tests/test_invalid_string.py b/tests/template_tests/syntax_tests/test_invalid_string.py index b05abcfdf3..e65ac938ec 100644 --- a/tests/template_tests/syntax_tests/test_invalid_string.py +++ b/tests/template_tests/syntax_tests/test_invalid_string.py @@ -4,59 +4,63 @@ from ..utils import setup class InvalidStringTests(SimpleTestCase): - libraries = {'i18n': 'django.templatetags.i18n'} + libraries = {"i18n": "django.templatetags.i18n"} - @setup({'invalidstr01': '{{ var|default:"Foo" }}'}) + @setup({"invalidstr01": '{{ var|default:"Foo" }}'}) def test_invalidstr01(self): - output = self.engine.render_to_string('invalidstr01') + output = self.engine.render_to_string("invalidstr01") if self.engine.string_if_invalid: - self.assertEqual(output, 'INVALID') + self.assertEqual(output, "INVALID") else: - self.assertEqual(output, 'Foo') + self.assertEqual(output, "Foo") - @setup({'invalidstr02': '{{ var|default_if_none:"Foo" }}'}) + @setup({"invalidstr02": '{{ var|default_if_none:"Foo" }}'}) def test_invalidstr02(self): - output = self.engine.render_to_string('invalidstr02') + output = self.engine.render_to_string("invalidstr02") if self.engine.string_if_invalid: - self.assertEqual(output, 'INVALID') + self.assertEqual(output, "INVALID") else: - self.assertEqual(output, '') + self.assertEqual(output, "") - @setup({'invalidstr03': '{% for v in var %}({{ v }}){% endfor %}'}) + @setup({"invalidstr03": "{% for v in var %}({{ v }}){% endfor %}"}) def test_invalidstr03(self): - output = self.engine.render_to_string('invalidstr03') - self.assertEqual(output, '') + output = self.engine.render_to_string("invalidstr03") + self.assertEqual(output, "") - @setup({'invalidstr04': '{% if var %}Yes{% else %}No{% endif %}'}) + @setup({"invalidstr04": "{% if var %}Yes{% else %}No{% endif %}"}) def test_invalidstr04(self): - output = self.engine.render_to_string('invalidstr04') - self.assertEqual(output, 'No') + output = self.engine.render_to_string("invalidstr04") + self.assertEqual(output, "No") - @setup({'invalidstr04_2': '{% if var|default:"Foo" %}Yes{% else %}No{% endif %}'}) + @setup({"invalidstr04_2": '{% if var|default:"Foo" %}Yes{% else %}No{% endif %}'}) def test_invalidstr04_2(self): - output = self.engine.render_to_string('invalidstr04_2') - self.assertEqual(output, 'Yes') + output = self.engine.render_to_string("invalidstr04_2") + self.assertEqual(output, "Yes") - @setup({'invalidstr05': '{{ var }}'}) + @setup({"invalidstr05": "{{ var }}"}) def test_invalidstr05(self): - output = self.engine.render_to_string('invalidstr05') + output = self.engine.render_to_string("invalidstr05") if self.engine.string_if_invalid: - self.assertEqual(output, 'INVALID') + self.assertEqual(output, "INVALID") else: - self.assertEqual(output, '') + self.assertEqual(output, "") - @setup({'invalidstr06': '{{ var.prop }}'}) + @setup({"invalidstr06": "{{ var.prop }}"}) def test_invalidstr06(self): - output = self.engine.render_to_string('invalidstr06') + output = self.engine.render_to_string("invalidstr06") if self.engine.string_if_invalid: - self.assertEqual(output, 'INVALID') + self.assertEqual(output, "INVALID") else: - self.assertEqual(output, '') + self.assertEqual(output, "") - @setup({'invalidstr07': '{% load i18n %}{% blocktranslate %}{{ var }}{% endblocktranslate %}'}) + @setup( + { + "invalidstr07": "{% load i18n %}{% blocktranslate %}{{ var }}{% endblocktranslate %}" + } + ) def test_invalidstr07(self): - output = self.engine.render_to_string('invalidstr07') + output = self.engine.render_to_string("invalidstr07") if self.engine.string_if_invalid: - self.assertEqual(output, 'INVALID') + self.assertEqual(output, "INVALID") else: - self.assertEqual(output, '') + self.assertEqual(output, "") diff --git a/tests/template_tests/syntax_tests/test_list_index.py b/tests/template_tests/syntax_tests/test_list_index.py index d1be0cb1a4..261e7dfdba 100644 --- a/tests/template_tests/syntax_tests/test_list_index.py +++ b/tests/template_tests/syntax_tests/test_list_index.py @@ -4,72 +4,77 @@ from ..utils import setup class ListIndexTests(SimpleTestCase): - - @setup({'list-index01': '{{ var.1 }}'}) + @setup({"list-index01": "{{ var.1 }}"}) def test_list_index01(self): """ List-index syntax allows a template to access a certain item of a subscriptable object. """ - output = self.engine.render_to_string('list-index01', {'var': ['first item', 'second item']}) - self.assertEqual(output, 'second item') + output = self.engine.render_to_string( + "list-index01", {"var": ["first item", "second item"]} + ) + self.assertEqual(output, "second item") - @setup({'list-index02': '{{ var.5 }}'}) + @setup({"list-index02": "{{ var.5 }}"}) def test_list_index02(self): """ Fail silently when the list index is out of range. """ - output = self.engine.render_to_string('list-index02', {'var': ['first item', 'second item']}) + output = self.engine.render_to_string( + "list-index02", {"var": ["first item", "second item"]} + ) if self.engine.string_if_invalid: - self.assertEqual(output, 'INVALID') + self.assertEqual(output, "INVALID") else: - self.assertEqual(output, '') + self.assertEqual(output, "") - @setup({'list-index03': '{{ var.1 }}'}) + @setup({"list-index03": "{{ var.1 }}"}) def test_list_index03(self): """ Fail silently when the list index is out of range. """ - output = self.engine.render_to_string('list-index03', {'var': None}) + output = self.engine.render_to_string("list-index03", {"var": None}) if self.engine.string_if_invalid: - self.assertEqual(output, 'INVALID') + self.assertEqual(output, "INVALID") else: - self.assertEqual(output, '') + self.assertEqual(output, "") - @setup({'list-index04': '{{ var.1 }}'}) + @setup({"list-index04": "{{ var.1 }}"}) def test_list_index04(self): """ Fail silently when variable is a dict without the specified key. """ - output = self.engine.render_to_string('list-index04', {'var': {}}) + output = self.engine.render_to_string("list-index04", {"var": {}}) if self.engine.string_if_invalid: - self.assertEqual(output, 'INVALID') + self.assertEqual(output, "INVALID") else: - self.assertEqual(output, '') + self.assertEqual(output, "") - @setup({'list-index05': '{{ var.1 }}'}) + @setup({"list-index05": "{{ var.1 }}"}) def test_list_index05(self): """ Dictionary lookup wins out when dict's key is a string. """ - output = self.engine.render_to_string('list-index05', {'var': {'1': "hello"}}) - self.assertEqual(output, 'hello') + output = self.engine.render_to_string("list-index05", {"var": {"1": "hello"}}) + self.assertEqual(output, "hello") - @setup({'list-index06': '{{ var.1 }}'}) + @setup({"list-index06": "{{ var.1 }}"}) def test_list_index06(self): """ But list-index lookup wins out when dict's key is an int, which behind the scenes is really a dictionary lookup (for a dict) after converting the key to an int. """ - output = self.engine.render_to_string('list-index06', {"var": {1: "hello"}}) - self.assertEqual(output, 'hello') + output = self.engine.render_to_string("list-index06", {"var": {1: "hello"}}) + self.assertEqual(output, "hello") - @setup({'list-index07': '{{ var.1 }}'}) + @setup({"list-index07": "{{ var.1 }}"}) def test_list_index07(self): """ Dictionary lookup wins out when there is a string and int version of the key. """ - output = self.engine.render_to_string('list-index07', {"var": {'1': "hello", 1: "world"}}) - self.assertEqual(output, 'hello') + output = self.engine.render_to_string( + "list-index07", {"var": {"1": "hello", 1: "world"}} + ) + self.assertEqual(output, "hello") diff --git a/tests/template_tests/syntax_tests/test_load.py b/tests/template_tests/syntax_tests/test_load.py index 919bbf1346..ae5f1d4b48 100644 --- a/tests/template_tests/syntax_tests/test_load.py +++ b/tests/template_tests/syntax_tests/test_load.py @@ -6,70 +6,82 @@ from ..utils import setup class LoadTagTests(SimpleTestCase): libraries = { - 'subpackage.echo': 'template_tests.templatetags.subpackage.echo', - 'testtags': 'template_tests.templatetags.testtags', + "subpackage.echo": "template_tests.templatetags.subpackage.echo", + "testtags": "template_tests.templatetags.testtags", } - @setup({'load01': '{% load testtags subpackage.echo %}{% echo test %} {% echo2 "test" %}'}) + @setup( + { + "load01": '{% load testtags subpackage.echo %}{% echo test %} {% echo2 "test" %}' + } + ) def test_load01(self): - output = self.engine.render_to_string('load01') - self.assertEqual(output, 'test test') + output = self.engine.render_to_string("load01") + self.assertEqual(output, "test test") - @setup({'load02': '{% load subpackage.echo %}{% echo2 "test" %}'}) + @setup({"load02": '{% load subpackage.echo %}{% echo2 "test" %}'}) def test_load02(self): - output = self.engine.render_to_string('load02') - self.assertEqual(output, 'test') + output = self.engine.render_to_string("load02") + self.assertEqual(output, "test") # {% load %} tag, importing individual tags - @setup({'load03': '{% load echo from testtags %}{% echo this that theother %}'}) + @setup({"load03": "{% load echo from testtags %}{% echo this that theother %}"}) def test_load03(self): - output = self.engine.render_to_string('load03') - self.assertEqual(output, 'this that theother') + output = self.engine.render_to_string("load03") + self.assertEqual(output, "this that theother") - @setup({'load04': '{% load echo other_echo from testtags %}' - '{% echo this that theother %} {% other_echo and another thing %}'}) + @setup( + { + "load04": "{% load echo other_echo from testtags %}" + "{% echo this that theother %} {% other_echo and another thing %}" + } + ) def test_load04(self): - output = self.engine.render_to_string('load04') - self.assertEqual(output, 'this that theother and another thing') + output = self.engine.render_to_string("load04") + self.assertEqual(output, "this that theother and another thing") - @setup({'load05': '{% load echo upper from testtags %}' - '{% echo this that theother %} {{ statement|upper }}'}) + @setup( + { + "load05": "{% load echo upper from testtags %}" + "{% echo this that theother %} {{ statement|upper }}" + } + ) def test_load05(self): - output = self.engine.render_to_string('load05', {'statement': 'not shouting'}) - self.assertEqual(output, 'this that theother NOT SHOUTING') + output = self.engine.render_to_string("load05", {"statement": "not shouting"}) + self.assertEqual(output, "this that theother NOT SHOUTING") - @setup({'load06': '{% load echo2 from subpackage.echo %}{% echo2 "test" %}'}) + @setup({"load06": '{% load echo2 from subpackage.echo %}{% echo2 "test" %}'}) def test_load06(self): - output = self.engine.render_to_string('load06') - self.assertEqual(output, 'test') + output = self.engine.render_to_string("load06") + self.assertEqual(output, "test") # {% load %} tag errors - @setup({'load07': '{% load echo other_echo bad_tag from testtags %}'}) + @setup({"load07": "{% load echo other_echo bad_tag from testtags %}"}) def test_load07(self): msg = "'bad_tag' is not a valid tag or filter in tag library 'testtags'" with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.get_template('load07') + self.engine.get_template("load07") - @setup({'load08': '{% load echo other_echo bad_tag from %}'}) + @setup({"load08": "{% load echo other_echo bad_tag from %}"}) def test_load08(self): msg = "'echo' is not a registered tag library. Must be one of:\nsubpackage.echo\ntesttags" with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.get_template('load08') + self.engine.get_template("load08") - @setup({'load09': '{% load from testtags %}'}) + @setup({"load09": "{% load from testtags %}"}) def test_load09(self): msg = "'from' is not a registered tag library. Must be one of:\nsubpackage.echo\ntesttags" with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.get_template('load09') + self.engine.get_template("load09") - @setup({'load10': '{% load echo from bad_library %}'}) + @setup({"load10": "{% load echo from bad_library %}"}) def test_load10(self): msg = "'bad_library' is not a registered tag library. Must be one of:\nsubpackage.echo\ntesttags" with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.get_template('load10') + self.engine.get_template("load10") - @setup({'load12': '{% load subpackage.missing %}'}) + @setup({"load12": "{% load subpackage.missing %}"}) def test_load12(self): msg = "'subpackage.missing' is not a registered tag library. Must be one of:\nsubpackage.echo\ntesttags" with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.get_template('load12') + self.engine.get_template("load12") diff --git a/tests/template_tests/syntax_tests/test_lorem.py b/tests/template_tests/syntax_tests/test_lorem.py index 4c81aadc66..846a2bc593 100644 --- a/tests/template_tests/syntax_tests/test_lorem.py +++ b/tests/template_tests/syntax_tests/test_lorem.py @@ -6,37 +6,36 @@ from ..utils import setup class LoremTagTests(SimpleTestCase): - - @setup({'lorem1': '{% lorem 3 w %}'}) + @setup({"lorem1": "{% lorem 3 w %}"}) def test_lorem1(self): - output = self.engine.render_to_string('lorem1') - self.assertEqual(output, 'lorem ipsum dolor') + output = self.engine.render_to_string("lorem1") + self.assertEqual(output, "lorem ipsum dolor") - @setup({'lorem_random': '{% lorem 3 w random %}'}) + @setup({"lorem_random": "{% lorem 3 w random %}"}) def test_lorem_random(self): - output = self.engine.render_to_string('lorem_random') - words = output.split(' ') + output = self.engine.render_to_string("lorem_random") + words = output.split(" ") self.assertEqual(len(words), 3) for word in words: self.assertIn(word, WORDS) - @setup({'lorem_default': '{% lorem %}'}) + @setup({"lorem_default": "{% lorem %}"}) def test_lorem_default(self): - output = self.engine.render_to_string('lorem_default') + output = self.engine.render_to_string("lorem_default") self.assertEqual(output, COMMON_P) - @setup({'lorem_syntax_error': '{% lorem 1 2 3 4 %}'}) + @setup({"lorem_syntax_error": "{% lorem 1 2 3 4 %}"}) def test_lorem_syntax(self): msg = "Incorrect format for 'lorem' tag" with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('lorem_syntax_error') + self.engine.render_to_string("lorem_syntax_error") - @setup({'lorem_multiple_paragraphs': '{% lorem 2 p %}'}) + @setup({"lorem_multiple_paragraphs": "{% lorem 2 p %}"}) def test_lorem_multiple_paragraphs(self): - output = self.engine.render_to_string('lorem_multiple_paragraphs') - self.assertEqual(output.count('<p>'), 2) + output = self.engine.render_to_string("lorem_multiple_paragraphs") + self.assertEqual(output.count("<p>"), 2) - @setup({'lorem_incorrect_count': '{% lorem two p %}'}) + @setup({"lorem_incorrect_count": "{% lorem two p %}"}) def test_lorem_incorrect_count(self): - output = self.engine.render_to_string('lorem_incorrect_count') - self.assertEqual(output.count('<p>'), 1) + output = self.engine.render_to_string("lorem_incorrect_count") + self.assertEqual(output.count("<p>"), 1) diff --git a/tests/template_tests/syntax_tests/test_multiline.py b/tests/template_tests/syntax_tests/test_multiline.py index a95e12986a..fc576da63e 100644 --- a/tests/template_tests/syntax_tests/test_multiline.py +++ b/tests/template_tests/syntax_tests/test_multiline.py @@ -13,8 +13,7 @@ gentlemen. class MultilineTests(SimpleTestCase): - - @setup({'multiline01': multiline_string}) + @setup({"multiline01": multiline_string}) def test_multiline01(self): - output = self.engine.render_to_string('multiline01') + output = self.engine.render_to_string("multiline01") self.assertEqual(output, multiline_string) diff --git a/tests/template_tests/syntax_tests/test_named_endblock.py b/tests/template_tests/syntax_tests/test_named_endblock.py index 73a66a34d0..2230edf52b 100644 --- a/tests/template_tests/syntax_tests/test_named_endblock.py +++ b/tests/template_tests/syntax_tests/test_named_endblock.py @@ -5,49 +5,76 @@ from ..utils import setup class NamedEndblockTests(SimpleTestCase): - - @setup({'namedendblocks01': '1{% block first %}_{% block second %}' - '2{% endblock second %}_{% endblock first %}3'}) + @setup( + { + "namedendblocks01": "1{% block first %}_{% block second %}" + "2{% endblock second %}_{% endblock first %}3" + } + ) def test_namedendblocks01(self): - output = self.engine.render_to_string('namedendblocks01') - self.assertEqual(output, '1_2_3') + output = self.engine.render_to_string("namedendblocks01") + self.assertEqual(output, "1_2_3") # Unbalanced blocks - @setup({'namedendblocks02': '1{% block first %}_{% block second %}' - '2{% endblock first %}_{% endblock second %}3'}) + @setup( + { + "namedendblocks02": "1{% block first %}_{% block second %}" + "2{% endblock first %}_{% endblock second %}3" + } + ) def test_namedendblocks02(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('namedendblocks02') + self.engine.get_template("namedendblocks02") - @setup({'namedendblocks03': '1{% block first %}_{% block second %}' - '2{% endblock %}_{% endblock second %}3'}) + @setup( + { + "namedendblocks03": "1{% block first %}_{% block second %}" + "2{% endblock %}_{% endblock second %}3" + } + ) def test_namedendblocks03(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('namedendblocks03') + self.engine.get_template("namedendblocks03") - @setup({'namedendblocks04': '1{% block first %}_{% block second %}' - '2{% endblock second %}_{% endblock third %}3'}) + @setup( + { + "namedendblocks04": "1{% block first %}_{% block second %}" + "2{% endblock second %}_{% endblock third %}3" + } + ) def test_namedendblocks04(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('namedendblocks04') + self.engine.get_template("namedendblocks04") - @setup({'namedendblocks05': '1{% block first %}_{% block second %}2{% endblock first %}'}) + @setup( + { + "namedendblocks05": "1{% block first %}_{% block second %}2{% endblock first %}" + } + ) def test_namedendblocks05(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('namedendblocks05') + self.engine.get_template("namedendblocks05") # Mixed named and unnamed endblocks - @setup({'namedendblocks06': '1{% block first %}_{% block second %}' - '2{% endblock %}_{% endblock first %}3'}) + @setup( + { + "namedendblocks06": "1{% block first %}_{% block second %}" + "2{% endblock %}_{% endblock first %}3" + } + ) def test_namedendblocks06(self): """ Mixed named and unnamed endblocks """ - output = self.engine.render_to_string('namedendblocks06') - self.assertEqual(output, '1_2_3') + output = self.engine.render_to_string("namedendblocks06") + self.assertEqual(output, "1_2_3") - @setup({'namedendblocks07': '1{% block first %}_{% block second %}' - '2{% endblock second %}_{% endblock %}3'}) + @setup( + { + "namedendblocks07": "1{% block first %}_{% block second %}" + "2{% endblock second %}_{% endblock %}3" + } + ) def test_namedendblocks07(self): - output = self.engine.render_to_string('namedendblocks07') - self.assertEqual(output, '1_2_3') + output = self.engine.render_to_string("namedendblocks07") + self.assertEqual(output, "1_2_3") diff --git a/tests/template_tests/syntax_tests/test_now.py b/tests/template_tests/syntax_tests/test_now.py index ac2a167b4f..a0a05ed0a7 100644 --- a/tests/template_tests/syntax_tests/test_now.py +++ b/tests/template_tests/syntax_tests/test_now.py @@ -8,60 +8,91 @@ from ..utils import setup class NowTagTests(SimpleTestCase): - - @setup({'now01': '{% now "j n Y" %}'}) + @setup({"now01": '{% now "j n Y" %}'}) def test_now01(self): """ Simple case """ - output = self.engine.render_to_string('now01') - self.assertEqual(output, "%d %d %d" % ( - datetime.now().day, datetime.now().month, datetime.now().year, - )) + output = self.engine.render_to_string("now01") + self.assertEqual( + output, + "%d %d %d" + % ( + datetime.now().day, + datetime.now().month, + datetime.now().year, + ), + ) # Check parsing of locale strings - @setup({'now02': '{% now "DATE_FORMAT" %}'}) + @setup({"now02": '{% now "DATE_FORMAT" %}'}) def test_now02(self): - output = self.engine.render_to_string('now02') + output = self.engine.render_to_string("now02") self.assertEqual(output, date_format(datetime.now())) - @setup({'now03': '{% now \'j n Y\' %}'}) + @setup({"now03": "{% now 'j n Y' %}"}) def test_now03(self): """ #15092 - Also accept simple quotes """ - output = self.engine.render_to_string('now03') - self.assertEqual(output, "%d %d %d" % ( - datetime.now().day, datetime.now().month, datetime.now().year, - )) + output = self.engine.render_to_string("now03") + self.assertEqual( + output, + "%d %d %d" + % ( + datetime.now().day, + datetime.now().month, + datetime.now().year, + ), + ) - @setup({'now04': '{% now \'DATE_FORMAT\' %}'}) + @setup({"now04": "{% now 'DATE_FORMAT' %}"}) def test_now04(self): - output = self.engine.render_to_string('now04') + output = self.engine.render_to_string("now04") self.assertEqual(output, date_format(datetime.now())) - @setup({'now05': '{% now \'j "n" Y\'%}'}) + @setup({"now05": "{% now 'j \"n\" Y'%}"}) def test_now05(self): - output = self.engine.render_to_string('now05') - self.assertEqual(output, '%d "%d" %d' % ( - datetime.now().day, datetime.now().month, datetime.now().year, - )) + output = self.engine.render_to_string("now05") + self.assertEqual( + output, + '%d "%d" %d' + % ( + datetime.now().day, + datetime.now().month, + datetime.now().year, + ), + ) - @setup({'now06': '{% now "j \'n\' Y"%}'}) + @setup({"now06": "{% now \"j 'n' Y\"%}"}) def test_now06(self): - output = self.engine.render_to_string('now06') - self.assertEqual(output, "%d '%d' %d" % ( - datetime.now().day, datetime.now().month, datetime.now().year, - )) + output = self.engine.render_to_string("now06") + self.assertEqual( + output, + "%d '%d' %d" + % ( + datetime.now().day, + datetime.now().month, + datetime.now().year, + ), + ) - @setup({'now07': '{% now "j n Y" as N %}-{{N}}-'}) + @setup({"now07": '{% now "j n Y" as N %}-{{N}}-'}) def test_now07(self): - output = self.engine.render_to_string('now07') - self.assertEqual(output, '-%d %d %d-' % ( - datetime.now().day, datetime.now().month, datetime.now().year, - )) + output = self.engine.render_to_string("now07") + self.assertEqual( + output, + "-%d %d %d-" + % ( + datetime.now().day, + datetime.now().month, + datetime.now().year, + ), + ) - @setup({'no_args': '{% now %}'}) + @setup({"no_args": "{% now %}"}) def test_now_args(self): - with self.assertRaisesMessage(TemplateSyntaxError, "'now' statement takes one argument"): - self.engine.render_to_string('no_args') + with self.assertRaisesMessage( + TemplateSyntaxError, "'now' statement takes one argument" + ): + self.engine.render_to_string("no_args") diff --git a/tests/template_tests/syntax_tests/test_numpy.py b/tests/template_tests/syntax_tests/test_numpy.py index 09d57ebcc2..2c78b45358 100644 --- a/tests/template_tests/syntax_tests/test_numpy.py +++ b/tests/template_tests/syntax_tests/test_numpy.py @@ -12,29 +12,28 @@ except ImportError: @skipIf(numpy is False, "Numpy must be installed to run these tests.") class NumpyTests(SimpleTestCase): - - @setup({'numpy-array-index01': '{{ var.1 }}'}) + @setup({"numpy-array-index01": "{{ var.1 }}"}) def test_numpy_array_index01(self): """ Numpy's array-index syntax allows a template to access a certain item of a subscriptable object. """ output = self.engine.render_to_string( - 'numpy-array-index01', - {'var': numpy.array(["first item", "second item"])}, + "numpy-array-index01", + {"var": numpy.array(["first item", "second item"])}, ) - self.assertEqual(output, 'second item') + self.assertEqual(output, "second item") - @setup({'numpy-array-index02': '{{ var.5 }}'}) + @setup({"numpy-array-index02": "{{ var.5 }}"}) def test_numpy_array_index02(self): """ Fail silently when the array index is out of range. """ output = self.engine.render_to_string( - 'numpy-array-index02', - {'var': numpy.array(["first item", "second item"])}, + "numpy-array-index02", + {"var": numpy.array(["first item", "second item"])}, ) if self.engine.string_if_invalid: - self.assertEqual(output, 'INVALID') + self.assertEqual(output, "INVALID") else: - self.assertEqual(output, '') + self.assertEqual(output, "") diff --git a/tests/template_tests/syntax_tests/test_regroup.py b/tests/template_tests/syntax_tests/test_regroup.py index 2c0135587e..eca5e0d5f9 100644 --- a/tests/template_tests/syntax_tests/test_regroup.py +++ b/tests/template_tests/syntax_tests/test_regroup.py @@ -7,115 +7,152 @@ from ..utils import setup class RegroupTagTests(SimpleTestCase): - - @setup({'regroup01': '' - '{% regroup data by bar as grouped %}' - '{% for group in grouped %}' - '{{ group.grouper }}:' - '{% for item in group.list %}' - '{{ item.foo }}' - '{% endfor %},' - '{% endfor %}'}) + @setup( + { + "regroup01": "" + "{% regroup data by bar as grouped %}" + "{% for group in grouped %}" + "{{ group.grouper }}:" + "{% for item in group.list %}" + "{{ item.foo }}" + "{% endfor %}," + "{% endfor %}" + } + ) def test_regroup01(self): - output = self.engine.render_to_string('regroup01', { - 'data': [{'foo': 'c', 'bar': 1}, - {'foo': 'd', 'bar': 1}, - {'foo': 'a', 'bar': 2}, - {'foo': 'b', 'bar': 2}, - {'foo': 'x', 'bar': 3}], - }) - self.assertEqual(output, '1:cd,2:ab,3:x,') + output = self.engine.render_to_string( + "regroup01", + { + "data": [ + {"foo": "c", "bar": 1}, + {"foo": "d", "bar": 1}, + {"foo": "a", "bar": 2}, + {"foo": "b", "bar": 2}, + {"foo": "x", "bar": 3}, + ], + }, + ) + self.assertEqual(output, "1:cd,2:ab,3:x,") - @setup({'regroup02': '' - '{% regroup data by bar as grouped %}' - '{% for group in grouped %}' - '{{ group.grouper }}:' - '{% for item in group.list %}' - '{{ item.foo }}' - '{% endfor %}' - '{% endfor %}'}) + @setup( + { + "regroup02": "" + "{% regroup data by bar as grouped %}" + "{% for group in grouped %}" + "{{ group.grouper }}:" + "{% for item in group.list %}" + "{{ item.foo }}" + "{% endfor %}" + "{% endfor %}" + } + ) def test_regroup02(self): """ Test for silent failure when target variable isn't found """ - output = self.engine.render_to_string('regroup02', {}) - self.assertEqual(output, '') + output = self.engine.render_to_string("regroup02", {}) + self.assertEqual(output, "") - @setup({'regroup03': '' - '{% regroup data by at|date:"m" as grouped %}' - '{% for group in grouped %}' - '{{ group.grouper }}:' - '{% for item in group.list %}' - '{{ item.at|date:"d" }}' - '{% endfor %},' - '{% endfor %}'}) + @setup( + { + "regroup03": "" + '{% regroup data by at|date:"m" as grouped %}' + "{% for group in grouped %}" + "{{ group.grouper }}:" + "{% for item in group.list %}" + '{{ item.at|date:"d" }}' + "{% endfor %}," + "{% endfor %}" + } + ) def test_regroup03(self): """ Regression tests for #17675 The date template filter has expects_localtime = True """ - output = self.engine.render_to_string('regroup03', { - 'data': [{'at': date(2012, 2, 14)}, - {'at': date(2012, 2, 28)}, - {'at': date(2012, 7, 4)}], - }) - self.assertEqual(output, '02:1428,07:04,') + output = self.engine.render_to_string( + "regroup03", + { + "data": [ + {"at": date(2012, 2, 14)}, + {"at": date(2012, 2, 28)}, + {"at": date(2012, 7, 4)}, + ], + }, + ) + self.assertEqual(output, "02:1428,07:04,") - @setup({'regroup04': '' - '{% regroup data by bar|join:"" as grouped %}' - '{% for group in grouped %}' - '{{ group.grouper }}:' - '{% for item in group.list %}' - '{{ item.foo|first }}' - '{% endfor %},' - '{% endfor %}'}) + @setup( + { + "regroup04": "" + '{% regroup data by bar|join:"" as grouped %}' + "{% for group in grouped %}" + "{{ group.grouper }}:" + "{% for item in group.list %}" + "{{ item.foo|first }}" + "{% endfor %}," + "{% endfor %}" + } + ) def test_regroup04(self): """ The join template filter has needs_autoescape = True """ - output = self.engine.render_to_string('regroup04', { - 'data': [{'foo': 'x', 'bar': ['ab', 'c']}, - {'foo': 'y', 'bar': ['a', 'bc']}, - {'foo': 'z', 'bar': ['a', 'd']}], - }) - self.assertEqual(output, 'abc:xy,ad:z,') + output = self.engine.render_to_string( + "regroup04", + { + "data": [ + {"foo": "x", "bar": ["ab", "c"]}, + {"foo": "y", "bar": ["a", "bc"]}, + {"foo": "z", "bar": ["a", "d"]}, + ], + }, + ) + self.assertEqual(output, "abc:xy,ad:z,") # Test syntax errors - @setup({'regroup05': '{% regroup data by bar as %}'}) + @setup({"regroup05": "{% regroup data by bar as %}"}) def test_regroup05(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('regroup05') + self.engine.get_template("regroup05") - @setup({'regroup06': '{% regroup data by bar thisaintright grouped %}'}) + @setup({"regroup06": "{% regroup data by bar thisaintright grouped %}"}) def test_regroup06(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('regroup06') + self.engine.get_template("regroup06") - @setup({'regroup07': '{% regroup data thisaintright bar as grouped %}'}) + @setup({"regroup07": "{% regroup data thisaintright bar as grouped %}"}) def test_regroup07(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('regroup07') + self.engine.get_template("regroup07") - @setup({'regroup08': '{% regroup data by bar as grouped toomanyargs %}'}) + @setup({"regroup08": "{% regroup data by bar as grouped toomanyargs %}"}) def test_regroup08(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('regroup08') + self.engine.get_template("regroup08") - @setup({'regroup_unpack': '{% regroup data by bar as grouped %}' - '{% for grouper, group in grouped %}' - '{{ grouper }}:' - '{% for item in group %}' - '{{ item.foo }}' - '{% endfor %},' - '{% endfor %}'}) + @setup( + { + "regroup_unpack": "{% regroup data by bar as grouped %}" + "{% for grouper, group in grouped %}" + "{{ grouper }}:" + "{% for item in group %}" + "{{ item.foo }}" + "{% endfor %}," + "{% endfor %}" + } + ) def test_regroup_unpack(self): - output = self.engine.render_to_string('regroup_unpack', { - 'data': [ - {'foo': 'c', 'bar': 1}, - {'foo': 'd', 'bar': 1}, - {'foo': 'a', 'bar': 2}, - {'foo': 'b', 'bar': 2}, - {'foo': 'x', 'bar': 3}, - ], - }) - self.assertEqual(output, '1:cd,2:ab,3:x,') + output = self.engine.render_to_string( + "regroup_unpack", + { + "data": [ + {"foo": "c", "bar": 1}, + {"foo": "d", "bar": 1}, + {"foo": "a", "bar": 2}, + {"foo": "b", "bar": 2}, + {"foo": "x", "bar": 3}, + ], + }, + ) + self.assertEqual(output, "1:cd,2:ab,3:x,") diff --git a/tests/template_tests/syntax_tests/test_resetcycle.py b/tests/template_tests/syntax_tests/test_resetcycle.py index 7c3bfc55fb..6d7365a6ec 100644 --- a/tests/template_tests/syntax_tests/test_resetcycle.py +++ b/tests/template_tests/syntax_tests/test_resetcycle.py @@ -5,91 +5,128 @@ from ..utils import setup class ResetCycleTagTests(SimpleTestCase): - - @setup({'resetcycle01': "{% resetcycle %}"}) + @setup({"resetcycle01": "{% resetcycle %}"}) def test_resetcycle01(self): with self.assertRaisesMessage(TemplateSyntaxError, "No cycles in template."): - self.engine.get_template('resetcycle01') + self.engine.get_template("resetcycle01") - @setup({'resetcycle02': "{% resetcycle undefinedcycle %}"}) + @setup({"resetcycle02": "{% resetcycle undefinedcycle %}"}) def test_resetcycle02(self): - with self.assertRaisesMessage(TemplateSyntaxError, "Named cycle 'undefinedcycle' does not exist."): - self.engine.get_template('resetcycle02') + with self.assertRaisesMessage( + TemplateSyntaxError, "Named cycle 'undefinedcycle' does not exist." + ): + self.engine.get_template("resetcycle02") - @setup({'resetcycle03': "{% cycle 'a' 'b' %}{% resetcycle undefinedcycle %}"}) + @setup({"resetcycle03": "{% cycle 'a' 'b' %}{% resetcycle undefinedcycle %}"}) def test_resetcycle03(self): - with self.assertRaisesMessage(TemplateSyntaxError, "Named cycle 'undefinedcycle' does not exist."): - self.engine.get_template('resetcycle03') + with self.assertRaisesMessage( + TemplateSyntaxError, "Named cycle 'undefinedcycle' does not exist." + ): + self.engine.get_template("resetcycle03") - @setup({'resetcycle04': "{% cycle 'a' 'b' as ab %}{% resetcycle undefinedcycle %}"}) + @setup({"resetcycle04": "{% cycle 'a' 'b' as ab %}{% resetcycle undefinedcycle %}"}) def test_resetcycle04(self): - with self.assertRaisesMessage(TemplateSyntaxError, "Named cycle 'undefinedcycle' does not exist."): - self.engine.get_template('resetcycle04') + with self.assertRaisesMessage( + TemplateSyntaxError, "Named cycle 'undefinedcycle' does not exist." + ): + self.engine.get_template("resetcycle04") - @setup({'resetcycle05': "{% for i in test %}{% cycle 'a' 'b' %}{% resetcycle %}{% endfor %}"}) + @setup( + { + "resetcycle05": "{% for i in test %}{% cycle 'a' 'b' %}{% resetcycle %}{% endfor %}" + } + ) def test_resetcycle05(self): - output = self.engine.render_to_string('resetcycle05', {'test': list(range(5))}) - self.assertEqual(output, 'aaaaa') + output = self.engine.render_to_string("resetcycle05", {"test": list(range(5))}) + self.assertEqual(output, "aaaaa") - @setup({'resetcycle06': "{% cycle 'a' 'b' 'c' as abc %}" - "{% for i in test %}" - "{% cycle abc %}" - "{% cycle '-' '+' %}" - "{% resetcycle %}" - "{% endfor %}"}) + @setup( + { + "resetcycle06": "{% cycle 'a' 'b' 'c' as abc %}" + "{% for i in test %}" + "{% cycle abc %}" + "{% cycle '-' '+' %}" + "{% resetcycle %}" + "{% endfor %}" + } + ) def test_resetcycle06(self): - output = self.engine.render_to_string('resetcycle06', {'test': list(range(5))}) - self.assertEqual(output, 'ab-c-a-b-c-') + output = self.engine.render_to_string("resetcycle06", {"test": list(range(5))}) + self.assertEqual(output, "ab-c-a-b-c-") - @setup({'resetcycle07': "{% cycle 'a' 'b' 'c' as abc %}" - "{% for i in test %}" - "{% resetcycle abc %}" - "{% cycle abc %}" - "{% cycle '-' '+' %}" - "{% endfor %}"}) + @setup( + { + "resetcycle07": "{% cycle 'a' 'b' 'c' as abc %}" + "{% for i in test %}" + "{% resetcycle abc %}" + "{% cycle abc %}" + "{% cycle '-' '+' %}" + "{% endfor %}" + } + ) def test_resetcycle07(self): - output = self.engine.render_to_string('resetcycle07', {'test': list(range(5))}) - self.assertEqual(output, 'aa-a+a-a+a-') + output = self.engine.render_to_string("resetcycle07", {"test": list(range(5))}) + self.assertEqual(output, "aa-a+a-a+a-") - @setup({'resetcycle08': "{% for i in outer %}" - "{% for j in inner %}" - "{% cycle 'a' 'b' %}" - "{% endfor %}" - "{% resetcycle %}" - "{% endfor %}"}) + @setup( + { + "resetcycle08": "{% for i in outer %}" + "{% for j in inner %}" + "{% cycle 'a' 'b' %}" + "{% endfor %}" + "{% resetcycle %}" + "{% endfor %}" + } + ) def test_resetcycle08(self): - output = self.engine.render_to_string('resetcycle08', {'outer': list(range(2)), 'inner': list(range(3))}) - self.assertEqual(output, 'abaaba') + output = self.engine.render_to_string( + "resetcycle08", {"outer": list(range(2)), "inner": list(range(3))} + ) + self.assertEqual(output, "abaaba") - @setup({'resetcycle09': "{% for i in outer %}" - "{% cycle 'a' 'b' %}" - "{% for j in inner %}" - "{% cycle 'X' 'Y' %}" - "{% endfor %}" - "{% resetcycle %}" - "{% endfor %}"}) + @setup( + { + "resetcycle09": "{% for i in outer %}" + "{% cycle 'a' 'b' %}" + "{% for j in inner %}" + "{% cycle 'X' 'Y' %}" + "{% endfor %}" + "{% resetcycle %}" + "{% endfor %}" + } + ) def test_resetcycle09(self): - output = self.engine.render_to_string('resetcycle09', {'outer': list(range(2)), 'inner': list(range(3))}) - self.assertEqual(output, 'aXYXbXYX') + output = self.engine.render_to_string( + "resetcycle09", {"outer": list(range(2)), "inner": list(range(3))} + ) + self.assertEqual(output, "aXYXbXYX") - @setup({'resetcycle10': "{% for i in test %}" - "{% cycle 'X' 'Y' 'Z' as XYZ %}" - "{% cycle 'a' 'b' 'c' as abc %}" - "{% if i == 1 %}" - "{% resetcycle abc %}" - "{% endif %}" - "{% endfor %}"}) + @setup( + { + "resetcycle10": "{% for i in test %}" + "{% cycle 'X' 'Y' 'Z' as XYZ %}" + "{% cycle 'a' 'b' 'c' as abc %}" + "{% if i == 1 %}" + "{% resetcycle abc %}" + "{% endif %}" + "{% endfor %}" + } + ) def test_resetcycle10(self): - output = self.engine.render_to_string('resetcycle10', {'test': list(range(5))}) - self.assertEqual(output, 'XaYbZaXbYc') + output = self.engine.render_to_string("resetcycle10", {"test": list(range(5))}) + self.assertEqual(output, "XaYbZaXbYc") - @setup({'resetcycle11': "{% for i in test %}" - "{% cycle 'X' 'Y' 'Z' as XYZ %}" - "{% cycle 'a' 'b' 'c' as abc %}" - "{% if i == 1 %}" - "{% resetcycle XYZ %}" - "{% endif %}" - "{% endfor %}"}) + @setup( + { + "resetcycle11": "{% for i in test %}" + "{% cycle 'X' 'Y' 'Z' as XYZ %}" + "{% cycle 'a' 'b' 'c' as abc %}" + "{% if i == 1 %}" + "{% resetcycle XYZ %}" + "{% endif %}" + "{% endfor %}" + } + ) def test_resetcycle11(self): - output = self.engine.render_to_string('resetcycle11', {'test': list(range(5))}) - self.assertEqual(output, 'XaYbXcYaZb') + output = self.engine.render_to_string("resetcycle11", {"test": list(range(5))}) + self.assertEqual(output, "XaYbXcYaZb") diff --git a/tests/template_tests/syntax_tests/test_setup.py b/tests/template_tests/syntax_tests/test_setup.py index 07377cea3f..a05cea4292 100644 --- a/tests/template_tests/syntax_tests/test_setup.py +++ b/tests/template_tests/syntax_tests/test_setup.py @@ -4,7 +4,6 @@ from ..utils import setup class SetupTests(SimpleTestCase): - def test_setup(self): """ Let's just make sure setup runs cases in the right order. @@ -13,16 +12,18 @@ class SetupTests(SimpleTestCase): @setup({}) def method(self): - cases.append([ - self.engine.string_if_invalid, - self.engine.debug, - ]) + cases.append( + [ + self.engine.string_if_invalid, + self.engine.debug, + ] + ) method(self) - self.assertEqual(cases[0], ['', False]) - self.assertEqual(cases[1], ['', False]) - self.assertEqual(cases[2], ['INVALID', False]) - self.assertEqual(cases[3], ['INVALID', False]) - self.assertEqual(cases[4], ['', True]) - self.assertEqual(cases[5], ['', True]) + self.assertEqual(cases[0], ["", False]) + self.assertEqual(cases[1], ["", False]) + self.assertEqual(cases[2], ["INVALID", False]) + self.assertEqual(cases[3], ["INVALID", False]) + self.assertEqual(cases[4], ["", True]) + self.assertEqual(cases[5], ["", True]) diff --git a/tests/template_tests/syntax_tests/test_simple_tag.py b/tests/template_tests/syntax_tests/test_simple_tag.py index 5e6ce4733e..79bffe05fa 100644 --- a/tests/template_tests/syntax_tests/test_simple_tag.py +++ b/tests/template_tests/syntax_tests/test_simple_tag.py @@ -5,19 +5,19 @@ from ..utils import setup class SimpleTagTests(SimpleTestCase): - libraries = {'custom': 'template_tests.templatetags.custom'} + libraries = {"custom": "template_tests.templatetags.custom"} - @setup({'simpletag-renamed01': '{% load custom %}{% minusone 7 %}'}) + @setup({"simpletag-renamed01": "{% load custom %}{% minusone 7 %}"}) def test_simpletag_renamed01(self): - output = self.engine.render_to_string('simpletag-renamed01') - self.assertEqual(output, '6') + output = self.engine.render_to_string("simpletag-renamed01") + self.assertEqual(output, "6") - @setup({'simpletag-renamed02': '{% load custom %}{% minustwo 7 %}'}) + @setup({"simpletag-renamed02": "{% load custom %}{% minustwo 7 %}"}) def test_simpletag_renamed02(self): - output = self.engine.render_to_string('simpletag-renamed02') - self.assertEqual(output, '5') + output = self.engine.render_to_string("simpletag-renamed02") + self.assertEqual(output, "5") - @setup({'simpletag-renamed03': '{% load custom %}{% minustwo_overridden_name 7 %}'}) + @setup({"simpletag-renamed03": "{% load custom %}{% minustwo_overridden_name 7 %}"}) def test_simpletag_renamed03(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('simpletag-renamed03') + self.engine.get_template("simpletag-renamed03") diff --git a/tests/template_tests/syntax_tests/test_spaceless.py b/tests/template_tests/syntax_tests/test_spaceless.py index 398b7919a1..8bb20dba6c 100644 --- a/tests/template_tests/syntax_tests/test_spaceless.py +++ b/tests/template_tests/syntax_tests/test_spaceless.py @@ -4,35 +4,54 @@ from ..utils import setup class SpacelessTagTests(SimpleTestCase): - - @setup({'spaceless01': "{% spaceless %} <b> <i> text </i> </b> {% endspaceless %}"}) + @setup( + { + "spaceless01": "{% spaceless %} <b> <i> text </i> </b> {% endspaceless %}" + } + ) def test_spaceless01(self): - output = self.engine.render_to_string('spaceless01') + output = self.engine.render_to_string("spaceless01") self.assertEqual(output, "<b><i> text </i></b>") - @setup({'spaceless02': "{% spaceless %} <b> \n <i> text </i> \n </b> {% endspaceless %}"}) + @setup( + { + "spaceless02": "{% spaceless %} <b> \n <i> text </i> \n </b> {% endspaceless %}" + } + ) def test_spaceless02(self): - output = self.engine.render_to_string('spaceless02') + output = self.engine.render_to_string("spaceless02") self.assertEqual(output, "<b><i> text </i></b>") - @setup({'spaceless03': "{% spaceless %}<b><i>text</i></b>{% endspaceless %}"}) + @setup({"spaceless03": "{% spaceless %}<b><i>text</i></b>{% endspaceless %}"}) def test_spaceless03(self): - output = self.engine.render_to_string('spaceless03') + output = self.engine.render_to_string("spaceless03") self.assertEqual(output, "<b><i>text</i></b>") - @setup({'spaceless04': "{% spaceless %}<b> <i>{{ text }}</i> </b>{% endspaceless %}"}) + @setup( + { + "spaceless04": "{% spaceless %}<b> <i>{{ text }}</i> </b>{% endspaceless %}" + } + ) def test_spaceless04(self): - output = self.engine.render_to_string('spaceless04', {'text': 'This & that'}) + output = self.engine.render_to_string("spaceless04", {"text": "This & that"}) self.assertEqual(output, "<b><i>This & that</i></b>") - @setup({'spaceless05': "{% autoescape off %}{% spaceless %}" - "<b> <i>{{ text }}</i> </b>{% endspaceless %}" - "{% endautoescape %}"}) + @setup( + { + "spaceless05": "{% autoescape off %}{% spaceless %}" + "<b> <i>{{ text }}</i> </b>{% endspaceless %}" + "{% endautoescape %}" + } + ) def test_spaceless05(self): - output = self.engine.render_to_string('spaceless05', {'text': 'This & that'}) + output = self.engine.render_to_string("spaceless05", {"text": "This & that"}) self.assertEqual(output, "<b><i>This & that</i></b>") - @setup({'spaceless06': "{% spaceless %}<b> <i>{{ text|safe }}</i> </b>{% endspaceless %}"}) + @setup( + { + "spaceless06": "{% spaceless %}<b> <i>{{ text|safe }}</i> </b>{% endspaceless %}" + } + ) def test_spaceless06(self): - output = self.engine.render_to_string('spaceless06', {'text': 'This & that'}) + output = self.engine.render_to_string("spaceless06", {"text": "This & that"}) self.assertEqual(output, "<b><i>This & that</i></b>") diff --git a/tests/template_tests/syntax_tests/test_static.py b/tests/template_tests/syntax_tests/test_static.py index 6f27d555bf..cd63350cb5 100644 --- a/tests/template_tests/syntax_tests/test_static.py +++ b/tests/template_tests/syntax_tests/test_static.py @@ -8,78 +8,107 @@ from django.test import SimpleTestCase, override_settings from ..utils import setup -@override_settings(INSTALLED_APPS=[], MEDIA_URL='media/', STATIC_URL='static/') +@override_settings(INSTALLED_APPS=[], MEDIA_URL="media/", STATIC_URL="static/") class StaticTagTests(SimpleTestCase): - libraries = {'static': 'django.templatetags.static'} + libraries = {"static": "django.templatetags.static"} - @setup({'static-prefixtag01': '{% load static %}{% get_static_prefix %}'}) + @setup({"static-prefixtag01": "{% load static %}{% get_static_prefix %}"}) def test_static_prefixtag01(self): - output = self.engine.render_to_string('static-prefixtag01') + output = self.engine.render_to_string("static-prefixtag01") self.assertEqual(output, settings.STATIC_URL) - @setup({'static-prefixtag02': '{% load static %}' - '{% get_static_prefix as static_prefix %}{{ static_prefix }}'}) + @setup( + { + "static-prefixtag02": "{% load static %}" + "{% get_static_prefix as static_prefix %}{{ static_prefix }}" + } + ) def test_static_prefixtag02(self): - output = self.engine.render_to_string('static-prefixtag02') + output = self.engine.render_to_string("static-prefixtag02") self.assertEqual(output, settings.STATIC_URL) - @setup({'static-prefixtag03': '{% load static %}{% get_media_prefix %}'}) + @setup({"static-prefixtag03": "{% load static %}{% get_media_prefix %}"}) def test_static_prefixtag03(self): - output = self.engine.render_to_string('static-prefixtag03') + output = self.engine.render_to_string("static-prefixtag03") self.assertEqual(output, settings.MEDIA_URL) - @setup({'static-prefixtag04': '{% load static %}' - '{% get_media_prefix as media_prefix %}{{ media_prefix }}'}) + @setup( + { + "static-prefixtag04": "{% load static %}" + "{% get_media_prefix as media_prefix %}{{ media_prefix }}" + } + ) def test_static_prefixtag04(self): - output = self.engine.render_to_string('static-prefixtag04') + output = self.engine.render_to_string("static-prefixtag04") self.assertEqual(output, settings.MEDIA_URL) - @setup({'t': '{% load static %}{% get_media_prefix ad media_prefix %}{{ media_prefix }}'}) + @setup( + { + "t": "{% load static %}{% get_media_prefix ad media_prefix %}{{ media_prefix }}" + } + ) def test_static_prefixtag_without_as(self): msg = "First argument in 'get_media_prefix' must be 'as'" with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('t') + self.engine.render_to_string("t") - @setup({'static-statictag01': '{% load static %}{% static "admin/base.css" %}'}) + @setup({"static-statictag01": '{% load static %}{% static "admin/base.css" %}'}) def test_static_statictag01(self): - output = self.engine.render_to_string('static-statictag01') - self.assertEqual(output, urljoin(settings.STATIC_URL, 'admin/base.css')) + output = self.engine.render_to_string("static-statictag01") + self.assertEqual(output, urljoin(settings.STATIC_URL, "admin/base.css")) - @setup({'static-statictag02': '{% load static %}{% static base_css %}'}) + @setup({"static-statictag02": "{% load static %}{% static base_css %}"}) def test_static_statictag02(self): - output = self.engine.render_to_string('static-statictag02', {'base_css': 'admin/base.css'}) - self.assertEqual(output, urljoin(settings.STATIC_URL, 'admin/base.css')) + output = self.engine.render_to_string( + "static-statictag02", {"base_css": "admin/base.css"} + ) + self.assertEqual(output, urljoin(settings.STATIC_URL, "admin/base.css")) - @setup({'static-statictag03': '{% load static %}{% static "admin/base.css" as foo %}{{ foo }}'}) + @setup( + { + "static-statictag03": '{% load static %}{% static "admin/base.css" as foo %}{{ foo }}' + } + ) def test_static_statictag03(self): - output = self.engine.render_to_string('static-statictag03') - self.assertEqual(output, urljoin(settings.STATIC_URL, 'admin/base.css')) + output = self.engine.render_to_string("static-statictag03") + self.assertEqual(output, urljoin(settings.STATIC_URL, "admin/base.css")) - @setup({'static-statictag04': '{% load static %}{% static base_css as foo %}{{ foo }}'}) + @setup( + {"static-statictag04": "{% load static %}{% static base_css as foo %}{{ foo }}"} + ) def test_static_statictag04(self): - output = self.engine.render_to_string('static-statictag04', {'base_css': 'admin/base.css'}) - self.assertEqual(output, urljoin(settings.STATIC_URL, 'admin/base.css')) + output = self.engine.render_to_string( + "static-statictag04", {"base_css": "admin/base.css"} + ) + self.assertEqual(output, urljoin(settings.STATIC_URL, "admin/base.css")) - @setup({'static-statictag05': '{% load static %}{% static "special?chars"ed.html" %}'}) + @setup( + { + "static-statictag05": '{% load static %}{% static "special?chars"ed.html" %}' + } + ) def test_static_quotes_urls(self): - output = self.engine.render_to_string('static-statictag05') - self.assertEqual(output, urljoin(settings.STATIC_URL, '/static/special%3Fchars%26quoted.html')) + output = self.engine.render_to_string("static-statictag05") + self.assertEqual( + output, + urljoin(settings.STATIC_URL, "/static/special%3Fchars%26quoted.html"), + ) - @setup({'t': '{% load static %}{% static %}'}) + @setup({"t": "{% load static %}{% static %}"}) def test_static_statictag_without_path(self): msg = "'static' takes at least one argument (path to file)" with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.render_to_string('t') + self.engine.render_to_string("t") class StaticNodeTests(SimpleTestCase): def test_repr(self): - static_node = StaticNode(varname='named-var', path='named-path') + static_node = StaticNode(varname="named-var", path="named-path") self.assertEqual( repr(static_node), "StaticNode(varname='named-var', path='named-path')", ) - static_node = StaticNode(path='named-path') + static_node = StaticNode(path="named-path") self.assertEqual( repr(static_node), "StaticNode(varname=None, path='named-path')", diff --git a/tests/template_tests/syntax_tests/test_template_tag.py b/tests/template_tests/syntax_tests/test_template_tag.py index e868c9f21a..b53b657921 100644 --- a/tests/template_tests/syntax_tests/test_template_tag.py +++ b/tests/template_tests/syntax_tests/test_template_tag.py @@ -5,63 +5,64 @@ from ..utils import setup class TemplateTagTests(SimpleTestCase): - - @setup({'templatetag01': '{% templatetag openblock %}'}) + @setup({"templatetag01": "{% templatetag openblock %}"}) def test_templatetag01(self): - output = self.engine.render_to_string('templatetag01') - self.assertEqual(output, '{%') + output = self.engine.render_to_string("templatetag01") + self.assertEqual(output, "{%") - @setup({'templatetag02': '{% templatetag closeblock %}'}) + @setup({"templatetag02": "{% templatetag closeblock %}"}) def test_templatetag02(self): - output = self.engine.render_to_string('templatetag02') - self.assertEqual(output, '%}') + output = self.engine.render_to_string("templatetag02") + self.assertEqual(output, "%}") - @setup({'templatetag03': '{% templatetag openvariable %}'}) + @setup({"templatetag03": "{% templatetag openvariable %}"}) def test_templatetag03(self): - output = self.engine.render_to_string('templatetag03') - self.assertEqual(output, '{{') + output = self.engine.render_to_string("templatetag03") + self.assertEqual(output, "{{") - @setup({'templatetag04': '{% templatetag closevariable %}'}) + @setup({"templatetag04": "{% templatetag closevariable %}"}) def test_templatetag04(self): - output = self.engine.render_to_string('templatetag04') - self.assertEqual(output, '}}') + output = self.engine.render_to_string("templatetag04") + self.assertEqual(output, "}}") - @setup({'templatetag05': '{% templatetag %}'}) + @setup({"templatetag05": "{% templatetag %}"}) def test_templatetag05(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('templatetag05') + self.engine.get_template("templatetag05") - @setup({'templatetag06': '{% templatetag foo %}'}) + @setup({"templatetag06": "{% templatetag foo %}"}) def test_templatetag06(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('templatetag06') + self.engine.get_template("templatetag06") - @setup({'templatetag07': '{% templatetag openbrace %}'}) + @setup({"templatetag07": "{% templatetag openbrace %}"}) def test_templatetag07(self): - output = self.engine.render_to_string('templatetag07') - self.assertEqual(output, '{') + output = self.engine.render_to_string("templatetag07") + self.assertEqual(output, "{") - @setup({'templatetag08': '{% templatetag closebrace %}'}) + @setup({"templatetag08": "{% templatetag closebrace %}"}) def test_templatetag08(self): - output = self.engine.render_to_string('templatetag08') - self.assertEqual(output, '}') + output = self.engine.render_to_string("templatetag08") + self.assertEqual(output, "}") - @setup({'templatetag09': '{% templatetag openbrace %}{% templatetag openbrace %}'}) + @setup({"templatetag09": "{% templatetag openbrace %}{% templatetag openbrace %}"}) def test_templatetag09(self): - output = self.engine.render_to_string('templatetag09') - self.assertEqual(output, '{{') + output = self.engine.render_to_string("templatetag09") + self.assertEqual(output, "{{") - @setup({'templatetag10': '{% templatetag closebrace %}{% templatetag closebrace %}'}) + @setup( + {"templatetag10": "{% templatetag closebrace %}{% templatetag closebrace %}"} + ) def test_templatetag10(self): - output = self.engine.render_to_string('templatetag10') - self.assertEqual(output, '}}') + output = self.engine.render_to_string("templatetag10") + self.assertEqual(output, "}}") - @setup({'templatetag11': '{% templatetag opencomment %}'}) + @setup({"templatetag11": "{% templatetag opencomment %}"}) def test_templatetag11(self): - output = self.engine.render_to_string('templatetag11') - self.assertEqual(output, '{#') + output = self.engine.render_to_string("templatetag11") + self.assertEqual(output, "{#") - @setup({'templatetag12': '{% templatetag closecomment %}'}) + @setup({"templatetag12": "{% templatetag closecomment %}"}) def test_templatetag12(self): - output = self.engine.render_to_string('templatetag12') - self.assertEqual(output, '#}') + output = self.engine.render_to_string("templatetag12") + self.assertEqual(output, "#}") diff --git a/tests/template_tests/syntax_tests/test_url.py b/tests/template_tests/syntax_tests/test_url.py index 831eac5527..3e51b0e3f5 100644 --- a/tests/template_tests/syntax_tests/test_url.py +++ b/tests/template_tests/syntax_tests/test_url.py @@ -6,286 +6,300 @@ from django.urls import NoReverseMatch, resolve from ..utils import setup -@override_settings(ROOT_URLCONF='template_tests.urls') +@override_settings(ROOT_URLCONF="template_tests.urls") class UrlTagTests(SimpleTestCase): request_factory = RequestFactory() # Successes - @setup({'url01': '{% url "client" client.id %}'}) + @setup({"url01": '{% url "client" client.id %}'}) def test_url01(self): - output = self.engine.render_to_string('url01', {'client': {'id': 1}}) - self.assertEqual(output, '/client/1/') + output = self.engine.render_to_string("url01", {"client": {"id": 1}}) + self.assertEqual(output, "/client/1/") - @setup({'url02': '{% url "client_action" id=client.id action="update" %}'}) + @setup({"url02": '{% url "client_action" id=client.id action="update" %}'}) def test_url02(self): - output = self.engine.render_to_string('url02', {'client': {'id': 1}}) - self.assertEqual(output, '/client/1/update/') + output = self.engine.render_to_string("url02", {"client": {"id": 1}}) + self.assertEqual(output, "/client/1/update/") - @setup({'url02a': '{% url "client_action" client.id "update" %}'}) + @setup({"url02a": '{% url "client_action" client.id "update" %}'}) def test_url02a(self): - output = self.engine.render_to_string('url02a', {'client': {'id': 1}}) - self.assertEqual(output, '/client/1/update/') + output = self.engine.render_to_string("url02a", {"client": {"id": 1}}) + self.assertEqual(output, "/client/1/update/") - @setup({'url02b': "{% url 'client_action' id=client.id action='update' %}"}) + @setup({"url02b": "{% url 'client_action' id=client.id action='update' %}"}) def test_url02b(self): - output = self.engine.render_to_string('url02b', {'client': {'id': 1}}) - self.assertEqual(output, '/client/1/update/') + output = self.engine.render_to_string("url02b", {"client": {"id": 1}}) + self.assertEqual(output, "/client/1/update/") - @setup({'url02c': "{% url 'client_action' client.id 'update' %}"}) + @setup({"url02c": "{% url 'client_action' client.id 'update' %}"}) def test_url02c(self): - output = self.engine.render_to_string('url02c', {'client': {'id': 1}}) - self.assertEqual(output, '/client/1/update/') + output = self.engine.render_to_string("url02c", {"client": {"id": 1}}) + self.assertEqual(output, "/client/1/update/") - @setup({'url03': '{% url "index" %}'}) + @setup({"url03": '{% url "index" %}'}) def test_url03(self): - output = self.engine.render_to_string('url03') - self.assertEqual(output, '/') + output = self.engine.render_to_string("url03") + self.assertEqual(output, "/") - @setup({'url04': '{% url "named.client" client.id %}'}) + @setup({"url04": '{% url "named.client" client.id %}'}) def test_url04(self): - output = self.engine.render_to_string('url04', {'client': {'id': 1}}) - self.assertEqual(output, '/named-client/1/') + output = self.engine.render_to_string("url04", {"client": {"id": 1}}) + self.assertEqual(output, "/named-client/1/") - @setup({'url05': '{% url "метка_оператора" v %}'}) + @setup({"url05": '{% url "метка_оператора" v %}'}) def test_url05(self): - output = self.engine.render_to_string('url05', {'v': 'Ω'}) - self.assertEqual(output, '/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/') + output = self.engine.render_to_string("url05", {"v": "Ω"}) + self.assertEqual(output, "/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/") - @setup({'url06': '{% url "метка_оператора_2" tag=v %}'}) + @setup({"url06": '{% url "метка_оператора_2" tag=v %}'}) def test_url06(self): - output = self.engine.render_to_string('url06', {'v': 'Ω'}) - self.assertEqual(output, '/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/') + output = self.engine.render_to_string("url06", {"v": "Ω"}) + self.assertEqual(output, "/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/") - @setup({'url08': '{% url "метка_оператора" v %}'}) + @setup({"url08": '{% url "метка_оператора" v %}'}) def test_url08(self): - output = self.engine.render_to_string('url08', {'v': 'Ω'}) - self.assertEqual(output, '/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/') + output = self.engine.render_to_string("url08", {"v": "Ω"}) + self.assertEqual(output, "/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/") - @setup({'url09': '{% url "метка_оператора_2" tag=v %}'}) + @setup({"url09": '{% url "метка_оператора_2" tag=v %}'}) def test_url09(self): - output = self.engine.render_to_string('url09', {'v': 'Ω'}) - self.assertEqual(output, '/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/') + output = self.engine.render_to_string("url09", {"v": "Ω"}) + self.assertEqual(output, "/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/") - @setup({'url10': '{% url "client_action" id=client.id action="two words" %}'}) + @setup({"url10": '{% url "client_action" id=client.id action="two words" %}'}) def test_url10(self): - output = self.engine.render_to_string('url10', {'client': {'id': 1}}) - self.assertEqual(output, '/client/1/two%20words/') + output = self.engine.render_to_string("url10", {"client": {"id": 1}}) + self.assertEqual(output, "/client/1/two%20words/") - @setup({'url11': '{% url "client_action" id=client.id action="==" %}'}) + @setup({"url11": '{% url "client_action" id=client.id action="==" %}'}) def test_url11(self): - output = self.engine.render_to_string('url11', {'client': {'id': 1}}) - self.assertEqual(output, '/client/1/==/') + output = self.engine.render_to_string("url11", {"client": {"id": 1}}) + self.assertEqual(output, "/client/1/==/") - @setup({'url12': '{% url "client_action" id=client.id action="!$&\'()*+,;=~:@," %}'}) + @setup( + {"url12": '{% url "client_action" id=client.id action="!$&\'()*+,;=~:@," %}'} + ) def test_url12(self): - output = self.engine.render_to_string('url12', {'client': {'id': 1}}) - self.assertEqual(output, '/client/1/!$&'()*+,;=~:@,/') + output = self.engine.render_to_string("url12", {"client": {"id": 1}}) + self.assertEqual(output, "/client/1/!$&'()*+,;=~:@,/") - @setup({'url13': '{% url "client_action" id=client.id action=arg|join:"-" %}'}) + @setup({"url13": '{% url "client_action" id=client.id action=arg|join:"-" %}'}) def test_url13(self): - output = self.engine.render_to_string('url13', {'client': {'id': 1}, 'arg': ['a', 'b']}) - self.assertEqual(output, '/client/1/a-b/') + output = self.engine.render_to_string( + "url13", {"client": {"id": 1}, "arg": ["a", "b"]} + ) + self.assertEqual(output, "/client/1/a-b/") - @setup({'url14': '{% url "client_action" client.id arg|join:"-" %}'}) + @setup({"url14": '{% url "client_action" client.id arg|join:"-" %}'}) def test_url14(self): - output = self.engine.render_to_string('url14', {'client': {'id': 1}, 'arg': ['a', 'b']}) - self.assertEqual(output, '/client/1/a-b/') + output = self.engine.render_to_string( + "url14", {"client": {"id": 1}, "arg": ["a", "b"]} + ) + self.assertEqual(output, "/client/1/a-b/") - @setup({'url15': '{% url "client_action" 12 "test" %}'}) + @setup({"url15": '{% url "client_action" 12 "test" %}'}) def test_url15(self): - output = self.engine.render_to_string('url15') - self.assertEqual(output, '/client/12/test/') + output = self.engine.render_to_string("url15") + self.assertEqual(output, "/client/12/test/") - @setup({'url18': '{% url "client" "1,2" %}'}) + @setup({"url18": '{% url "client" "1,2" %}'}) def test_url18(self): - output = self.engine.render_to_string('url18') - self.assertEqual(output, '/client/1,2/') + output = self.engine.render_to_string("url18") + self.assertEqual(output, "/client/1,2/") - @setup({'url19': '{% url named_url client.id %}'}) + @setup({"url19": "{% url named_url client.id %}"}) def test_url19(self): output = self.engine.render_to_string( - 'url19', {'client': {'id': 1}, 'named_url': 'client'} + "url19", {"client": {"id": 1}, "named_url": "client"} ) - self.assertEqual(output, '/client/1/') + self.assertEqual(output, "/client/1/") - @setup({'url20': '{% url url_name_in_var client.id %}'}) + @setup({"url20": "{% url url_name_in_var client.id %}"}) def test_url20(self): - output = self.engine.render_to_string('url20', {'client': {'id': 1}, 'url_name_in_var': 'named.client'}) - self.assertEqual(output, '/named-client/1/') + output = self.engine.render_to_string( + "url20", {"client": {"id": 1}, "url_name_in_var": "named.client"} + ) + self.assertEqual(output, "/named-client/1/") - @setup({'url21': '{% autoescape off %}' - '{% url "client_action" id=client.id action="!$&\'()*+,;=~:@," %}' - '{% endautoescape %}'}) + @setup( + { + "url21": "{% autoescape off %}" + '{% url "client_action" id=client.id action="!$&\'()*+,;=~:@," %}' + "{% endautoescape %}" + } + ) def test_url21(self): - output = self.engine.render_to_string('url21', {'client': {'id': 1}}) - self.assertEqual(output, '/client/1/!$&\'()*+,;=~:@,/') + output = self.engine.render_to_string("url21", {"client": {"id": 1}}) + self.assertEqual(output, "/client/1/!$&'()*+,;=~:@,/") # Failures - @setup({'url-fail01': '{% url %}'}) + @setup({"url-fail01": "{% url %}"}) def test_url_fail01(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('url-fail01') + self.engine.get_template("url-fail01") - @setup({'url-fail02': '{% url "no_such_view" %}'}) + @setup({"url-fail02": '{% url "no_such_view" %}'}) def test_url_fail02(self): with self.assertRaises(NoReverseMatch): - self.engine.render_to_string('url-fail02') + self.engine.render_to_string("url-fail02") - @setup({'url-fail03': '{% url "client" %}'}) + @setup({"url-fail03": '{% url "client" %}'}) def test_url_fail03(self): with self.assertRaises(NoReverseMatch): - self.engine.render_to_string('url-fail03') + self.engine.render_to_string("url-fail03") - @setup({'url-fail04': '{% url "view" id, %}'}) + @setup({"url-fail04": '{% url "view" id, %}'}) def test_url_fail04(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('url-fail04') + self.engine.get_template("url-fail04") - @setup({'url-fail05': '{% url "view" id= %}'}) + @setup({"url-fail05": '{% url "view" id= %}'}) def test_url_fail05(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('url-fail05') + self.engine.get_template("url-fail05") - @setup({'url-fail06': '{% url "view" a.id=id %}'}) + @setup({"url-fail06": '{% url "view" a.id=id %}'}) def test_url_fail06(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('url-fail06') + self.engine.get_template("url-fail06") - @setup({'url-fail07': '{% url "view" a.id!id %}'}) + @setup({"url-fail07": '{% url "view" a.id!id %}'}) def test_url_fail07(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('url-fail07') + self.engine.get_template("url-fail07") - @setup({'url-fail08': '{% url "view" id="unterminatedstring %}'}) + @setup({"url-fail08": '{% url "view" id="unterminatedstring %}'}) def test_url_fail08(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('url-fail08') + self.engine.get_template("url-fail08") - @setup({'url-fail09': '{% url "view" id=", %}'}) + @setup({"url-fail09": '{% url "view" id=", %}'}) def test_url_fail09(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('url-fail09') + self.engine.get_template("url-fail09") - @setup({'url-fail11': '{% url named_url %}'}) + @setup({"url-fail11": "{% url named_url %}"}) def test_url_fail11(self): with self.assertRaises(NoReverseMatch): - self.engine.render_to_string('url-fail11') + self.engine.render_to_string("url-fail11") - @setup({'url-fail12': '{% url named_url %}'}) + @setup({"url-fail12": "{% url named_url %}"}) def test_url_fail12(self): with self.assertRaises(NoReverseMatch): - self.engine.render_to_string('url-fail12', {'named_url': 'no_such_view'}) + self.engine.render_to_string("url-fail12", {"named_url": "no_such_view"}) - @setup({'url-fail13': '{% url named_url %}'}) + @setup({"url-fail13": "{% url named_url %}"}) def test_url_fail13(self): with self.assertRaises(NoReverseMatch): - self.engine.render_to_string('url-fail13', {'named_url': 'template_tests.views.client'}) + self.engine.render_to_string( + "url-fail13", {"named_url": "template_tests.views.client"} + ) - @setup({'url-fail14': '{% url named_url id, %}'}) + @setup({"url-fail14": "{% url named_url id, %}"}) def test_url_fail14(self): with self.assertRaises(TemplateSyntaxError): - self.engine.render_to_string('url-fail14', {'named_url': 'view'}) + self.engine.render_to_string("url-fail14", {"named_url": "view"}) - @setup({'url-fail15': '{% url named_url id= %}'}) + @setup({"url-fail15": "{% url named_url id= %}"}) def test_url_fail15(self): with self.assertRaises(TemplateSyntaxError): - self.engine.render_to_string('url-fail15', {'named_url': 'view'}) + self.engine.render_to_string("url-fail15", {"named_url": "view"}) - @setup({'url-fail16': '{% url named_url a.id=id %}'}) + @setup({"url-fail16": "{% url named_url a.id=id %}"}) def test_url_fail16(self): with self.assertRaises(TemplateSyntaxError): - self.engine.render_to_string('url-fail16', {'named_url': 'view'}) + self.engine.render_to_string("url-fail16", {"named_url": "view"}) - @setup({'url-fail17': '{% url named_url a.id!id %}'}) + @setup({"url-fail17": "{% url named_url a.id!id %}"}) def test_url_fail17(self): with self.assertRaises(TemplateSyntaxError): - self.engine.render_to_string('url-fail17', {'named_url': 'view'}) + self.engine.render_to_string("url-fail17", {"named_url": "view"}) - @setup({'url-fail18': '{% url named_url id="unterminatedstring %}'}) + @setup({"url-fail18": '{% url named_url id="unterminatedstring %}'}) def test_url_fail18(self): with self.assertRaises(TemplateSyntaxError): - self.engine.render_to_string('url-fail18', {'named_url': 'view'}) + self.engine.render_to_string("url-fail18", {"named_url": "view"}) - @setup({'url-fail19': '{% url named_url id=", %}'}) + @setup({"url-fail19": '{% url named_url id=", %}'}) def test_url_fail19(self): with self.assertRaises(TemplateSyntaxError): - self.engine.render_to_string('url-fail19', {'named_url': 'view'}) + self.engine.render_to_string("url-fail19", {"named_url": "view"}) # {% url ... as var %} - @setup({'url-asvar01': '{% url "index" as url %}'}) + @setup({"url-asvar01": '{% url "index" as url %}'}) def test_url_asvar01(self): - output = self.engine.render_to_string('url-asvar01') - self.assertEqual(output, '') + output = self.engine.render_to_string("url-asvar01") + self.assertEqual(output, "") - @setup({'url-asvar02': '{% url "index" as url %}{{ url }}'}) + @setup({"url-asvar02": '{% url "index" as url %}{{ url }}'}) def test_url_asvar02(self): - output = self.engine.render_to_string('url-asvar02') - self.assertEqual(output, '/') + output = self.engine.render_to_string("url-asvar02") + self.assertEqual(output, "/") - @setup({'url-asvar03': '{% url "no_such_view" as url %}{{ url }}'}) + @setup({"url-asvar03": '{% url "no_such_view" as url %}{{ url }}'}) def test_url_asvar03(self): - output = self.engine.render_to_string('url-asvar03') - self.assertEqual(output, '') + output = self.engine.render_to_string("url-asvar03") + self.assertEqual(output, "") - @setup({'url-namespace01': '{% url "app:named.client" 42 %}'}) + @setup({"url-namespace01": '{% url "app:named.client" 42 %}'}) def test_url_namespace01(self): - request = self.request_factory.get('/') - request.resolver_match = resolve('/ns1/') - template = self.engine.get_template('url-namespace01') + request = self.request_factory.get("/") + request.resolver_match = resolve("/ns1/") + template = self.engine.get_template("url-namespace01") context = RequestContext(request) output = template.render(context) - self.assertEqual(output, '/ns1/named-client/42/') + self.assertEqual(output, "/ns1/named-client/42/") - @setup({'url-namespace02': '{% url "app:named.client" 42 %}'}) + @setup({"url-namespace02": '{% url "app:named.client" 42 %}'}) def test_url_namespace02(self): - request = self.request_factory.get('/') - request.resolver_match = resolve('/ns2/') - template = self.engine.get_template('url-namespace02') + request = self.request_factory.get("/") + request.resolver_match = resolve("/ns2/") + template = self.engine.get_template("url-namespace02") context = RequestContext(request) output = template.render(context) - self.assertEqual(output, '/ns2/named-client/42/') + self.assertEqual(output, "/ns2/named-client/42/") - @setup({'url-namespace03': '{% url "app:named.client" 42 %}'}) + @setup({"url-namespace03": '{% url "app:named.client" 42 %}'}) def test_url_namespace03(self): - request = self.request_factory.get('/') - template = self.engine.get_template('url-namespace03') + request = self.request_factory.get("/") + template = self.engine.get_template("url-namespace03") context = RequestContext(request) output = template.render(context) - self.assertEqual(output, '/ns2/named-client/42/') + self.assertEqual(output, "/ns2/named-client/42/") - @setup({'url-namespace-no-current-app': '{% url "app:named.client" 42 %}'}) + @setup({"url-namespace-no-current-app": '{% url "app:named.client" 42 %}'}) def test_url_namespace_no_current_app(self): - request = self.request_factory.get('/') - request.resolver_match = resolve('/ns1/') + request = self.request_factory.get("/") + request.resolver_match = resolve("/ns1/") request.current_app = None - template = self.engine.get_template('url-namespace-no-current-app') + template = self.engine.get_template("url-namespace-no-current-app") context = RequestContext(request) output = template.render(context) - self.assertEqual(output, '/ns2/named-client/42/') + self.assertEqual(output, "/ns2/named-client/42/") - @setup({'url-namespace-explicit-current-app': '{% url "app:named.client" 42 %}'}) + @setup({"url-namespace-explicit-current-app": '{% url "app:named.client" 42 %}'}) def test_url_namespace_explicit_current_app(self): - request = self.request_factory.get('/') - request.resolver_match = resolve('/ns1/') - request.current_app = 'app' - template = self.engine.get_template('url-namespace-explicit-current-app') + request = self.request_factory.get("/") + request.resolver_match = resolve("/ns1/") + request.current_app = "app" + template = self.engine.get_template("url-namespace-explicit-current-app") context = RequestContext(request) output = template.render(context) - self.assertEqual(output, '/ns2/named-client/42/') + self.assertEqual(output, "/ns2/named-client/42/") class URLNodeTest(SimpleTestCase): def test_repr(self): - url_node = URLNode(view_name='named-view', args=[], kwargs={}, asvar=None) + url_node = URLNode(view_name="named-view", args=[], kwargs={}, asvar=None) self.assertEqual( repr(url_node), "<URLNode view_name='named-view' args=[] kwargs={} as=None>", ) url_node = URLNode( - view_name='named-view', + view_name="named-view", args=[1, 2], - kwargs={'action': 'update'}, - asvar='my_url', + kwargs={"action": "update"}, + asvar="my_url", ) self.assertEqual( repr(url_node), diff --git a/tests/template_tests/syntax_tests/test_verbatim.py b/tests/template_tests/syntax_tests/test_verbatim.py index 7304796b4b..afb08e013a 100644 --- a/tests/template_tests/syntax_tests/test_verbatim.py +++ b/tests/template_tests/syntax_tests/test_verbatim.py @@ -5,34 +5,47 @@ from ..utils import setup class VerbatimTagTests(SimpleTestCase): - - @setup({'verbatim-tag01': '{% verbatim %}{{bare }}{% endverbatim %}'}) + @setup({"verbatim-tag01": "{% verbatim %}{{bare }}{% endverbatim %}"}) def test_verbatim_tag01(self): - output = self.engine.render_to_string('verbatim-tag01') - self.assertEqual(output, '{{bare }}') + output = self.engine.render_to_string("verbatim-tag01") + self.assertEqual(output, "{{bare }}") - @setup({'verbatim-tag02': '{% verbatim %}{% endif %}{% endverbatim %}'}) + @setup({"verbatim-tag02": "{% verbatim %}{% endif %}{% endverbatim %}"}) def test_verbatim_tag02(self): - output = self.engine.render_to_string('verbatim-tag02') - self.assertEqual(output, '{% endif %}') + output = self.engine.render_to_string("verbatim-tag02") + self.assertEqual(output, "{% endif %}") - @setup({'verbatim-tag03': '{% verbatim %}It\'s the {% verbatim %} tag{% endverbatim %}'}) + @setup( + {"verbatim-tag03": "{% verbatim %}It's the {% verbatim %} tag{% endverbatim %}"} + ) def test_verbatim_tag03(self): - output = self.engine.render_to_string('verbatim-tag03') - self.assertEqual(output, 'It\'s the {% verbatim %} tag') + output = self.engine.render_to_string("verbatim-tag03") + self.assertEqual(output, "It's the {% verbatim %} tag") - @setup({'verbatim-tag04': '{% verbatim %}{% verbatim %}{% endverbatim %}{% endverbatim %}'}) + @setup( + { + "verbatim-tag04": "{% verbatim %}{% verbatim %}{% endverbatim %}{% endverbatim %}" + } + ) def test_verbatim_tag04(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('verbatim-tag04') + self.engine.get_template("verbatim-tag04") - @setup({'verbatim-tag05': '{% verbatim %}{% endverbatim %}{% verbatim %}{% endverbatim %}'}) + @setup( + { + "verbatim-tag05": "{% verbatim %}{% endverbatim %}{% verbatim %}{% endverbatim %}" + } + ) def test_verbatim_tag05(self): - output = self.engine.render_to_string('verbatim-tag05') - self.assertEqual(output, '') + output = self.engine.render_to_string("verbatim-tag05") + self.assertEqual(output, "") - @setup({'verbatim-tag06': '{% verbatim special %}' - 'Don\'t {% endverbatim %} just yet{% endverbatim special %}'}) + @setup( + { + "verbatim-tag06": "{% verbatim special %}" + "Don't {% endverbatim %} just yet{% endverbatim special %}" + } + ) def test_verbatim_tag06(self): - output = self.engine.render_to_string('verbatim-tag06') - self.assertEqual(output, 'Don\'t {% endverbatim %} just yet') + output = self.engine.render_to_string("verbatim-tag06") + self.assertEqual(output, "Don't {% endverbatim %} just yet") diff --git a/tests/template_tests/syntax_tests/test_width_ratio.py b/tests/template_tests/syntax_tests/test_width_ratio.py index 7db90a44e1..3f3a072f96 100644 --- a/tests/template_tests/syntax_tests/test_width_ratio.py +++ b/tests/template_tests/syntax_tests/test_width_ratio.py @@ -5,150 +5,164 @@ from ..utils import setup class WidthRatioTagTests(SimpleTestCase): - libraries = {'custom': 'template_tests.templatetags.custom'} + libraries = {"custom": "template_tests.templatetags.custom"} - @setup({'widthratio01': '{% widthratio a b 0 %}'}) + @setup({"widthratio01": "{% widthratio a b 0 %}"}) def test_widthratio01(self): - output = self.engine.render_to_string('widthratio01', {'a': 50, 'b': 100}) - self.assertEqual(output, '0') + output = self.engine.render_to_string("widthratio01", {"a": 50, "b": 100}) + self.assertEqual(output, "0") - @setup({'widthratio02': '{% widthratio a b 100 %}'}) + @setup({"widthratio02": "{% widthratio a b 100 %}"}) def test_widthratio02(self): - output = self.engine.render_to_string('widthratio02', {'a': 0, 'b': 0}) - self.assertEqual(output, '0') + output = self.engine.render_to_string("widthratio02", {"a": 0, "b": 0}) + self.assertEqual(output, "0") - @setup({'widthratio03': '{% widthratio a b 100 %}'}) + @setup({"widthratio03": "{% widthratio a b 100 %}"}) def test_widthratio03(self): - output = self.engine.render_to_string('widthratio03', {'a': 0, 'b': 100}) - self.assertEqual(output, '0') + output = self.engine.render_to_string("widthratio03", {"a": 0, "b": 100}) + self.assertEqual(output, "0") - @setup({'widthratio04': '{% widthratio a b 100 %}'}) + @setup({"widthratio04": "{% widthratio a b 100 %}"}) def test_widthratio04(self): - output = self.engine.render_to_string('widthratio04', {'a': 50, 'b': 100}) - self.assertEqual(output, '50') + output = self.engine.render_to_string("widthratio04", {"a": 50, "b": 100}) + self.assertEqual(output, "50") - @setup({'widthratio05': '{% widthratio a b 100 %}'}) + @setup({"widthratio05": "{% widthratio a b 100 %}"}) def test_widthratio05(self): - output = self.engine.render_to_string('widthratio05', {'a': 100, 'b': 100}) - self.assertEqual(output, '100') + output = self.engine.render_to_string("widthratio05", {"a": 100, "b": 100}) + self.assertEqual(output, "100") - @setup({'widthratio06': '{% widthratio a b 100 %}'}) + @setup({"widthratio06": "{% widthratio a b 100 %}"}) def test_widthratio06(self): """ 62.5 should round to 62 """ - output = self.engine.render_to_string('widthratio06', {'a': 50, 'b': 80}) - self.assertEqual(output, '62') + output = self.engine.render_to_string("widthratio06", {"a": 50, "b": 80}) + self.assertEqual(output, "62") - @setup({'widthratio07': '{% widthratio a b 100 %}'}) + @setup({"widthratio07": "{% widthratio a b 100 %}"}) def test_widthratio07(self): """ 71.4 should round to 71 """ - output = self.engine.render_to_string('widthratio07', {'a': 50, 'b': 70}) - self.assertEqual(output, '71') + output = self.engine.render_to_string("widthratio07", {"a": 50, "b": 70}) + self.assertEqual(output, "71") # Raise exception if we don't have 3 args, last one an integer - @setup({'widthratio08': '{% widthratio %}'}) + @setup({"widthratio08": "{% widthratio %}"}) def test_widthratio08(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('widthratio08') + self.engine.get_template("widthratio08") - @setup({'widthratio09': '{% widthratio a b %}'}) + @setup({"widthratio09": "{% widthratio a b %}"}) def test_widthratio09(self): with self.assertRaises(TemplateSyntaxError): - self.engine.render_to_string('widthratio09', {'a': 50, 'b': 100}) + self.engine.render_to_string("widthratio09", {"a": 50, "b": 100}) - @setup({'widthratio10': '{% widthratio a b 100.0 %}'}) + @setup({"widthratio10": "{% widthratio a b 100.0 %}"}) def test_widthratio10(self): - output = self.engine.render_to_string('widthratio10', {'a': 50, 'b': 100}) - self.assertEqual(output, '50') + output = self.engine.render_to_string("widthratio10", {"a": 50, "b": 100}) + self.assertEqual(output, "50") - @setup({'widthratio11': '{% widthratio a b c %}'}) + @setup({"widthratio11": "{% widthratio a b c %}"}) def test_widthratio11(self): """ #10043: widthratio should allow max_width to be a variable """ - output = self.engine.render_to_string('widthratio11', {'a': 50, 'c': 100, 'b': 100}) - self.assertEqual(output, '50') + output = self.engine.render_to_string( + "widthratio11", {"a": 50, "c": 100, "b": 100} + ) + self.assertEqual(output, "50") # #18739: widthratio should handle None args consistently with # non-numerics - @setup({'widthratio12a': '{% widthratio a b c %}'}) + @setup({"widthratio12a": "{% widthratio a b c %}"}) def test_widthratio12a(self): - output = self.engine.render_to_string('widthratio12a', {'a': 'a', 'c': 100, 'b': 100}) - self.assertEqual(output, '') + output = self.engine.render_to_string( + "widthratio12a", {"a": "a", "c": 100, "b": 100} + ) + self.assertEqual(output, "") - @setup({'widthratio12b': '{% widthratio a b c %}'}) + @setup({"widthratio12b": "{% widthratio a b c %}"}) def test_widthratio12b(self): - output = self.engine.render_to_string('widthratio12b', {'a': None, 'c': 100, 'b': 100}) - self.assertEqual(output, '') + output = self.engine.render_to_string( + "widthratio12b", {"a": None, "c": 100, "b": 100} + ) + self.assertEqual(output, "") - @setup({'widthratio13a': '{% widthratio a b c %}'}) + @setup({"widthratio13a": "{% widthratio a b c %}"}) def test_widthratio13a(self): - output = self.engine.render_to_string('widthratio13a', {'a': 0, 'c': 100, 'b': 'b'}) - self.assertEqual(output, '') + output = self.engine.render_to_string( + "widthratio13a", {"a": 0, "c": 100, "b": "b"} + ) + self.assertEqual(output, "") - @setup({'widthratio13b': '{% widthratio a b c %}'}) + @setup({"widthratio13b": "{% widthratio a b c %}"}) def test_widthratio13b(self): - output = self.engine.render_to_string('widthratio13b', {'a': 0, 'c': 100, 'b': None}) - self.assertEqual(output, '') + output = self.engine.render_to_string( + "widthratio13b", {"a": 0, "c": 100, "b": None} + ) + self.assertEqual(output, "") - @setup({'widthratio14a': '{% widthratio a b c %}'}) + @setup({"widthratio14a": "{% widthratio a b c %}"}) def test_widthratio14a(self): with self.assertRaises(TemplateSyntaxError): - self.engine.render_to_string('widthratio14a', {'a': 0, 'c': 'c', 'b': 100}) + self.engine.render_to_string("widthratio14a", {"a": 0, "c": "c", "b": 100}) - @setup({'widthratio14b': '{% widthratio a b c %}'}) + @setup({"widthratio14b": "{% widthratio a b c %}"}) def test_widthratio14b(self): with self.assertRaises(TemplateSyntaxError): - self.engine.render_to_string('widthratio14b', {'a': 0, 'c': None, 'b': 100}) + self.engine.render_to_string("widthratio14b", {"a": 0, "c": None, "b": 100}) - @setup({'widthratio15': '{% load custom %}{% widthratio a|noop:"x y" b 0 %}'}) + @setup({"widthratio15": '{% load custom %}{% widthratio a|noop:"x y" b 0 %}'}) def test_widthratio15(self): """ Test whitespace in filter argument """ - output = self.engine.render_to_string('widthratio15', {'a': 50, 'b': 100}) - self.assertEqual(output, '0') + output = self.engine.render_to_string("widthratio15", {"a": 50, "b": 100}) + self.assertEqual(output, "0") # Widthratio with variable assignment - @setup({'widthratio16': '{% widthratio a b 100 as variable %}-{{ variable }}-'}) + @setup({"widthratio16": "{% widthratio a b 100 as variable %}-{{ variable }}-"}) def test_widthratio16(self): - output = self.engine.render_to_string('widthratio16', {'a': 50, 'b': 100}) - self.assertEqual(output, '-50-') + output = self.engine.render_to_string("widthratio16", {"a": 50, "b": 100}) + self.assertEqual(output, "-50-") - @setup({'widthratio17': '{% widthratio a b 100 as variable %}-{{ variable }}-'}) + @setup({"widthratio17": "{% widthratio a b 100 as variable %}-{{ variable }}-"}) def test_widthratio17(self): - output = self.engine.render_to_string('widthratio17', {'a': 100, 'b': 100}) - self.assertEqual(output, '-100-') + output = self.engine.render_to_string("widthratio17", {"a": 100, "b": 100}) + self.assertEqual(output, "-100-") - @setup({'widthratio18': '{% widthratio a b 100 as %}'}) + @setup({"widthratio18": "{% widthratio a b 100 as %}"}) def test_widthratio18(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('widthratio18') + self.engine.get_template("widthratio18") - @setup({'widthratio19': '{% widthratio a b 100 not_as variable %}'}) + @setup({"widthratio19": "{% widthratio a b 100 not_as variable %}"}) def test_widthratio19(self): with self.assertRaises(TemplateSyntaxError): - self.engine.get_template('widthratio19') + self.engine.get_template("widthratio19") - @setup({'widthratio20': '{% widthratio a b 100 %}'}) + @setup({"widthratio20": "{% widthratio a b 100 %}"}) def test_widthratio20(self): - output = self.engine.render_to_string('widthratio20', {'a': float('inf'), 'b': float('inf')}) - self.assertEqual(output, '') + output = self.engine.render_to_string( + "widthratio20", {"a": float("inf"), "b": float("inf")} + ) + self.assertEqual(output, "") - @setup({'widthratio21': '{% widthratio a b 100 %}'}) + @setup({"widthratio21": "{% widthratio a b 100 %}"}) def test_widthratio21(self): - output = self.engine.render_to_string('widthratio21', {'a': float('inf'), 'b': 2}) - self.assertEqual(output, '') + output = self.engine.render_to_string( + "widthratio21", {"a": float("inf"), "b": 2} + ) + self.assertEqual(output, "") - @setup({'t': '{% widthratio a b 100 as variable %}-{{ variable }}-'}) + @setup({"t": "{% widthratio a b 100 as variable %}-{{ variable }}-"}) def test_zerodivisionerror_as_var(self): - output = self.engine.render_to_string('t', {'a': 0, 'b': 0}) - self.assertEqual(output, '-0-') + output = self.engine.render_to_string("t", {"a": 0, "b": 0}) + self.assertEqual(output, "-0-") - @setup({'t': '{% widthratio a b c as variable %}-{{ variable }}-'}) + @setup({"t": "{% widthratio a b c as variable %}-{{ variable }}-"}) def test_typeerror_as_var(self): - output = self.engine.render_to_string('t', {'a': 'a', 'c': 100, 'b': 100}) - self.assertEqual(output, '--') + output = self.engine.render_to_string("t", {"a": "a", "c": 100, "b": 100}) + self.assertEqual(output, "--") diff --git a/tests/template_tests/syntax_tests/test_with.py b/tests/template_tests/syntax_tests/test_with.py index d8f24349f5..dde581eab3 100644 --- a/tests/template_tests/syntax_tests/test_with.py +++ b/tests/template_tests/syntax_tests/test_with.py @@ -8,53 +8,61 @@ from ..utils import setup class WithTagTests(SimpleTestCase): at_least_with_one_msg = "'with' expected at least one variable assignment" - @setup({'with01': '{% with key=dict.key %}{{ key }}{% endwith %}'}) + @setup({"with01": "{% with key=dict.key %}{{ key }}{% endwith %}"}) def test_with01(self): - output = self.engine.render_to_string('with01', {'dict': {'key': 50}}) - self.assertEqual(output, '50') + output = self.engine.render_to_string("with01", {"dict": {"key": 50}}) + self.assertEqual(output, "50") - @setup({'legacywith01': '{% with dict.key as key %}{{ key }}{% endwith %}'}) + @setup({"legacywith01": "{% with dict.key as key %}{{ key }}{% endwith %}"}) def test_legacywith01(self): - output = self.engine.render_to_string('legacywith01', {'dict': {'key': 50}}) - self.assertEqual(output, '50') + output = self.engine.render_to_string("legacywith01", {"dict": {"key": 50}}) + self.assertEqual(output, "50") - @setup({'with02': '{{ key }}{% with key=dict.key %}' - '{{ key }}-{{ dict.key }}-{{ key }}' - '{% endwith %}{{ key }}'}) + @setup( + { + "with02": "{{ key }}{% with key=dict.key %}" + "{{ key }}-{{ dict.key }}-{{ key }}" + "{% endwith %}{{ key }}" + } + ) def test_with02(self): - output = self.engine.render_to_string('with02', {'dict': {'key': 50}}) + output = self.engine.render_to_string("with02", {"dict": {"key": 50}}) if self.engine.string_if_invalid: - self.assertEqual(output, 'INVALID50-50-50INVALID') + self.assertEqual(output, "INVALID50-50-50INVALID") else: - self.assertEqual(output, '50-50-50') + self.assertEqual(output, "50-50-50") - @setup({'legacywith02': '{{ key }}{% with dict.key as key %}' - '{{ key }}-{{ dict.key }}-{{ key }}' - '{% endwith %}{{ key }}'}) + @setup( + { + "legacywith02": "{{ key }}{% with dict.key as key %}" + "{{ key }}-{{ dict.key }}-{{ key }}" + "{% endwith %}{{ key }}" + } + ) def test_legacywith02(self): - output = self.engine.render_to_string('legacywith02', {'dict': {'key': 50}}) + output = self.engine.render_to_string("legacywith02", {"dict": {"key": 50}}) if self.engine.string_if_invalid: - self.assertEqual(output, 'INVALID50-50-50INVALID') + self.assertEqual(output, "INVALID50-50-50INVALID") else: - self.assertEqual(output, '50-50-50') + self.assertEqual(output, "50-50-50") - @setup({'with03': '{% with a=alpha b=beta %}{{ a }}{{ b }}{% endwith %}'}) + @setup({"with03": "{% with a=alpha b=beta %}{{ a }}{{ b }}{% endwith %}"}) def test_with03(self): - output = self.engine.render_to_string('with03', {'alpha': 'A', 'beta': 'B'}) - self.assertEqual(output, 'AB') + output = self.engine.render_to_string("with03", {"alpha": "A", "beta": "B"}) + self.assertEqual(output, "AB") - @setup({'with-error01': '{% with dict.key xx key %}{{ key }}{% endwith %}'}) + @setup({"with-error01": "{% with dict.key xx key %}{{ key }}{% endwith %}"}) def test_with_error01(self): with self.assertRaisesMessage(TemplateSyntaxError, self.at_least_with_one_msg): - self.engine.render_to_string('with-error01', {'dict': {'key': 50}}) + self.engine.render_to_string("with-error01", {"dict": {"key": 50}}) - @setup({'with-error02': '{% with dict.key as %}{{ key }}{% endwith %}'}) + @setup({"with-error02": "{% with dict.key as %}{{ key }}{% endwith %}"}) def test_with_error02(self): with self.assertRaisesMessage(TemplateSyntaxError, self.at_least_with_one_msg): - self.engine.render_to_string('with-error02', {'dict': {'key': 50}}) + self.engine.render_to_string("with-error02", {"dict": {"key": 50}}) class WithNodeTests(SimpleTestCase): def test_repr(self): - node = WithNode(nodelist=[], name='a', var='dict.key') - self.assertEqual(repr(node), '<WithNode>') + node = WithNode(nodelist=[], name="a", var="dict.key") + self.assertEqual(repr(node), "<WithNode>") diff --git a/tests/template_tests/templatetags/custom.py b/tests/template_tests/templatetags/custom.py index 0880e6fad4..f096e98286 100644 --- a/tests/template_tests/templatetags/custom.py +++ b/tests/template_tests/templatetags/custom.py @@ -64,7 +64,10 @@ explicit_no_context.anything = "Expected explicit_no_context __dict__" @register.simple_tag(takes_context=True) def no_params_with_context(context): """Expected no_params_with_context __doc__""" - return "no_params_with_context - Expected result (context value: %s)" % context['value'] + return ( + "no_params_with_context - Expected result (context value: %s)" + % context["value"] + ) no_params_with_context.anything = "Expected no_params_with_context __dict__" @@ -73,7 +76,10 @@ no_params_with_context.anything = "Expected no_params_with_context __dict__" @register.simple_tag(takes_context=True) def params_and_context(context, arg): """Expected params_and_context __doc__""" - return "params_and_context - Expected result (context value: %s): %s" % (context['value'], arg) + return "params_and_context - Expected result (context value: %s): %s" % ( + context["value"], + arg, + ) params_and_context.anything = "Expected params_and_context __dict__" @@ -99,7 +105,7 @@ def simple_keyword_only_default(*, kwarg=42): @register.simple_tag -def simple_one_default(one, two='hi'): +def simple_one_default(one, two="hi"): """Expected simple_one_default __doc__""" return "simple_one_default - Expected result: %s, %s" % (one, two) @@ -108,10 +114,10 @@ simple_one_default.anything = "Expected simple_one_default __dict__" @register.simple_tag -def simple_unlimited_args(one, two='hi', *args): +def simple_unlimited_args(one, two="hi", *args): """Expected simple_unlimited_args __doc__""" return "simple_unlimited_args - Expected result: %s" % ( - ', '.join(str(arg) for arg in [one, two, *args]) + ", ".join(str(arg) for arg in [one, two, *args]) ) @@ -121,20 +127,22 @@ simple_unlimited_args.anything = "Expected simple_unlimited_args __dict__" @register.simple_tag def simple_only_unlimited_args(*args): """Expected simple_only_unlimited_args __doc__""" - return "simple_only_unlimited_args - Expected result: %s" % ', '.join(str(arg) for arg in args) + return "simple_only_unlimited_args - Expected result: %s" % ", ".join( + str(arg) for arg in args + ) simple_only_unlimited_args.anything = "Expected simple_only_unlimited_args __dict__" @register.simple_tag -def simple_unlimited_args_kwargs(one, two='hi', *args, **kwargs): +def simple_unlimited_args_kwargs(one, two="hi", *args, **kwargs): """Expected simple_unlimited_args_kwargs __doc__""" # Sort the dictionary by key to guarantee the order for testing. sorted_kwarg = sorted(kwargs.items(), key=operator.itemgetter(0)) return "simple_unlimited_args_kwargs - Expected result: %s / %s" % ( - ', '.join(str(arg) for arg in [one, two, *args]), - ', '.join('%s=%s' % (k, v) for (k, v) in sorted_kwarg) + ", ".join(str(arg) for arg in [one, two, *args]), + ", ".join("%s=%s" % (k, v) for (k, v) in sorted_kwarg), ) @@ -147,36 +155,38 @@ def simple_tag_without_context_parameter(arg): return "Expected result" -simple_tag_without_context_parameter.anything = "Expected simple_tag_without_context_parameter __dict__" +simple_tag_without_context_parameter.anything = ( + "Expected simple_tag_without_context_parameter __dict__" +) @register.simple_tag(takes_context=True) def simple_tag_takes_context_without_params(): """Expected simple_tag_takes_context_without_params __doc__""" - return 'Expected result' + return "Expected result" simple_tag_takes_context_without_params.anything = ( - 'Expected simple_tag_takes_context_without_params __dict__' + "Expected simple_tag_takes_context_without_params __dict__" ) @register.simple_tag(takes_context=True) def escape_naive(context): """A tag that doesn't even think about escaping issues""" - return "Hello {}!".format(context['name']) + return "Hello {}!".format(context["name"]) @register.simple_tag(takes_context=True) def escape_explicit(context): """A tag that uses escape explicitly""" - return escape("Hello {}!".format(context['name'])) + return escape("Hello {}!".format(context["name"])) @register.simple_tag(takes_context=True) def escape_format_html(context): """A tag that uses format_html""" - return format_html("Hello {0}!", context['name']) + return format_html("Hello {0}!", context["name"]) @register.simple_tag(takes_context=True) @@ -189,15 +199,15 @@ def use_l10n(context): return str(context.use_l10n) -@register.simple_tag(name='minustwo') +@register.simple_tag(name="minustwo") def minustwo_overridden_name(value): return value - 2 -register.simple_tag(lambda x: x - 1, name='minusone') +register.simple_tag(lambda x: x - 1, name="minusone") -@register.tag('counter') +@register.tag("counter") def counter(parser, token): return CounterNode() diff --git a/tests/template_tests/templatetags/inclusion.py b/tests/template_tests/templatetags/inclusion.py index 45281b4c56..f9e457bbc1 100644 --- a/tests/template_tests/templatetags/inclusion.py +++ b/tests/template_tests/templatetags/inclusion.py @@ -6,7 +6,7 @@ engine = Engine(app_dirs=True) register = Library() -@register.inclusion_tag('inclusion.html') +@register.inclusion_tag("inclusion.html") def inclusion_no_params(): """Expected inclusion_no_params __doc__""" return {"result": "inclusion_no_params - Expected result"} @@ -15,16 +15,18 @@ def inclusion_no_params(): inclusion_no_params.anything = "Expected inclusion_no_params __dict__" -@register.inclusion_tag(engine.get_template('inclusion.html')) +@register.inclusion_tag(engine.get_template("inclusion.html")) def inclusion_no_params_from_template(): """Expected inclusion_no_params_from_template __doc__""" return {"result": "inclusion_no_params_from_template - Expected result"} -inclusion_no_params_from_template.anything = "Expected inclusion_no_params_from_template __dict__" +inclusion_no_params_from_template.anything = ( + "Expected inclusion_no_params_from_template __dict__" +) -@register.inclusion_tag('inclusion.html') +@register.inclusion_tag("inclusion.html") def inclusion_one_param(arg): """Expected inclusion_one_param __doc__""" return {"result": "inclusion_one_param - Expected result: %s" % arg} @@ -33,48 +35,63 @@ def inclusion_one_param(arg): inclusion_one_param.anything = "Expected inclusion_one_param __dict__" -@register.inclusion_tag(engine.get_template('inclusion.html')) +@register.inclusion_tag(engine.get_template("inclusion.html")) def inclusion_one_param_from_template(arg): """Expected inclusion_one_param_from_template __doc__""" return {"result": "inclusion_one_param_from_template - Expected result: %s" % arg} -inclusion_one_param_from_template.anything = "Expected inclusion_one_param_from_template __dict__" +inclusion_one_param_from_template.anything = ( + "Expected inclusion_one_param_from_template __dict__" +) -@register.inclusion_tag('inclusion.html', takes_context=False) +@register.inclusion_tag("inclusion.html", takes_context=False) def inclusion_explicit_no_context(arg): """Expected inclusion_explicit_no_context __doc__""" return {"result": "inclusion_explicit_no_context - Expected result: %s" % arg} -inclusion_explicit_no_context.anything = "Expected inclusion_explicit_no_context __dict__" +inclusion_explicit_no_context.anything = ( + "Expected inclusion_explicit_no_context __dict__" +) -@register.inclusion_tag(engine.get_template('inclusion.html'), takes_context=False) +@register.inclusion_tag(engine.get_template("inclusion.html"), takes_context=False) def inclusion_explicit_no_context_from_template(arg): """Expected inclusion_explicit_no_context_from_template __doc__""" - return {"result": "inclusion_explicit_no_context_from_template - Expected result: %s" % arg} + return { + "result": "inclusion_explicit_no_context_from_template - Expected result: %s" + % arg + } -inclusion_explicit_no_context_from_template.anything = "Expected inclusion_explicit_no_context_from_template __dict__" +inclusion_explicit_no_context_from_template.anything = ( + "Expected inclusion_explicit_no_context_from_template __dict__" +) -@register.inclusion_tag('inclusion.html', takes_context=True) +@register.inclusion_tag("inclusion.html", takes_context=True) def inclusion_no_params_with_context(context): """Expected inclusion_no_params_with_context __doc__""" - return {"result": "inclusion_no_params_with_context - Expected result (context value: %s)" % context['value']} + return { + "result": "inclusion_no_params_with_context - Expected result (context value: %s)" + % context["value"] + } -inclusion_no_params_with_context.anything = "Expected inclusion_no_params_with_context __dict__" +inclusion_no_params_with_context.anything = ( + "Expected inclusion_no_params_with_context __dict__" +) -@register.inclusion_tag(engine.get_template('inclusion.html'), takes_context=True) +@register.inclusion_tag(engine.get_template("inclusion.html"), takes_context=True) def inclusion_no_params_with_context_from_template(context): """Expected inclusion_no_params_with_context_from_template __doc__""" return { "result": ( - "inclusion_no_params_with_context_from_template - Expected result (context value: %s)" % context['value'] + "inclusion_no_params_with_context_from_template - Expected result (context value: %s)" + % context["value"] ) } @@ -84,32 +101,35 @@ inclusion_no_params_with_context_from_template.anything = ( ) -@register.inclusion_tag('inclusion.html', takes_context=True) +@register.inclusion_tag("inclusion.html", takes_context=True) def inclusion_params_and_context(context, arg): """Expected inclusion_params_and_context __doc__""" return { - "result": "inclusion_params_and_context - Expected result (context value: %s): %s" % (context['value'], arg) + "result": "inclusion_params_and_context - Expected result (context value: %s): %s" + % (context["value"], arg) } inclusion_params_and_context.anything = "Expected inclusion_params_and_context __dict__" -@register.inclusion_tag(engine.get_template('inclusion.html'), takes_context=True) +@register.inclusion_tag(engine.get_template("inclusion.html"), takes_context=True) def inclusion_params_and_context_from_template(context, arg): """Expected inclusion_params_and_context_from_template __doc__""" return { "result": ( "inclusion_params_and_context_from_template - Expected result " - "(context value: %s): %s" % (context['value'], arg) + "(context value: %s): %s" % (context["value"], arg) ) } -inclusion_params_and_context_from_template.anything = "Expected inclusion_params_and_context_from_template __dict__" +inclusion_params_and_context_from_template.anything = ( + "Expected inclusion_params_and_context_from_template __dict__" +) -@register.inclusion_tag('inclusion.html') +@register.inclusion_tag("inclusion.html") def inclusion_two_params(one, two): """Expected inclusion_two_params __doc__""" return {"result": "inclusion_two_params - Expected result: %s, %s" % (one, two)} @@ -118,17 +138,22 @@ def inclusion_two_params(one, two): inclusion_two_params.anything = "Expected inclusion_two_params __dict__" -@register.inclusion_tag(engine.get_template('inclusion.html')) +@register.inclusion_tag(engine.get_template("inclusion.html")) def inclusion_two_params_from_template(one, two): """Expected inclusion_two_params_from_template __doc__""" - return {"result": "inclusion_two_params_from_template - Expected result: %s, %s" % (one, two)} + return { + "result": "inclusion_two_params_from_template - Expected result: %s, %s" + % (one, two) + } -inclusion_two_params_from_template.anything = "Expected inclusion_two_params_from_template __dict__" +inclusion_two_params_from_template.anything = ( + "Expected inclusion_two_params_from_template __dict__" +) -@register.inclusion_tag('inclusion.html') -def inclusion_one_default(one, two='hi'): +@register.inclusion_tag("inclusion.html") +def inclusion_one_default(one, two="hi"): """Expected inclusion_one_default __doc__""" return {"result": "inclusion_one_default - Expected result: %s, %s" % (one, two)} @@ -136,32 +161,34 @@ def inclusion_one_default(one, two='hi'): inclusion_one_default.anything = "Expected inclusion_one_default __dict__" -@register.inclusion_tag('inclusion.html') +@register.inclusion_tag("inclusion.html") def inclusion_keyword_only_default(*, kwarg=42): return { - 'result': ( - 'inclusion_keyword_only_default - Expected result: %s' % kwarg - ), + "result": ("inclusion_keyword_only_default - Expected result: %s" % kwarg), } -@register.inclusion_tag(engine.get_template('inclusion.html')) -def inclusion_one_default_from_template(one, two='hi'): +@register.inclusion_tag(engine.get_template("inclusion.html")) +def inclusion_one_default_from_template(one, two="hi"): """Expected inclusion_one_default_from_template __doc__""" - return {"result": "inclusion_one_default_from_template - Expected result: %s, %s" % (one, two)} + return { + "result": "inclusion_one_default_from_template - Expected result: %s, %s" + % (one, two) + } -inclusion_one_default_from_template.anything = "Expected inclusion_one_default_from_template __dict__" +inclusion_one_default_from_template.anything = ( + "Expected inclusion_one_default_from_template __dict__" +) -@register.inclusion_tag('inclusion.html') -def inclusion_unlimited_args(one, two='hi', *args): +@register.inclusion_tag("inclusion.html") +def inclusion_unlimited_args(one, two="hi", *args): """Expected inclusion_unlimited_args __doc__""" return { "result": ( - "inclusion_unlimited_args - Expected result: %s" % ( - ', '.join(str(arg) for arg in [one, two, *args]) - ) + "inclusion_unlimited_args - Expected result: %s" + % (", ".join(str(arg) for arg in [one, two, *args])) ) } @@ -169,48 +196,51 @@ def inclusion_unlimited_args(one, two='hi', *args): inclusion_unlimited_args.anything = "Expected inclusion_unlimited_args __dict__" -@register.inclusion_tag(engine.get_template('inclusion.html')) -def inclusion_unlimited_args_from_template(one, two='hi', *args): +@register.inclusion_tag(engine.get_template("inclusion.html")) +def inclusion_unlimited_args_from_template(one, two="hi", *args): """Expected inclusion_unlimited_args_from_template __doc__""" return { "result": ( - "inclusion_unlimited_args_from_template - Expected result: %s" % ( - ', '.join(str(arg) for arg in [one, two, *args]) - ) + "inclusion_unlimited_args_from_template - Expected result: %s" + % (", ".join(str(arg) for arg in [one, two, *args])) ) } -inclusion_unlimited_args_from_template.anything = "Expected inclusion_unlimited_args_from_template __dict__" +inclusion_unlimited_args_from_template.anything = ( + "Expected inclusion_unlimited_args_from_template __dict__" +) -@register.inclusion_tag('inclusion.html') +@register.inclusion_tag("inclusion.html") def inclusion_only_unlimited_args(*args): """Expected inclusion_only_unlimited_args __doc__""" return { - "result": "inclusion_only_unlimited_args - Expected result: %s" % ( - ', '.join(str(arg) for arg in args) - ) + "result": "inclusion_only_unlimited_args - Expected result: %s" + % (", ".join(str(arg) for arg in args)) } -inclusion_only_unlimited_args.anything = "Expected inclusion_only_unlimited_args __dict__" +inclusion_only_unlimited_args.anything = ( + "Expected inclusion_only_unlimited_args __dict__" +) -@register.inclusion_tag(engine.get_template('inclusion.html')) +@register.inclusion_tag(engine.get_template("inclusion.html")) def inclusion_only_unlimited_args_from_template(*args): """Expected inclusion_only_unlimited_args_from_template __doc__""" return { - "result": "inclusion_only_unlimited_args_from_template - Expected result: %s" % ( - ', '.join(str(arg) for arg in args) - ) + "result": "inclusion_only_unlimited_args_from_template - Expected result: %s" + % (", ".join(str(arg) for arg in args)) } -inclusion_only_unlimited_args_from_template.anything = "Expected inclusion_only_unlimited_args_from_template __dict__" +inclusion_only_unlimited_args_from_template.anything = ( + "Expected inclusion_only_unlimited_args_from_template __dict__" +) -@register.inclusion_tag('test_incl_tag_use_l10n.html', takes_context=True) +@register.inclusion_tag("test_incl_tag_use_l10n.html", takes_context=True) def inclusion_tag_use_l10n(context): """Expected inclusion_tag_use_l10n __doc__""" return {} @@ -219,45 +249,52 @@ def inclusion_tag_use_l10n(context): inclusion_tag_use_l10n.anything = "Expected inclusion_tag_use_l10n __dict__" -@register.inclusion_tag('inclusion.html') -def inclusion_unlimited_args_kwargs(one, two='hi', *args, **kwargs): +@register.inclusion_tag("inclusion.html") +def inclusion_unlimited_args_kwargs(one, two="hi", *args, **kwargs): """Expected inclusion_unlimited_args_kwargs __doc__""" # Sort the dictionary by key to guarantee the order for testing. sorted_kwarg = sorted(kwargs.items(), key=operator.itemgetter(0)) - return {"result": "inclusion_unlimited_args_kwargs - Expected result: %s / %s" % ( - ', '.join(str(arg) for arg in [one, two, *args]), - ', '.join('%s=%s' % (k, v) for (k, v) in sorted_kwarg) - )} + return { + "result": "inclusion_unlimited_args_kwargs - Expected result: %s / %s" + % ( + ", ".join(str(arg) for arg in [one, two, *args]), + ", ".join("%s=%s" % (k, v) for (k, v) in sorted_kwarg), + ) + } -inclusion_unlimited_args_kwargs.anything = "Expected inclusion_unlimited_args_kwargs __dict__" +inclusion_unlimited_args_kwargs.anything = ( + "Expected inclusion_unlimited_args_kwargs __dict__" +) -@register.inclusion_tag('inclusion.html', takes_context=True) +@register.inclusion_tag("inclusion.html", takes_context=True) def inclusion_tag_without_context_parameter(arg): """Expected inclusion_tag_without_context_parameter __doc__""" return {} -inclusion_tag_without_context_parameter.anything = "Expected inclusion_tag_without_context_parameter __dict__" +inclusion_tag_without_context_parameter.anything = ( + "Expected inclusion_tag_without_context_parameter __dict__" +) -@register.inclusion_tag('inclusion.html', takes_context=True) +@register.inclusion_tag("inclusion.html", takes_context=True) def inclusion_tag_takes_context_without_params(): """Expected inclusion_tag_takes_context_without_params __doc__""" return {} inclusion_tag_takes_context_without_params.anything = ( - 'Expected inclusion_tag_takes_context_without_params __dict__' + "Expected inclusion_tag_takes_context_without_params __dict__" ) -@register.inclusion_tag('inclusion_extends1.html') +@register.inclusion_tag("inclusion_extends1.html") def inclusion_extends1(): return {} -@register.inclusion_tag('inclusion_extends2.html') +@register.inclusion_tag("inclusion_extends2.html") def inclusion_extends2(): return {} diff --git a/tests/template_tests/templatetags/tag_27584.py b/tests/template_tests/templatetags/tag_27584.py index 8c675be16b..80ea9cb6f4 100644 --- a/tests/template_tests/templatetags/tag_27584.py +++ b/tests/template_tests/templatetags/tag_27584.py @@ -5,11 +5,11 @@ register = template.Library() @register.tag def badtag(parser, token): - parser.parse(('endbadtag',)) + parser.parse(("endbadtag",)) parser.delete_first_token() return BadNode() class BadNode(template.Node): def render(self, context): - raise template.TemplateSyntaxError('error') + raise template.TemplateSyntaxError("error") diff --git a/tests/template_tests/templatetags/testtags.py b/tests/template_tests/templatetags/testtags.py index 4b839a9a54..85f76dc912 100644 --- a/tests/template_tests/templatetags/testtags.py +++ b/tests/template_tests/templatetags/testtags.py @@ -8,7 +8,7 @@ class EchoNode(Node): self.contents = contents def render(self, context): - return ' '.join(self.contents) + return " ".join(self.contents) @register.tag @@ -16,7 +16,7 @@ def echo(parser, token): return EchoNode(token.contents.split()[1:]) -register.tag('other_echo', echo) +register.tag("other_echo", echo) @register.filter diff --git a/tests/template_tests/test_autoreloader.py b/tests/template_tests/test_autoreloader.py index 0f62181f3c..cc2c3f58a5 100644 --- a/tests/template_tests/test_autoreloader.py +++ b/tests/template_tests/test_autoreloader.py @@ -10,31 +10,35 @@ EXTRA_TEMPLATES_DIR = ROOT / "templates_extra" @override_settings( - INSTALLED_APPS=['template_tests'], - TEMPLATES=[{ - 'BACKEND': 'django.template.backends.dummy.TemplateStrings', - 'APP_DIRS': True, - }, { - 'BACKEND': 'django.template.backends.django.DjangoTemplates', - 'DIRS': [EXTRA_TEMPLATES_DIR], - 'OPTIONS': { - 'context_processors': [ - 'django.template.context_processors.request', - ], - 'loaders': [ - 'django.template.loaders.filesystem.Loader', - 'django.template.loaders.app_directories.Loader', - ] + INSTALLED_APPS=["template_tests"], + TEMPLATES=[ + { + "BACKEND": "django.template.backends.dummy.TemplateStrings", + "APP_DIRS": True, + }, + { + "BACKEND": "django.template.backends.django.DjangoTemplates", + "DIRS": [EXTRA_TEMPLATES_DIR], + "OPTIONS": { + "context_processors": [ + "django.template.context_processors.request", + ], + "loaders": [ + "django.template.loaders.filesystem.Loader", + "django.template.loaders.app_directories.Loader", + ], + }, }, - }]) + ], +) class TemplateReloadTests(SimpleTestCase): - @mock.patch('django.template.autoreload.reset_loaders') + @mock.patch("django.template.autoreload.reset_loaders") def test_template_changed(self, mock_reset): - template_path = Path(__file__).parent / 'templates' / 'index.html' + template_path = Path(__file__).parent / "templates" / "index.html" self.assertTrue(autoreload.template_changed(None, template_path)) mock_reset.assert_called_once() - @mock.patch('django.template.autoreload.reset_loaders') + @mock.patch("django.template.autoreload.reset_loaders") def test_non_template_changed(self, mock_reset): self.assertIsNone(autoreload.template_changed(None, Path(__file__))) mock_reset.assert_not_called() @@ -42,12 +46,12 @@ class TemplateReloadTests(SimpleTestCase): @override_settings( TEMPLATES=[ { - 'DIRS': [ROOT], - 'BACKEND': 'django.template.backends.django.DjangoTemplates', + "DIRS": [ROOT], + "BACKEND": "django.template.backends.django.DjangoTemplates", } ] ) - @mock.patch('django.template.autoreload.reset_loaders') + @mock.patch("django.template.autoreload.reset_loaders") def test_non_template_changed_in_template_directory(self, mock_reset): self.assertIsNone(autoreload.template_changed(None, Path(__file__))) mock_reset.assert_not_called() @@ -58,48 +62,50 @@ class TemplateReloadTests(SimpleTestCase): self.assertSequenceEqual( sorted(mock_reloader.watch_dir.call_args_list), [ - mock.call(ROOT / 'templates', '**/*'), - mock.call(ROOT / 'templates_extra', '**/*') - ] + mock.call(ROOT / "templates", "**/*"), + mock.call(ROOT / "templates_extra", "**/*"), + ], ) def test_get_template_directories(self): self.assertSetEqual( autoreload.get_template_directories(), { - ROOT / 'templates_extra', - ROOT / 'templates', - } + ROOT / "templates_extra", + ROOT / "templates", + }, ) - @mock.patch('django.template.loaders.base.Loader.reset') + @mock.patch("django.template.loaders.base.Loader.reset") def test_reset_all_loaders(self, mock_reset): autoreload.reset_loaders() self.assertEqual(mock_reset.call_count, 2) @override_settings( - TEMPLATES=[{ - 'DIRS': [ - str(ROOT) + '/absolute_str', - 'template_tests/relative_str', - Path('template_tests/relative_path'), - ], - 'BACKEND': 'django.template.backends.django.DjangoTemplates', - }] + TEMPLATES=[ + { + "DIRS": [ + str(ROOT) + "/absolute_str", + "template_tests/relative_str", + Path("template_tests/relative_path"), + ], + "BACKEND": "django.template.backends.django.DjangoTemplates", + } + ] ) def test_template_dirs_normalized_to_paths(self): self.assertSetEqual( autoreload.get_template_directories(), { - ROOT / 'absolute_str', - Path.cwd() / 'template_tests/relative_str', - Path.cwd() / 'template_tests/relative_path', - } + ROOT / "absolute_str", + Path.cwd() / "template_tests/relative_str", + Path.cwd() / "template_tests/relative_path", + }, ) @require_jinja2 -@override_settings(INSTALLED_APPS=['template_tests']) +@override_settings(INSTALLED_APPS=["template_tests"]) class Jinja2TemplateReloadTests(SimpleTestCase): def test_watch_for_template_changes(self): mock_reloader = mock.MagicMock() @@ -107,19 +113,19 @@ class Jinja2TemplateReloadTests(SimpleTestCase): self.assertSequenceEqual( sorted(mock_reloader.watch_dir.call_args_list), [ - mock.call(ROOT / 'templates', '**/*'), - ] + mock.call(ROOT / "templates", "**/*"), + ], ) def test_get_template_directories(self): self.assertSetEqual( autoreload.get_template_directories(), { - ROOT / 'templates', - } + ROOT / "templates", + }, ) - @mock.patch('django.template.loaders.base.Loader.reset') + @mock.patch("django.template.loaders.base.Loader.reset") def test_reset_all_loaders(self, mock_reset): autoreload.reset_loaders() self.assertEqual(mock_reset.call_count, 0) diff --git a/tests/template_tests/test_base.py b/tests/template_tests/test_base.py index 64fc562626..7b85d1de80 100644 --- a/tests/template_tests/test_base.py +++ b/tests/template_tests/test_base.py @@ -6,28 +6,30 @@ from django.utils.translation import gettext_lazy class LexerTestMixin: template_string = ( - 'text\n' - '{% if test %}{{ varvalue }}{% endif %}' - '{#comment {{not a var}} %{not a block}% #}' - 'end text' + "text\n" + "{% if test %}{{ varvalue }}{% endif %}" + "{#comment {{not a var}} %{not a block}% #}" + "end text" ) expected_token_tuples = [ # (token_type, contents, lineno, position) - (TokenType.TEXT, 'text\n', 1, (0, 5)), - (TokenType.BLOCK, 'if test', 2, (5, 18)), - (TokenType.VAR, 'varvalue', 2, (18, 32)), - (TokenType.BLOCK, 'endif', 2, (32, 43)), - (TokenType.COMMENT, 'comment {{not a var}} %{not a block}%', 2, (43, 85)), - (TokenType.TEXT, 'end text', 2, (85, 93)), + (TokenType.TEXT, "text\n", 1, (0, 5)), + (TokenType.BLOCK, "if test", 2, (5, 18)), + (TokenType.VAR, "varvalue", 2, (18, 32)), + (TokenType.BLOCK, "endif", 2, (32, 43)), + (TokenType.COMMENT, "comment {{not a var}} %{not a block}%", 2, (43, 85)), + (TokenType.TEXT, "end text", 2, (85, 93)), ] def test_tokenize(self): tokens = self.lexer_class(self.template_string).tokenize() - token_tuples = [(t.token_type, t.contents, t.lineno, t.position) for t in tokens] + token_tuples = [ + (t.token_type, t.contents, t.lineno, t.position) for t in tokens + ] self.assertEqual(token_tuples, self.make_expected()) def make_expected(self): - raise NotImplementedError('This method must be implemented by a subclass.') + raise NotImplementedError("This method must be implemented by a subclass.") class LexerTests(LexerTestMixin, SimpleTestCase): @@ -47,14 +49,14 @@ class DebugLexerTests(LexerTestMixin, SimpleTestCase): class TemplateTests(SimpleTestCase): def test_lazy_template_string(self): - template_string = gettext_lazy('lazy string') + template_string = gettext_lazy("lazy string") self.assertEqual(Template(template_string).render(Context()), template_string) def test_repr(self): template = Template( - '<html><body>\n' - '{% if test %}<h1>{{ varvalue }}</h1>{% endif %}' - '</body></html>' + "<html><body>\n" + "{% if test %}<h1>{{ varvalue }}</h1>{% endif %}" + "</body></html>" ) self.assertEqual( repr(template), @@ -64,19 +66,21 @@ class TemplateTests(SimpleTestCase): class VariableDoesNotExistTests(SimpleTestCase): def test_str(self): - exc = VariableDoesNotExist(msg='Failed lookup in %r', params=({'foo': 'bar'},)) + exc = VariableDoesNotExist(msg="Failed lookup in %r", params=({"foo": "bar"},)) self.assertEqual(str(exc), "Failed lookup in {'foo': 'bar'}") class VariableTests(SimpleTestCase): def test_integer_literals(self): - self.assertEqual(Variable('999999999999999999999999999').literal, 999999999999999999999999999) + self.assertEqual( + Variable("999999999999999999999999999").literal, 999999999999999999999999999 + ) def test_nonliterals(self): """Variable names that aren't resolved as literals.""" var_names = [] - for var in ('inf', 'infinity', 'iNFiniTy', 'nan'): - var_names.extend((var, '-' + var, '+' + var)) + for var in ("inf", "infinity", "iNFiniTy", "nan"): + var_names.extend((var, "-" + var, "+" + var)) for var in var_names: with self.subTest(var=var): self.assertIsNone(Variable(var).literal) diff --git a/tests/template_tests/test_callables.py b/tests/template_tests/test_callables.py index b72b122deb..acd8fb9d2c 100644 --- a/tests/template_tests/test_callables.py +++ b/tests/template_tests/test_callables.py @@ -4,14 +4,12 @@ from django.template import Context, Engine class CallableVariablesTests(TestCase): - @classmethod def setUpClass(cls): cls.engine = Engine() super().setUpClass() def test_callable(self): - class Doodad: def __init__(self, value): self.num_calls = 0 @@ -27,20 +25,19 @@ class CallableVariablesTests(TestCase): # We can't access ``my_doodad.value`` in the template, because # ``my_doodad.__call__`` will be invoked first, yielding a dictionary # without a key ``value``. - t = self.engine.from_string('{{ my_doodad.value }}') - self.assertEqual(t.render(c), '') + t = self.engine.from_string("{{ my_doodad.value }}") + self.assertEqual(t.render(c), "") # We can confirm that the doodad has been called self.assertEqual(my_doodad.num_calls, 1) # But we can access keys on the dict that's returned # by ``__call__``, instead. - t = self.engine.from_string('{{ my_doodad.the_value }}') - self.assertEqual(t.render(c), '42') + t = self.engine.from_string("{{ my_doodad.the_value }}") + self.assertEqual(t.render(c), "42") self.assertEqual(my_doodad.num_calls, 2) def test_alters_data(self): - class Doodad: alters_data = True @@ -57,17 +54,16 @@ class CallableVariablesTests(TestCase): # Since ``my_doodad.alters_data`` is True, the template system will not # try to call our doodad but will use string_if_invalid - t = self.engine.from_string('{{ my_doodad.value }}') - self.assertEqual(t.render(c), '') - t = self.engine.from_string('{{ my_doodad.the_value }}') - self.assertEqual(t.render(c), '') + t = self.engine.from_string("{{ my_doodad.value }}") + self.assertEqual(t.render(c), "") + t = self.engine.from_string("{{ my_doodad.the_value }}") + self.assertEqual(t.render(c), "") # Double-check that the object was really never called during the # template rendering. self.assertEqual(my_doodad.num_calls, 0) def test_do_not_call(self): - class Doodad: do_not_call_in_templates = True @@ -86,10 +82,10 @@ class CallableVariablesTests(TestCase): # system will not try to call our doodad. We can access its attributes # as normal, and we don't have access to the dict that it returns when # called. - t = self.engine.from_string('{{ my_doodad.value }}') - self.assertEqual(t.render(c), '42') - t = self.engine.from_string('{{ my_doodad.the_value }}') - self.assertEqual(t.render(c), '') + t = self.engine.from_string("{{ my_doodad.value }}") + self.assertEqual(t.render(c), "42") + t = self.engine.from_string("{{ my_doodad.the_value }}") + self.assertEqual(t.render(c), "") # Double-check that the object was really never called during the # template rendering. @@ -115,10 +111,10 @@ class CallableVariablesTests(TestCase): my_doodad = Doodad(42) c = Context({"my_doodad": my_doodad}) - t = self.engine.from_string('{{ my_doodad.value }}') - self.assertEqual(t.render(c), '42') - t = self.engine.from_string('{{ my_doodad.the_value }}') - self.assertEqual(t.render(c), '') + t = self.engine.from_string("{{ my_doodad.value }}") + self.assertEqual(t.render(c), "42") + t = self.engine.from_string("{{ my_doodad.the_value }}") + self.assertEqual(t.render(c), "") # Double-check that the object was really never called during the # template rendering. diff --git a/tests/template_tests/test_context.py b/tests/template_tests/test_context.py index 1150a14639..4feb9e57d6 100644 --- a/tests/template_tests/test_context.py +++ b/tests/template_tests/test_context.py @@ -2,14 +2,18 @@ from unittest import mock from django.http import HttpRequest from django.template import ( - Context, Engine, RequestContext, Template, Variable, VariableDoesNotExist, + Context, + Engine, + RequestContext, + Template, + Variable, + VariableDoesNotExist, ) from django.template.context import RenderContext from django.test import RequestFactory, SimpleTestCase class ContextTests(SimpleTestCase): - def test_context(self): c = Context({"a": 1, "b": "xyzzy"}) self.assertEqual(c["a"], 1) @@ -25,75 +29,75 @@ class ContextTests(SimpleTestCase): def test_push_context_manager(self): c = Context({"a": 1}) with c.push(): - c['a'] = 2 - self.assertEqual(c['a'], 2) - self.assertEqual(c['a'], 1) + c["a"] = 2 + self.assertEqual(c["a"], 2) + self.assertEqual(c["a"], 1) with c.push(a=3): - self.assertEqual(c['a'], 3) - self.assertEqual(c['a'], 1) + self.assertEqual(c["a"], 3) + self.assertEqual(c["a"], 1) def test_update_context_manager(self): c = Context({"a": 1}) with c.update({}): - c['a'] = 2 - self.assertEqual(c['a'], 2) - self.assertEqual(c['a'], 1) + c["a"] = 2 + self.assertEqual(c["a"], 2) + self.assertEqual(c["a"], 1) - with c.update({'a': 3}): - self.assertEqual(c['a'], 3) - self.assertEqual(c['a'], 1) + with c.update({"a": 3}): + self.assertEqual(c["a"], 3) + self.assertEqual(c["a"], 1) def test_push_context_manager_with_context_object(self): - c = Context({'a': 1}) - with c.push(Context({'a': 3})): - self.assertEqual(c['a'], 3) - self.assertEqual(c['a'], 1) + c = Context({"a": 1}) + with c.push(Context({"a": 3})): + self.assertEqual(c["a"], 3) + self.assertEqual(c["a"], 1) def test_update_context_manager_with_context_object(self): - c = Context({'a': 1}) - with c.update(Context({'a': 3})): - self.assertEqual(c['a'], 3) - self.assertEqual(c['a'], 1) + c = Context({"a": 1}) + with c.update(Context({"a": 3})): + self.assertEqual(c["a"], 3) + self.assertEqual(c["a"], 1) def test_push_proper_layering(self): - c = Context({'a': 1}) - c.push(Context({'b': 2})) - c.push(Context({'c': 3, 'd': {'z': '26'}})) + c = Context({"a": 1}) + c.push(Context({"b": 2})) + c.push(Context({"c": 3, "d": {"z": "26"}})) self.assertEqual( c.dicts, [ - {'False': False, 'None': None, 'True': True}, - {'a': 1}, - {'b': 2}, - {'c': 3, 'd': {'z': '26'}}, - ] + {"False": False, "None": None, "True": True}, + {"a": 1}, + {"b": 2}, + {"c": 3, "d": {"z": "26"}}, + ], ) def test_update_proper_layering(self): - c = Context({'a': 1}) - c.update(Context({'b': 2})) - c.update(Context({'c': 3, 'd': {'z': '26'}})) + c = Context({"a": 1}) + c.update(Context({"b": 2})) + c.update(Context({"c": 3, "d": {"z": "26"}})) self.assertEqual( c.dicts, [ - {'False': False, 'None': None, 'True': True}, - {'a': 1}, - {'b': 2}, - {'c': 3, 'd': {'z': '26'}}, - ] + {"False": False, "None": None, "True": True}, + {"a": 1}, + {"b": 2}, + {"c": 3, "d": {"z": "26"}}, + ], ) def test_setdefault(self): c = Context() - x = c.setdefault('x', 42) + x = c.setdefault("x", 42) self.assertEqual(x, 42) - self.assertEqual(c['x'], 42) + self.assertEqual(c["x"], 42) - x = c.setdefault('x', 100) + x = c.setdefault("x", 100) self.assertEqual(x, 42) - self.assertEqual(c['x'], 42) + self.assertEqual(c["x"], 42) def test_resolve_on_context_method(self): """ @@ -102,61 +106,64 @@ class ContextTests(SimpleTestCase): empty_context = Context() with self.assertRaises(VariableDoesNotExist): - Variable('no_such_variable').resolve(empty_context) + Variable("no_such_variable").resolve(empty_context) with self.assertRaises(VariableDoesNotExist): - Variable('new').resolve(empty_context) + Variable("new").resolve(empty_context) self.assertEqual( - Variable('new').resolve(Context({'new': 'foo'})), - 'foo', + Variable("new").resolve(Context({"new": "foo"})), + "foo", ) def test_render_context(self): - test_context = RenderContext({'fruit': 'papaya'}) + test_context = RenderContext({"fruit": "papaya"}) # push() limits access to the topmost dict test_context.push() - test_context['vegetable'] = 'artichoke' - self.assertEqual(list(test_context), ['vegetable']) + test_context["vegetable"] = "artichoke" + self.assertEqual(list(test_context), ["vegetable"]) - self.assertNotIn('fruit', test_context) + self.assertNotIn("fruit", test_context) with self.assertRaises(KeyError): - test_context['fruit'] - self.assertIsNone(test_context.get('fruit')) + test_context["fruit"] + self.assertIsNone(test_context.get("fruit")) def test_flatten_context(self): a = Context() - a.update({'a': 2}) - a.update({'b': 4}) - a.update({'c': 8}) + a.update({"a": 2}) + a.update({"b": 4}) + a.update({"c": 8}) - self.assertEqual(a.flatten(), { - 'False': False, 'None': None, 'True': True, - 'a': 2, 'b': 4, 'c': 8 - }) + self.assertEqual( + a.flatten(), + {"False": False, "None": None, "True": True, "a": 2, "b": 4, "c": 8}, + ) def test_flatten_context_with_context(self): """ Context.push() with a Context argument should work. """ - a = Context({'a': 2}) - a.push(Context({'z': '8'})) - self.assertEqual(a.flatten(), { - 'False': False, - 'None': None, - 'True': True, - 'a': 2, - 'z': '8', - }) + a = Context({"a": 2}) + a.push(Context({"z": "8"})) + self.assertEqual( + a.flatten(), + { + "False": False, + "None": None, + "True": True, + "a": 2, + "z": "8", + }, + ) def test_context_comparable(self): """ #21765 -- equality comparison should work """ - test_data = {'x': 'y', 'v': 'z', 'd': {'o': object, 'a': 'b'}} + test_data = {"x": "y", "v": "z", "d": {"o": object, "a": "b"}} self.assertEqual(Context(test_data), Context(test_data)) @@ -165,16 +172,16 @@ class ContextTests(SimpleTestCase): self.assertEqual(a, b) # update only a - a.update({'a': 1}) + a.update({"a": 1}) self.assertNotEqual(a, b) # update both to check regression - a.update({'c': 3}) - b.update({'c': 3}) + a.update({"c": 3}) + b.update({"c": 3}) self.assertNotEqual(a, b) # make contexts equals again - b.update({'a': 1}) + b.update({"a": 1}) self.assertEqual(a, b) def test_copy_request_context_twice(self): @@ -184,35 +191,35 @@ class ContextTests(SimpleTestCase): RequestContext(HttpRequest()).new().new() def test_set_upward(self): - c = Context({'a': 1}) - c.set_upward('a', 2) - self.assertEqual(c.get('a'), 2) + c = Context({"a": 1}) + c.set_upward("a", 2) + self.assertEqual(c.get("a"), 2) def test_set_upward_empty_context(self): empty_context = Context() - empty_context.set_upward('a', 1) - self.assertEqual(empty_context.get('a'), 1) + empty_context.set_upward("a", 1) + self.assertEqual(empty_context.get("a"), 1) def test_set_upward_with_push(self): """ The highest context which has the given key is used. """ - c = Context({'a': 1}) - c.push({'a': 2}) - c.set_upward('a', 3) - self.assertEqual(c.get('a'), 3) + c = Context({"a": 1}) + c.push({"a": 2}) + c.set_upward("a", 3) + self.assertEqual(c.get("a"), 3) c.pop() - self.assertEqual(c.get('a'), 1) + self.assertEqual(c.get("a"), 1) def test_set_upward_with_push_no_match(self): """ The highest context is used if the given key isn't found. """ - c = Context({'b': 1}) - c.push({'b': 2}) - c.set_upward('a', 2) + c = Context({"b": 1}) + c.push({"b": 2}) + c.set_upward("a", 2) self.assertEqual(len(c.dicts), 3) - self.assertEqual(c.dicts[-1]['a'], 2) + self.assertEqual(c.dicts[-1]["a"], 2) class RequestContextTests(SimpleTestCase): @@ -223,19 +230,28 @@ class RequestContextTests(SimpleTestCase): #15721 -- ``{% include %}`` and ``RequestContext`` should work together. """ - engine = Engine(loaders=[ - ('django.template.loaders.locmem.Loader', { - 'child': '{{ var|default:"none" }}', - }), - ]) - request = self.request_factory.get('/') - ctx = RequestContext(request, {'var': 'parent'}) - self.assertEqual(engine.from_string('{% include "child" %}').render(ctx), 'parent') - self.assertEqual(engine.from_string('{% include "child" only %}').render(ctx), 'none') + engine = Engine( + loaders=[ + ( + "django.template.loaders.locmem.Loader", + { + "child": '{{ var|default:"none" }}', + }, + ), + ] + ) + request = self.request_factory.get("/") + ctx = RequestContext(request, {"var": "parent"}) + self.assertEqual( + engine.from_string('{% include "child" %}').render(ctx), "parent" + ) + self.assertEqual( + engine.from_string('{% include "child" only %}').render(ctx), "none" + ) def test_stack_size(self): """Optimized RequestContext construction (#7116).""" - request = self.request_factory.get('/') + request = self.request_factory.get("/") ctx = RequestContext(request, {}) # The stack contains 4 items: # [builtins, supplied context, context processor, empty dict] @@ -243,11 +259,11 @@ class RequestContextTests(SimpleTestCase): def test_context_comparable(self): # Create an engine without any context processors. - test_data = {'x': 'y', 'v': 'z', 'd': {'o': object, 'a': 'b'}} + test_data = {"x": "y", "v": "z", "d": {"o": object, "a": "b"}} # test comparing RequestContext to prevent problems if somebody # adds __eq__ in the future - request = self.request_factory.get('/') + request = self.request_factory.get("/") self.assertEqual( RequestContext(request, dict_=test_data), @@ -255,8 +271,8 @@ class RequestContextTests(SimpleTestCase): ) def test_modify_context_and_render(self): - template = Template('{{ foo }}') - request = self.request_factory.get('/') + template = Template("{{ foo }}") + request = self.request_factory.get("/") context = RequestContext(request, {}) - context['foo'] = 'foo' - self.assertEqual(template.render(context), 'foo') + context["foo"] = "foo" + self.assertEqual(template.render(context), "foo") diff --git a/tests/template_tests/test_custom.py b/tests/template_tests/test_custom.py index 59f83d80e2..acfb6890a5 100644 --- a/tests/template_tests/test_custom.py +++ b/tests/template_tests/test_custom.py @@ -10,29 +10,28 @@ from .templatetags import custom, inclusion from .utils import ROOT LIBRARIES = { - 'custom': 'template_tests.templatetags.custom', - 'inclusion': 'template_tests.templatetags.inclusion', + "custom": "template_tests.templatetags.custom", + "inclusion": "template_tests.templatetags.inclusion", } class CustomFilterTests(SimpleTestCase): - def test_filter(self): engine = Engine(libraries=LIBRARIES) t = engine.from_string("{% load custom %}{{ string|trim:5 }}") self.assertEqual( - t.render(Context({"string": "abcdefghijklmnopqrstuvwxyz"})), - "abcde" + t.render(Context({"string": "abcdefghijklmnopqrstuvwxyz"})), "abcde" ) def test_decorated_filter(self): engine = Engine(libraries=LIBRARIES) - t = engine.from_string('{% load custom %}{{ name|make_data_div }}') - self.assertEqual(t.render(Context({'name': 'foo'})), '<div data-name="foo"></div>') + t = engine.from_string("{% load custom %}{{ name|make_data_div }}") + self.assertEqual( + t.render(Context({"name": "foo"})), '<div data-name="foo"></div>' + ) class TagTestCase(SimpleTestCase): - @classmethod def setUpClass(cls): cls.engine = Engine(app_dirs=True, libraries=LIBRARIES) @@ -40,47 +39,81 @@ class TagTestCase(SimpleTestCase): def verify_tag(self, tag, name): self.assertEqual(tag.__name__, name) - self.assertEqual(tag.__doc__, 'Expected %s __doc__' % name) - self.assertEqual(tag.__dict__['anything'], 'Expected %s __dict__' % name) + self.assertEqual(tag.__doc__, "Expected %s __doc__" % name) + self.assertEqual(tag.__dict__["anything"], "Expected %s __dict__" % name) class SimpleTagTests(TagTestCase): - def test_simple_tags(self): - c = Context({'value': 42}) + c = Context({"value": 42}) templates = [ - ('{% load custom %}{% no_params %}', 'no_params - Expected result'), - ('{% load custom %}{% one_param 37 %}', 'one_param - Expected result: 37'), - ('{% load custom %}{% explicit_no_context 37 %}', 'explicit_no_context - Expected result: 37'), - ('{% load custom %}{% no_params_with_context %}', - 'no_params_with_context - Expected result (context value: 42)'), - ('{% load custom %}{% params_and_context 37 %}', - 'params_and_context - Expected result (context value: 42): 37'), - ('{% load custom %}{% simple_two_params 37 42 %}', 'simple_two_params - Expected result: 37, 42'), - ('{% load custom %}{% simple_keyword_only_param kwarg=37 %}', - 'simple_keyword_only_param - Expected result: 37'), - ('{% load custom %}{% simple_keyword_only_default %}', - 'simple_keyword_only_default - Expected result: 42'), + ("{% load custom %}{% no_params %}", "no_params - Expected result"), + ("{% load custom %}{% one_param 37 %}", "one_param - Expected result: 37"), + ( + "{% load custom %}{% explicit_no_context 37 %}", + "explicit_no_context - Expected result: 37", + ), + ( + "{% load custom %}{% no_params_with_context %}", + "no_params_with_context - Expected result (context value: 42)", + ), + ( + "{% load custom %}{% params_and_context 37 %}", + "params_and_context - Expected result (context value: 42): 37", + ), + ( + "{% load custom %}{% simple_two_params 37 42 %}", + "simple_two_params - Expected result: 37, 42", + ), + ( + "{% load custom %}{% simple_keyword_only_param kwarg=37 %}", + "simple_keyword_only_param - Expected result: 37", + ), + ( + "{% load custom %}{% simple_keyword_only_default %}", + "simple_keyword_only_default - Expected result: 42", + ), + ( + "{% load custom %}{% simple_keyword_only_default kwarg=37 %}", + "simple_keyword_only_default - Expected result: 37", + ), + ( + "{% load custom %}{% simple_one_default 37 %}", + "simple_one_default - Expected result: 37, hi", + ), + ( + '{% load custom %}{% simple_one_default 37 two="hello" %}', + "simple_one_default - Expected result: 37, hello", + ), + ( + '{% load custom %}{% simple_one_default one=99 two="hello" %}', + "simple_one_default - Expected result: 99, hello", + ), + ( + "{% load custom %}{% simple_one_default 37 42 %}", + "simple_one_default - Expected result: 37, 42", + ), + ( + "{% load custom %}{% simple_unlimited_args 37 %}", + "simple_unlimited_args - Expected result: 37, hi", + ), + ( + "{% load custom %}{% simple_unlimited_args 37 42 56 89 %}", + "simple_unlimited_args - Expected result: 37, 42, 56, 89", + ), + ( + "{% load custom %}{% simple_only_unlimited_args %}", + "simple_only_unlimited_args - Expected result: ", + ), ( - '{% load custom %}{% simple_keyword_only_default kwarg=37 %}', - 'simple_keyword_only_default - Expected result: 37', + "{% load custom %}{% simple_only_unlimited_args 37 42 56 89 %}", + "simple_only_unlimited_args - Expected result: 37, 42, 56, 89", + ), + ( + '{% load custom %}{% simple_unlimited_args_kwargs 37 40|add:2 56 eggs="scrambled" four=1|add:3 %}', + "simple_unlimited_args_kwargs - Expected result: 37, 42, 56 / eggs=scrambled, four=4", ), - ('{% load custom %}{% simple_one_default 37 %}', 'simple_one_default - Expected result: 37, hi'), - ('{% load custom %}{% simple_one_default 37 two="hello" %}', - 'simple_one_default - Expected result: 37, hello'), - ('{% load custom %}{% simple_one_default one=99 two="hello" %}', - 'simple_one_default - Expected result: 99, hello'), - ('{% load custom %}{% simple_one_default 37 42 %}', - 'simple_one_default - Expected result: 37, 42'), - ('{% load custom %}{% simple_unlimited_args 37 %}', 'simple_unlimited_args - Expected result: 37, hi'), - ('{% load custom %}{% simple_unlimited_args 37 42 56 89 %}', - 'simple_unlimited_args - Expected result: 37, 42, 56, 89'), - ('{% load custom %}{% simple_only_unlimited_args %}', 'simple_only_unlimited_args - Expected result: '), - ('{% load custom %}{% simple_only_unlimited_args 37 42 56 89 %}', - 'simple_only_unlimited_args - Expected result: 37, 42, 56, 89'), - ('{% load custom %}{% simple_unlimited_args_kwargs 37 40|add:2 56 eggs="scrambled" four=1|add:3 %}', - 'simple_unlimited_args_kwargs - Expected result: 37, 42, 56 / eggs=scrambled, four=4'), ] for entry in templates: @@ -88,34 +121,48 @@ class SimpleTagTests(TagTestCase): self.assertEqual(t.render(c), entry[1]) for entry in templates: - t = self.engine.from_string("%s as var %%}Result: {{ var }}" % entry[0][0:-2]) + t = self.engine.from_string( + "%s as var %%}Result: {{ var }}" % entry[0][0:-2] + ) self.assertEqual(t.render(c), "Result: %s" % entry[1]) def test_simple_tag_errors(self): errors = [ - ("'simple_one_default' received unexpected keyword argument 'three'", - '{% load custom %}{% simple_one_default 99 two="hello" three="foo" %}'), - ("'simple_two_params' received too many positional arguments", - '{% load custom %}{% simple_two_params 37 42 56 %}'), - ("'simple_one_default' received too many positional arguments", - '{% load custom %}{% simple_one_default 37 42 56 %}'), - ("'simple_keyword_only_param' did not receive value(s) for the argument(s): 'kwarg'", - '{% load custom %}{% simple_keyword_only_param %}'), + ( + "'simple_one_default' received unexpected keyword argument 'three'", + '{% load custom %}{% simple_one_default 99 two="hello" three="foo" %}', + ), + ( + "'simple_two_params' received too many positional arguments", + "{% load custom %}{% simple_two_params 37 42 56 %}", + ), + ( + "'simple_one_default' received too many positional arguments", + "{% load custom %}{% simple_one_default 37 42 56 %}", + ), + ( + "'simple_keyword_only_param' did not receive value(s) for the argument(s): 'kwarg'", + "{% load custom %}{% simple_keyword_only_param %}", + ), ( "'simple_keyword_only_param' received multiple values for " "keyword argument 'kwarg'", - '{% load custom %}{% simple_keyword_only_param kwarg=42 kwarg=37 %}', + "{% load custom %}{% simple_keyword_only_param kwarg=42 kwarg=37 %}", ), ( "'simple_keyword_only_default' received multiple values for " "keyword argument 'kwarg'", - '{% load custom %}{% simple_keyword_only_default kwarg=42 ' - 'kwarg=37 %}', + "{% load custom %}{% simple_keyword_only_default kwarg=42 " + "kwarg=37 %}", + ), + ( + "'simple_unlimited_args_kwargs' received some positional argument(s) after some keyword argument(s)", + '{% load custom %}{% simple_unlimited_args_kwargs 37 40|add:2 eggs="scrambled" 56 four=1|add:3 %}', + ), + ( + "'simple_unlimited_args_kwargs' received multiple values for keyword argument 'eggs'", + '{% load custom %}{% simple_unlimited_args_kwargs 37 eggs="scrambled" eggs="scrambled" %}', ), - ("'simple_unlimited_args_kwargs' received some positional argument(s) after some keyword argument(s)", - '{% load custom %}{% simple_unlimited_args_kwargs 37 40|add:2 eggs="scrambled" 56 four=1|add:3 %}'), - ("'simple_unlimited_args_kwargs' received multiple values for keyword argument 'eggs'", - '{% load custom %}{% simple_unlimited_args_kwargs 37 eggs="scrambled" eggs="scrambled" %}'), ] for entry in errors: @@ -127,37 +174,42 @@ class SimpleTagTests(TagTestCase): self.engine.from_string("%s as var %%}" % entry[1][0:-2]) def test_simple_tag_escaping_autoescape_off(self): - c = Context({'name': "Jack & Jill"}, autoescape=False) + c = Context({"name": "Jack & Jill"}, autoescape=False) t = self.engine.from_string("{% load custom %}{% escape_naive %}") self.assertEqual(t.render(c), "Hello Jack & Jill!") def test_simple_tag_naive_escaping(self): - c = Context({'name': "Jack & Jill"}) + c = Context({"name": "Jack & Jill"}) t = self.engine.from_string("{% load custom %}{% escape_naive %}") self.assertEqual(t.render(c), "Hello Jack & Jill!") def test_simple_tag_explicit_escaping(self): # Check we don't double escape - c = Context({'name': "Jack & Jill"}) + c = Context({"name": "Jack & Jill"}) t = self.engine.from_string("{% load custom %}{% escape_explicit %}") self.assertEqual(t.render(c), "Hello Jack & Jill!") def test_simple_tag_format_html_escaping(self): # Check we don't double escape - c = Context({'name': "Jack & Jill"}) + c = Context({"name": "Jack & Jill"}) t = self.engine.from_string("{% load custom %}{% escape_format_html %}") self.assertEqual(t.render(c), "Hello Jack & Jill!") def test_simple_tag_registration(self): # The decorators preserve the decorated function's docstring, name, # and attributes. - self.verify_tag(custom.no_params, 'no_params') - self.verify_tag(custom.one_param, 'one_param') - self.verify_tag(custom.explicit_no_context, 'explicit_no_context') - self.verify_tag(custom.no_params_with_context, 'no_params_with_context') - self.verify_tag(custom.params_and_context, 'params_and_context') - self.verify_tag(custom.simple_unlimited_args_kwargs, 'simple_unlimited_args_kwargs') - self.verify_tag(custom.simple_tag_without_context_parameter, 'simple_tag_without_context_parameter') + self.verify_tag(custom.no_params, "no_params") + self.verify_tag(custom.one_param, "one_param") + self.verify_tag(custom.explicit_no_context, "explicit_no_context") + self.verify_tag(custom.no_params_with_context, "no_params_with_context") + self.verify_tag(custom.params_and_context, "params_and_context") + self.verify_tag( + custom.simple_unlimited_args_kwargs, "simple_unlimited_args_kwargs" + ) + self.verify_tag( + custom.simple_tag_without_context_parameter, + "simple_tag_without_context_parameter", + ) def test_simple_tag_missing_context(self): # The 'context' parameter must be present when takes_context is True @@ -166,7 +218,9 @@ class SimpleTagTests(TagTestCase): "takes_context=True so it must have a first argument of 'context'" ) with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.from_string('{% load custom %}{% simple_tag_without_context_parameter 123 %}') + self.engine.from_string( + "{% load custom %}{% simple_tag_without_context_parameter 123 %}" + ) def test_simple_tag_missing_context_no_params(self): msg = ( @@ -175,50 +229,79 @@ class SimpleTagTests(TagTestCase): ) with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.from_string( - '{% load custom %}{% simple_tag_takes_context_without_params %}' + "{% load custom %}{% simple_tag_takes_context_without_params %}" ) class InclusionTagTests(TagTestCase): - def test_inclusion_tags(self): - c = Context({'value': 42}) + c = Context({"value": 42}) templates = [ - ('{% load inclusion %}{% inclusion_no_params %}', 'inclusion_no_params - Expected result\n'), - ('{% load inclusion %}{% inclusion_one_param 37 %}', 'inclusion_one_param - Expected result: 37\n'), - ('{% load inclusion %}{% inclusion_explicit_no_context 37 %}', - 'inclusion_explicit_no_context - Expected result: 37\n'), - ('{% load inclusion %}{% inclusion_no_params_with_context %}', - 'inclusion_no_params_with_context - Expected result (context value: 42)\n'), - ('{% load inclusion %}{% inclusion_params_and_context 37 %}', - 'inclusion_params_and_context - Expected result (context value: 42): 37\n'), - ('{% load inclusion %}{% inclusion_two_params 37 42 %}', - 'inclusion_two_params - Expected result: 37, 42\n'), ( - '{% load inclusion %}{% inclusion_one_default 37 %}', - 'inclusion_one_default - Expected result: 37, hi\n' + "{% load inclusion %}{% inclusion_no_params %}", + "inclusion_no_params - Expected result\n", + ), + ( + "{% load inclusion %}{% inclusion_one_param 37 %}", + "inclusion_one_param - Expected result: 37\n", + ), + ( + "{% load inclusion %}{% inclusion_explicit_no_context 37 %}", + "inclusion_explicit_no_context - Expected result: 37\n", + ), + ( + "{% load inclusion %}{% inclusion_no_params_with_context %}", + "inclusion_no_params_with_context - Expected result (context value: 42)\n", + ), + ( + "{% load inclusion %}{% inclusion_params_and_context 37 %}", + "inclusion_params_and_context - Expected result (context value: 42): 37\n", + ), + ( + "{% load inclusion %}{% inclusion_two_params 37 42 %}", + "inclusion_two_params - Expected result: 37, 42\n", + ), + ( + "{% load inclusion %}{% inclusion_one_default 37 %}", + "inclusion_one_default - Expected result: 37, hi\n", ), - ('{% load inclusion %}{% inclusion_one_default 37 two="hello" %}', - 'inclusion_one_default - Expected result: 37, hello\n'), - ('{% load inclusion %}{% inclusion_one_default one=99 two="hello" %}', - 'inclusion_one_default - Expected result: 99, hello\n'), - ('{% load inclusion %}{% inclusion_one_default 37 42 %}', - 'inclusion_one_default - Expected result: 37, 42\n'), ( - '{% load inclusion %}{% inclusion_keyword_only_default kwarg=37 %}', - 'inclusion_keyword_only_default - Expected result: 37\n', + '{% load inclusion %}{% inclusion_one_default 37 two="hello" %}', + "inclusion_one_default - Expected result: 37, hello\n", + ), + ( + '{% load inclusion %}{% inclusion_one_default one=99 two="hello" %}', + "inclusion_one_default - Expected result: 99, hello\n", + ), + ( + "{% load inclusion %}{% inclusion_one_default 37 42 %}", + "inclusion_one_default - Expected result: 37, 42\n", + ), + ( + "{% load inclusion %}{% inclusion_keyword_only_default kwarg=37 %}", + "inclusion_keyword_only_default - Expected result: 37\n", + ), + ( + "{% load inclusion %}{% inclusion_unlimited_args 37 %}", + "inclusion_unlimited_args - Expected result: 37, hi\n", + ), + ( + "{% load inclusion %}{% inclusion_unlimited_args 37 42 56 89 %}", + "inclusion_unlimited_args - Expected result: 37, 42, 56, 89\n", + ), + ( + "{% load inclusion %}{% inclusion_only_unlimited_args %}", + "inclusion_only_unlimited_args - Expected result: \n", + ), + ( + "{% load inclusion %}{% inclusion_only_unlimited_args 37 42 56 89 %}", + "inclusion_only_unlimited_args - Expected result: 37, 42, 56, 89\n", + ), + ( + '{% load inclusion %}{% inclusion_unlimited_args_kwargs 37 40|add:2 56 eggs="scrambled" four=1|add:3 %}', + "inclusion_unlimited_args_kwargs - Expected result: 37, 42, 56 / eggs=scrambled, four=4\n", ), - ('{% load inclusion %}{% inclusion_unlimited_args 37 %}', - 'inclusion_unlimited_args - Expected result: 37, hi\n'), - ('{% load inclusion %}{% inclusion_unlimited_args 37 42 56 89 %}', - 'inclusion_unlimited_args - Expected result: 37, 42, 56, 89\n'), - ('{% load inclusion %}{% inclusion_only_unlimited_args %}', - 'inclusion_only_unlimited_args - Expected result: \n'), - ('{% load inclusion %}{% inclusion_only_unlimited_args 37 42 56 89 %}', - 'inclusion_only_unlimited_args - Expected result: 37, 42, 56, 89\n'), - ('{% load inclusion %}{% inclusion_unlimited_args_kwargs 37 40|add:2 56 eggs="scrambled" four=1|add:3 %}', - 'inclusion_unlimited_args_kwargs - Expected result: 37, 42, 56 / eggs=scrambled, four=4\n'), ] for entry in templates: @@ -227,29 +310,41 @@ class InclusionTagTests(TagTestCase): def test_inclusion_tag_errors(self): errors = [ - ("'inclusion_one_default' received unexpected keyword argument 'three'", - '{% load inclusion %}{% inclusion_one_default 99 two="hello" three="foo" %}'), - ("'inclusion_two_params' received too many positional arguments", - '{% load inclusion %}{% inclusion_two_params 37 42 56 %}'), - ("'inclusion_one_default' received too many positional arguments", - '{% load inclusion %}{% inclusion_one_default 37 42 56 %}'), - ("'inclusion_one_default' did not receive value(s) for the argument(s): 'one'", - '{% load inclusion %}{% inclusion_one_default %}'), + ( + "'inclusion_one_default' received unexpected keyword argument 'three'", + '{% load inclusion %}{% inclusion_one_default 99 two="hello" three="foo" %}', + ), + ( + "'inclusion_two_params' received too many positional arguments", + "{% load inclusion %}{% inclusion_two_params 37 42 56 %}", + ), + ( + "'inclusion_one_default' received too many positional arguments", + "{% load inclusion %}{% inclusion_one_default 37 42 56 %}", + ), + ( + "'inclusion_one_default' did not receive value(s) for the argument(s): 'one'", + "{% load inclusion %}{% inclusion_one_default %}", + ), ( "'inclusion_keyword_only_default' received multiple values " "for keyword argument 'kwarg'", - '{% load inclusion %}{% inclusion_keyword_only_default ' - 'kwarg=37 kwarg=42 %}', + "{% load inclusion %}{% inclusion_keyword_only_default " + "kwarg=37 kwarg=42 %}", + ), + ( + "'inclusion_unlimited_args' did not receive value(s) for the argument(s): 'one'", + "{% load inclusion %}{% inclusion_unlimited_args %}", ), - ("'inclusion_unlimited_args' did not receive value(s) for the argument(s): 'one'", - '{% load inclusion %}{% inclusion_unlimited_args %}'), ( "'inclusion_unlimited_args_kwargs' received some positional argument(s) " "after some keyword argument(s)", '{% load inclusion %}{% inclusion_unlimited_args_kwargs 37 40|add:2 eggs="boiled" 56 four=1|add:3 %}', ), - ("'inclusion_unlimited_args_kwargs' received multiple values for keyword argument 'eggs'", - '{% load inclusion %}{% inclusion_unlimited_args_kwargs 37 eggs="scrambled" eggs="scrambled" %}'), + ( + "'inclusion_unlimited_args_kwargs' received multiple values for keyword argument 'eggs'", + '{% load inclusion %}{% inclusion_unlimited_args_kwargs 37 eggs="scrambled" eggs="scrambled" %}', + ), ] for entry in errors: @@ -263,7 +358,9 @@ class InclusionTagTests(TagTestCase): "takes_context=True so it must have a first argument of 'context'" ) with self.assertRaisesMessage(TemplateSyntaxError, msg): - self.engine.from_string('{% load inclusion %}{% inclusion_tag_without_context_parameter 123 %}') + self.engine.from_string( + "{% load inclusion %}{% inclusion_tag_without_context_parameter 123 %}" + ) def test_include_tag_missing_context_no_params(self): msg = ( @@ -272,37 +369,61 @@ class InclusionTagTests(TagTestCase): ) with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.from_string( - '{% load inclusion %}{% inclusion_tag_takes_context_without_params %}' + "{% load inclusion %}{% inclusion_tag_takes_context_without_params %}" ) def test_inclusion_tags_from_template(self): - c = Context({'value': 42}) + c = Context({"value": 42}) templates = [ - ('{% load inclusion %}{% inclusion_no_params_from_template %}', - 'inclusion_no_params_from_template - Expected result\n'), - ('{% load inclusion %}{% inclusion_one_param_from_template 37 %}', - 'inclusion_one_param_from_template - Expected result: 37\n'), - ('{% load inclusion %}{% inclusion_explicit_no_context_from_template 37 %}', - 'inclusion_explicit_no_context_from_template - Expected result: 37\n'), - ('{% load inclusion %}{% inclusion_no_params_with_context_from_template %}', - 'inclusion_no_params_with_context_from_template - Expected result (context value: 42)\n'), - ('{% load inclusion %}{% inclusion_params_and_context_from_template 37 %}', - 'inclusion_params_and_context_from_template - Expected result (context value: 42): 37\n'), - ('{% load inclusion %}{% inclusion_two_params_from_template 37 42 %}', - 'inclusion_two_params_from_template - Expected result: 37, 42\n'), - ('{% load inclusion %}{% inclusion_one_default_from_template 37 %}', - 'inclusion_one_default_from_template - Expected result: 37, hi\n'), - ('{% load inclusion %}{% inclusion_one_default_from_template 37 42 %}', - 'inclusion_one_default_from_template - Expected result: 37, 42\n'), - ('{% load inclusion %}{% inclusion_unlimited_args_from_template 37 %}', - 'inclusion_unlimited_args_from_template - Expected result: 37, hi\n'), - ('{% load inclusion %}{% inclusion_unlimited_args_from_template 37 42 56 89 %}', - 'inclusion_unlimited_args_from_template - Expected result: 37, 42, 56, 89\n'), - ('{% load inclusion %}{% inclusion_only_unlimited_args_from_template %}', - 'inclusion_only_unlimited_args_from_template - Expected result: \n'), - ('{% load inclusion %}{% inclusion_only_unlimited_args_from_template 37 42 56 89 %}', - 'inclusion_only_unlimited_args_from_template - Expected result: 37, 42, 56, 89\n'), + ( + "{% load inclusion %}{% inclusion_no_params_from_template %}", + "inclusion_no_params_from_template - Expected result\n", + ), + ( + "{% load inclusion %}{% inclusion_one_param_from_template 37 %}", + "inclusion_one_param_from_template - Expected result: 37\n", + ), + ( + "{% load inclusion %}{% inclusion_explicit_no_context_from_template 37 %}", + "inclusion_explicit_no_context_from_template - Expected result: 37\n", + ), + ( + "{% load inclusion %}{% inclusion_no_params_with_context_from_template %}", + "inclusion_no_params_with_context_from_template - Expected result (context value: 42)\n", + ), + ( + "{% load inclusion %}{% inclusion_params_and_context_from_template 37 %}", + "inclusion_params_and_context_from_template - Expected result (context value: 42): 37\n", + ), + ( + "{% load inclusion %}{% inclusion_two_params_from_template 37 42 %}", + "inclusion_two_params_from_template - Expected result: 37, 42\n", + ), + ( + "{% load inclusion %}{% inclusion_one_default_from_template 37 %}", + "inclusion_one_default_from_template - Expected result: 37, hi\n", + ), + ( + "{% load inclusion %}{% inclusion_one_default_from_template 37 42 %}", + "inclusion_one_default_from_template - Expected result: 37, 42\n", + ), + ( + "{% load inclusion %}{% inclusion_unlimited_args_from_template 37 %}", + "inclusion_unlimited_args_from_template - Expected result: 37, hi\n", + ), + ( + "{% load inclusion %}{% inclusion_unlimited_args_from_template 37 42 56 89 %}", + "inclusion_unlimited_args_from_template - Expected result: 37, 42, 56, 89\n", + ), + ( + "{% load inclusion %}{% inclusion_only_unlimited_args_from_template %}", + "inclusion_only_unlimited_args_from_template - Expected result: \n", + ), + ( + "{% load inclusion %}{% inclusion_only_unlimited_args_from_template 37 42 56 89 %}", + "inclusion_only_unlimited_args_from_template - Expected result: 37, 42, 56, 89\n", + ), ] for entry in templates: @@ -312,18 +433,32 @@ class InclusionTagTests(TagTestCase): def test_inclusion_tag_registration(self): # The decorators preserve the decorated function's docstring, name, # and attributes. - self.verify_tag(inclusion.inclusion_no_params, 'inclusion_no_params') - self.verify_tag(inclusion.inclusion_one_param, 'inclusion_one_param') - self.verify_tag(inclusion.inclusion_explicit_no_context, 'inclusion_explicit_no_context') - self.verify_tag(inclusion.inclusion_no_params_with_context, 'inclusion_no_params_with_context') - self.verify_tag(inclusion.inclusion_params_and_context, 'inclusion_params_and_context') - self.verify_tag(inclusion.inclusion_two_params, 'inclusion_two_params') - self.verify_tag(inclusion.inclusion_one_default, 'inclusion_one_default') - self.verify_tag(inclusion.inclusion_unlimited_args, 'inclusion_unlimited_args') - self.verify_tag(inclusion.inclusion_only_unlimited_args, 'inclusion_only_unlimited_args') - self.verify_tag(inclusion.inclusion_tag_without_context_parameter, 'inclusion_tag_without_context_parameter') - self.verify_tag(inclusion.inclusion_tag_use_l10n, 'inclusion_tag_use_l10n') - self.verify_tag(inclusion.inclusion_unlimited_args_kwargs, 'inclusion_unlimited_args_kwargs') + self.verify_tag(inclusion.inclusion_no_params, "inclusion_no_params") + self.verify_tag(inclusion.inclusion_one_param, "inclusion_one_param") + self.verify_tag( + inclusion.inclusion_explicit_no_context, "inclusion_explicit_no_context" + ) + self.verify_tag( + inclusion.inclusion_no_params_with_context, + "inclusion_no_params_with_context", + ) + self.verify_tag( + inclusion.inclusion_params_and_context, "inclusion_params_and_context" + ) + self.verify_tag(inclusion.inclusion_two_params, "inclusion_two_params") + self.verify_tag(inclusion.inclusion_one_default, "inclusion_one_default") + self.verify_tag(inclusion.inclusion_unlimited_args, "inclusion_unlimited_args") + self.verify_tag( + inclusion.inclusion_only_unlimited_args, "inclusion_only_unlimited_args" + ) + self.verify_tag( + inclusion.inclusion_tag_without_context_parameter, + "inclusion_tag_without_context_parameter", + ) + self.verify_tag(inclusion.inclusion_tag_use_l10n, "inclusion_tag_use_l10n") + self.verify_tag( + inclusion.inclusion_unlimited_args_kwargs, "inclusion_unlimited_args_kwargs" + ) def test_15070_use_l10n(self): """ @@ -331,18 +466,18 @@ class InclusionTagTests(TagTestCase): Context of the included/rendered template as well. """ c = Context({}) - t = self.engine.from_string('{% load inclusion %}{% inclusion_tag_use_l10n %}') - self.assertEqual(t.render(c).strip(), 'None') + t = self.engine.from_string("{% load inclusion %}{% inclusion_tag_use_l10n %}") + self.assertEqual(t.render(c).strip(), "None") c.use_l10n = True - self.assertEqual(t.render(c).strip(), 'True') + self.assertEqual(t.render(c).strip(), "True") def test_no_render_side_effect(self): """ #23441 -- InclusionNode shouldn't modify its nodelist at render time. """ engine = Engine(app_dirs=True, libraries=LIBRARIES) - template = engine.from_string('{% load inclusion %}{% inclusion_no_params %}') + template = engine.from_string("{% load inclusion %}{% inclusion_no_params %}") count = template.nodelist.get_nodes_by_type(Node) template.render(Context({})) self.assertEqual(template.nodelist.get_nodes_by_type(Node), count) @@ -354,15 +489,16 @@ class InclusionTagTests(TagTestCase): extending can interfere with subsequent rendering. """ engine = Engine(app_dirs=True, libraries=LIBRARIES) - template = engine.from_string('{% load inclusion %}{% inclusion_extends1 %}{% inclusion_extends2 %}') - self.assertEqual(template.render(Context({})).strip(), 'one\ntwo') + template = engine.from_string( + "{% load inclusion %}{% inclusion_extends1 %}{% inclusion_extends2 %}" + ) + self.assertEqual(template.render(Context({})).strip(), "one\ntwo") class TemplateTagLoadingTests(SimpleTestCase): - @classmethod def setUpClass(cls): - cls.egg_dir = os.path.join(ROOT, 'eggs') + cls.egg_dir = os.path.join(ROOT, "eggs") super().setUpClass() def test_load_error(self): @@ -372,10 +508,10 @@ class TemplateTagLoadingTests(SimpleTestCase): "'Xtemplate'" ) with self.assertRaisesMessage(InvalidTemplateLibrary, msg): - Engine(libraries={'broken_tag': 'template_tests.broken_tag'}) + Engine(libraries={"broken_tag": "template_tests.broken_tag"}) def test_load_error_egg(self): - egg_name = '%s/tagsegg.egg' % self.egg_dir + egg_name = "%s/tagsegg.egg" % self.egg_dir msg = ( "Invalid template library specified. ImportError raised when " "trying to load 'tagsegg.templatetags.broken_egg': cannot " @@ -383,18 +519,22 @@ class TemplateTagLoadingTests(SimpleTestCase): ) with extend_sys_path(egg_name): with self.assertRaisesMessage(InvalidTemplateLibrary, msg): - Engine(libraries={'broken_egg': 'tagsegg.templatetags.broken_egg'}) + Engine(libraries={"broken_egg": "tagsegg.templatetags.broken_egg"}) def test_load_working_egg(self): ttext = "{% load working_egg %}" - egg_name = '%s/tagsegg.egg' % self.egg_dir + egg_name = "%s/tagsegg.egg" % self.egg_dir with extend_sys_path(egg_name): - engine = Engine(libraries={ - 'working_egg': 'tagsegg.templatetags.working_egg', - }) + engine = Engine( + libraries={ + "working_egg": "tagsegg.templatetags.working_egg", + } + ) engine.from_string(ttext) def test_load_annotated_function(self): - Engine(libraries={ - 'annotated_tag_function': 'template_tests.annotated_tag_function', - }) + Engine( + libraries={ + "annotated_tag_function": "template_tests.annotated_tag_function", + } + ) diff --git a/tests/template_tests/test_engine.py b/tests/template_tests/test_engine.py index 2b32211761..ff725b9880 100644 --- a/tests/template_tests/test_engine.py +++ b/tests/template_tests/test_engine.py @@ -7,7 +7,7 @@ from django.test import SimpleTestCase, override_settings from .utils import ROOT, TEMPLATE_DIR -OTHER_DIR = os.path.join(ROOT, 'other_templates') +OTHER_DIR = os.path.join(ROOT, "other_templates") class EngineTest(SimpleTestCase): @@ -20,18 +20,18 @@ class EngineTest(SimpleTestCase): "['django.template.loaders.filesystem.Loader'])] " "string_if_invalid='' file_charset='utf-8' builtins=[" "'django.template.defaulttags', 'django.template.defaultfilters', " - "'django.template.loader_tags'] autoescape=True>" + "'django.template.loader_tags'] autoescape=True>", ) def test_repr(self): engine = Engine( dirs=[TEMPLATE_DIR], - context_processors=['django.template.context_processors.debug'], + context_processors=["django.template.context_processors.debug"], debug=True, - loaders=['django.template.loaders.filesystem.Loader'], - string_if_invalid='x', - file_charset='utf-16', - libraries={'custom': 'template_tests.templatetags.custom'}, + loaders=["django.template.loaders.filesystem.Loader"], + string_if_invalid="x", + file_charset="utf-16", + libraries={"custom": "template_tests.templatetags.custom"}, autoescape=False, ) self.assertEqual( @@ -43,91 +43,100 @@ class EngineTest(SimpleTestCase): "libraries={'custom': 'template_tests.templatetags.custom'} " "builtins=['django.template.defaulttags', " "'django.template.defaultfilters', 'django.template.loader_tags'] " - "autoescape=False>" + "autoescape=False>", ) class RenderToStringTest(SimpleTestCase): - def setUp(self): self.engine = Engine(dirs=[TEMPLATE_DIR]) def test_basic_context(self): self.assertEqual( - self.engine.render_to_string('test_context.html', {'obj': 'test'}), - 'obj:test\n', + self.engine.render_to_string("test_context.html", {"obj": "test"}), + "obj:test\n", ) def test_autoescape_off(self): engine = Engine(dirs=[TEMPLATE_DIR], autoescape=False) self.assertEqual( - engine.render_to_string('test_context.html', {'obj': '<script>'}), - 'obj:<script>\n', + engine.render_to_string("test_context.html", {"obj": "<script>"}), + "obj:<script>\n", ) class GetDefaultTests(SimpleTestCase): - @override_settings(TEMPLATES=[]) def test_no_engines_configured(self): - msg = 'No DjangoTemplates backend is configured.' + msg = "No DjangoTemplates backend is configured." with self.assertRaisesMessage(ImproperlyConfigured, msg): Engine.get_default() - @override_settings(TEMPLATES=[{ - 'NAME': 'default', - 'BACKEND': 'django.template.backends.django.DjangoTemplates', - 'OPTIONS': {'file_charset': 'abc'}, - }]) + @override_settings( + TEMPLATES=[ + { + "NAME": "default", + "BACKEND": "django.template.backends.django.DjangoTemplates", + "OPTIONS": {"file_charset": "abc"}, + } + ] + ) def test_single_engine_configured(self): - self.assertEqual(Engine.get_default().file_charset, 'abc') + self.assertEqual(Engine.get_default().file_charset, "abc") - @override_settings(TEMPLATES=[{ - 'NAME': 'default', - 'BACKEND': 'django.template.backends.django.DjangoTemplates', - 'OPTIONS': {'file_charset': 'abc'}, - }, { - 'NAME': 'other', - 'BACKEND': 'django.template.backends.django.DjangoTemplates', - 'OPTIONS': {'file_charset': 'def'}, - }]) + @override_settings( + TEMPLATES=[ + { + "NAME": "default", + "BACKEND": "django.template.backends.django.DjangoTemplates", + "OPTIONS": {"file_charset": "abc"}, + }, + { + "NAME": "other", + "BACKEND": "django.template.backends.django.DjangoTemplates", + "OPTIONS": {"file_charset": "def"}, + }, + ] + ) def test_multiple_engines_configured(self): - self.assertEqual(Engine.get_default().file_charset, 'abc') + self.assertEqual(Engine.get_default().file_charset, "abc") class LoaderTests(SimpleTestCase): - def test_origin(self): engine = Engine(dirs=[TEMPLATE_DIR], debug=True) - template = engine.get_template('index.html') - self.assertEqual(template.origin.template_name, 'index.html') + template = engine.get_template("index.html") + self.assertEqual(template.origin.template_name, "index.html") def test_loader_priority(self): """ #21460 -- The order of template loader works. """ loaders = [ - 'django.template.loaders.filesystem.Loader', - 'django.template.loaders.app_directories.Loader', + "django.template.loaders.filesystem.Loader", + "django.template.loaders.app_directories.Loader", ] engine = Engine(dirs=[OTHER_DIR, TEMPLATE_DIR], loaders=loaders) - template = engine.get_template('priority/foo.html') - self.assertEqual(template.render(Context()), 'priority\n') + template = engine.get_template("priority/foo.html") + self.assertEqual(template.render(Context()), "priority\n") def test_cached_loader_priority(self): """ The order of template loader works. Refs #21460. """ loaders = [ - ('django.template.loaders.cached.Loader', [ - 'django.template.loaders.filesystem.Loader', - 'django.template.loaders.app_directories.Loader', - ]), + ( + "django.template.loaders.cached.Loader", + [ + "django.template.loaders.filesystem.Loader", + "django.template.loaders.app_directories.Loader", + ], + ), ] engine = Engine(dirs=[OTHER_DIR, TEMPLATE_DIR], loaders=loaders) - template = engine.get_template('priority/foo.html') - self.assertEqual(template.render(Context()), 'priority\n') + template = engine.get_template("priority/foo.html") + self.assertEqual(template.render(Context()), "priority\n") - template = engine.get_template('priority/foo.html') - self.assertEqual(template.render(Context()), 'priority\n') + template = engine.get_template("priority/foo.html") + self.assertEqual(template.render(Context()), "priority\n") diff --git a/tests/template_tests/test_extends.py b/tests/template_tests/test_extends.py index 38c7ce230f..bce5162d83 100644 --- a/tests/template_tests/test_extends.py +++ b/tests/template_tests/test_extends.py @@ -5,104 +5,116 @@ from django.test import SimpleTestCase from .utils import ROOT -RECURSIVE = os.path.join(ROOT, 'recursive_templates') +RECURSIVE = os.path.join(ROOT, "recursive_templates") class ExtendsBehaviorTests(SimpleTestCase): - def test_normal_extend(self): - engine = Engine(dirs=[os.path.join(RECURSIVE, 'fs')]) - template = engine.get_template('one.html') + engine = Engine(dirs=[os.path.join(RECURSIVE, "fs")]) + template = engine.get_template("one.html") output = template.render(Context({})) - self.assertEqual(output.strip(), 'three two one') + self.assertEqual(output.strip(), "three two one") def test_extend_recursive(self): - engine = Engine(dirs=[ - os.path.join(RECURSIVE, 'fs'), - os.path.join(RECURSIVE, 'fs2'), - os.path.join(RECURSIVE, 'fs3'), - ]) - template = engine.get_template('recursive.html') + engine = Engine( + dirs=[ + os.path.join(RECURSIVE, "fs"), + os.path.join(RECURSIVE, "fs2"), + os.path.join(RECURSIVE, "fs3"), + ] + ) + template = engine.get_template("recursive.html") output = template.render(Context({})) - self.assertEqual(output.strip(), 'fs3/recursive fs2/recursive fs/recursive') + self.assertEqual(output.strip(), "fs3/recursive fs2/recursive fs/recursive") def test_extend_missing(self): - engine = Engine(dirs=[os.path.join(RECURSIVE, 'fs')]) - template = engine.get_template('extend-missing.html') + engine = Engine(dirs=[os.path.join(RECURSIVE, "fs")]) + template = engine.get_template("extend-missing.html") with self.assertRaises(TemplateDoesNotExist) as e: template.render(Context({})) tried = e.exception.tried self.assertEqual(len(tried), 1) - self.assertEqual(tried[0][0].template_name, 'missing.html') + self.assertEqual(tried[0][0].template_name, "missing.html") def test_recursive_multiple_loaders(self): engine = Engine( - dirs=[os.path.join(RECURSIVE, 'fs')], - loaders=[( - 'django.template.loaders.locmem.Loader', { - 'one.html': ( - '{% extends "one.html" %}{% block content %}{{ block.super }} locmem-one{% endblock %}' - ), - 'two.html': ( - '{% extends "two.html" %}{% block content %}{{ block.super }} locmem-two{% endblock %}' - ), - 'three.html': ( - '{% extends "three.html" %}{% block content %}{{ block.super }} locmem-three{% endblock %}' - ), - } - ), 'django.template.loaders.filesystem.Loader'], + dirs=[os.path.join(RECURSIVE, "fs")], + loaders=[ + ( + "django.template.loaders.locmem.Loader", + { + "one.html": ( + '{% extends "one.html" %}{% block content %}{{ block.super }} locmem-one{% endblock %}' + ), + "two.html": ( + '{% extends "two.html" %}{% block content %}{{ block.super }} locmem-two{% endblock %}' + ), + "three.html": ( + '{% extends "three.html" %}{% block content %}{{ block.super }} locmem-three{% endblock %}' + ), + }, + ), + "django.template.loaders.filesystem.Loader", + ], ) - template = engine.get_template('one.html') + template = engine.get_template("one.html") output = template.render(Context({})) - self.assertEqual(output.strip(), 'three locmem-three two locmem-two one locmem-one') + self.assertEqual( + output.strip(), "three locmem-three two locmem-two one locmem-one" + ) def test_extend_self_error(self): """ Catch if a template extends itself and no other matching templates are found. """ - engine = Engine(dirs=[os.path.join(RECURSIVE, 'fs')]) - template = engine.get_template('self.html') + engine = Engine(dirs=[os.path.join(RECURSIVE, "fs")]) + template = engine.get_template("self.html") with self.assertRaises(TemplateDoesNotExist) as e: template.render(Context({})) tried = e.exception.tried self.assertEqual(len(tried), 1) origin, message = tried[0] - self.assertEqual(origin.template_name, 'self.html') - self.assertEqual(message, 'Skipped to avoid recursion') + self.assertEqual(origin.template_name, "self.html") + self.assertEqual(message, "Skipped to avoid recursion") def test_extend_cached(self): engine = Engine( dirs=[ - os.path.join(RECURSIVE, 'fs'), - os.path.join(RECURSIVE, 'fs2'), - os.path.join(RECURSIVE, 'fs3'), + os.path.join(RECURSIVE, "fs"), + os.path.join(RECURSIVE, "fs2"), + os.path.join(RECURSIVE, "fs3"), ], loaders=[ - ('django.template.loaders.cached.Loader', [ - 'django.template.loaders.filesystem.Loader', - ]), + ( + "django.template.loaders.cached.Loader", + [ + "django.template.loaders.filesystem.Loader", + ], + ), ], ) - template = engine.get_template('recursive.html') + template = engine.get_template("recursive.html") output = template.render(Context({})) - self.assertEqual(output.strip(), 'fs3/recursive fs2/recursive fs/recursive') + self.assertEqual(output.strip(), "fs3/recursive fs2/recursive fs/recursive") cache = engine.template_loaders[0].get_template_cache self.assertEqual(len(cache), 3) - expected_path = os.path.join('fs', 'recursive.html') - self.assertTrue(cache['recursive.html'].origin.name.endswith(expected_path)) + expected_path = os.path.join("fs", "recursive.html") + self.assertTrue(cache["recursive.html"].origin.name.endswith(expected_path)) # Render another path that uses the same templates from the cache - template = engine.get_template('other-recursive.html') + template = engine.get_template("other-recursive.html") output = template.render(Context({})) - self.assertEqual(output.strip(), 'fs3/recursive fs2/recursive fs/recursive') + self.assertEqual(output.strip(), "fs3/recursive fs2/recursive fs/recursive") # Template objects should not be duplicated. self.assertEqual(len(cache), 4) - expected_path = os.path.join('fs', 'other-recursive.html') - self.assertTrue(cache['other-recursive.html'].origin.name.endswith(expected_path)) + expected_path = os.path.join("fs", "other-recursive.html") + self.assertTrue( + cache["other-recursive.html"].origin.name.endswith(expected_path) + ) def test_unique_history_per_loader(self): """ @@ -111,17 +123,23 @@ class ExtendsBehaviorTests(SimpleTestCase): """ engine = Engine( loaders=[ - ['django.template.loaders.locmem.Loader', { - 'base.html': '{% extends "base.html" %}{% block content %}{{ block.super }} loader1{% endblock %}', - }], - ['django.template.loaders.locmem.Loader', { - 'base.html': '{% block content %}loader2{% endblock %}', - }], + [ + "django.template.loaders.locmem.Loader", + { + "base.html": '{% extends "base.html" %}{% block content %}{{ block.super }} loader1{% endblock %}', + }, + ], + [ + "django.template.loaders.locmem.Loader", + { + "base.html": "{% block content %}loader2{% endblock %}", + }, + ], ] ) - template = engine.get_template('base.html') + template = engine.get_template("base.html") output = template.render(Context({})) - self.assertEqual(output.strip(), 'loader2 loader1') + self.assertEqual(output.strip(), "loader2 loader1") def test_block_override_in_extended_included_template(self): """ @@ -130,16 +148,21 @@ class ExtendsBehaviorTests(SimpleTestCase): """ engine = Engine( loaders=[ - ['django.template.loaders.locmem.Loader', { - 'base.html': "{% extends 'base.html' %}{% block base %}{{ block.super }}2{% endblock %}", - 'included.html': - "{% extends 'included.html' %}{% block included %}{{ block.super }}B{% endblock %}", - }], - ['django.template.loaders.locmem.Loader', { - 'base.html': "{% block base %}1{% endblock %}{% include 'included.html' %}", - 'included.html': "{% block included %}A{% endblock %}", - }], + [ + "django.template.loaders.locmem.Loader", + { + "base.html": "{% extends 'base.html' %}{% block base %}{{ block.super }}2{% endblock %}", + "included.html": "{% extends 'included.html' %}{% block included %}{{ block.super }}B{% endblock %}", + }, + ], + [ + "django.template.loaders.locmem.Loader", + { + "base.html": "{% block base %}1{% endblock %}{% include 'included.html' %}", + "included.html": "{% block included %}A{% endblock %}", + }, + ], ], ) - template = engine.get_template('base.html') - self.assertEqual(template.render(Context({})), '12AB') + template = engine.get_template("base.html") + self.assertEqual(template.render(Context({})), "12AB") diff --git a/tests/template_tests/test_extends_relative.py b/tests/template_tests/test_extends_relative.py index 49a7624600..b20b0150d4 100644 --- a/tests/template_tests/test_extends_relative.py +++ b/tests/template_tests/test_extends_relative.py @@ -5,52 +5,51 @@ from django.test import SimpleTestCase from .utils import ROOT -RELATIVE = os.path.join(ROOT, 'relative_templates') +RELATIVE = os.path.join(ROOT, "relative_templates") class ExtendsRelativeBehaviorTests(SimpleTestCase): - def test_normal_extend(self): engine = Engine(dirs=[RELATIVE]) - template = engine.get_template('one.html') + template = engine.get_template("one.html") output = template.render(Context({})) - self.assertEqual(output.strip(), 'three two one') + self.assertEqual(output.strip(), "three two one") def test_normal_extend_variable(self): engine = Engine(dirs=[RELATIVE]) - template = engine.get_template('one_var.html') - output = template.render(Context({'tmpl': './two.html'})) - self.assertEqual(output.strip(), 'three two one') + template = engine.get_template("one_var.html") + output = template.render(Context({"tmpl": "./two.html"})) + self.assertEqual(output.strip(), "three two one") def test_dir1_extend(self): engine = Engine(dirs=[RELATIVE]) - template = engine.get_template('dir1/one.html') + template = engine.get_template("dir1/one.html") output = template.render(Context({})) - self.assertEqual(output.strip(), 'three two one dir1 one') + self.assertEqual(output.strip(), "three two one dir1 one") def test_dir1_extend1(self): engine = Engine(dirs=[RELATIVE]) - template = engine.get_template('dir1/one1.html') + template = engine.get_template("dir1/one1.html") output = template.render(Context({})) - self.assertEqual(output.strip(), 'three two one dir1 one') + self.assertEqual(output.strip(), "three two one dir1 one") def test_dir1_extend2(self): engine = Engine(dirs=[RELATIVE]) - template = engine.get_template('dir1/one2.html') + template = engine.get_template("dir1/one2.html") output = template.render(Context({})) - self.assertEqual(output.strip(), 'three two one dir1 one') + self.assertEqual(output.strip(), "three two one dir1 one") def test_dir1_extend3(self): engine = Engine(dirs=[RELATIVE]) - template = engine.get_template('dir1/one3.html') + template = engine.get_template("dir1/one3.html") output = template.render(Context({})) - self.assertEqual(output.strip(), 'three two one dir1 one') + self.assertEqual(output.strip(), "three two one dir1 one") def test_dir2_extend(self): engine = Engine(dirs=[RELATIVE]) - template = engine.get_template('dir1/dir2/one.html') + template = engine.get_template("dir1/dir2/one.html") output = template.render(Context({})) - self.assertEqual(output.strip(), 'three two one dir2 one') + self.assertEqual(output.strip(), "three two one dir2 one") def test_extend_error(self): engine = Engine(dirs=[RELATIVE]) @@ -59,28 +58,27 @@ class ExtendsRelativeBehaviorTests(SimpleTestCase): "hierarchy that template 'error_extends.html' is in." ) with self.assertRaisesMessage(TemplateSyntaxError, msg): - engine.render_to_string('error_extends.html') + engine.render_to_string("error_extends.html") class IncludeRelativeBehaviorTests(SimpleTestCase): - def test_normal_include(self): engine = Engine(dirs=[RELATIVE]) - template = engine.get_template('dir1/dir2/inc2.html') + template = engine.get_template("dir1/dir2/inc2.html") output = template.render(Context({})) - self.assertEqual(output.strip(), 'dir2 include') + self.assertEqual(output.strip(), "dir2 include") def test_normal_include_variable(self): engine = Engine(dirs=[RELATIVE]) - template = engine.get_template('dir1/dir2/inc3.html') - output = template.render(Context({'tmpl': './include_content.html'})) - self.assertEqual(output.strip(), 'dir2 include') + template = engine.get_template("dir1/dir2/inc3.html") + output = template.render(Context({"tmpl": "./include_content.html"})) + self.assertEqual(output.strip(), "dir2 include") def test_dir2_include(self): engine = Engine(dirs=[RELATIVE]) - template = engine.get_template('dir1/dir2/inc1.html') + template = engine.get_template("dir1/dir2/inc1.html") output = template.render(Context({})) - self.assertEqual(output.strip(), 'three') + self.assertEqual(output.strip(), "three") def test_include_error(self): engine = Engine(dirs=[RELATIVE]) @@ -89,29 +87,28 @@ class IncludeRelativeBehaviorTests(SimpleTestCase): "hierarchy that template 'error_include.html' is in." ) with self.assertRaisesMessage(TemplateSyntaxError, msg): - engine.render_to_string('error_include.html') + engine.render_to_string("error_include.html") class ExtendsMixedBehaviorTests(SimpleTestCase): - def test_mixing1(self): engine = Engine(dirs=[RELATIVE]) - template = engine.get_template('dir1/two.html') + template = engine.get_template("dir1/two.html") output = template.render(Context({})) - self.assertEqual(output.strip(), 'three two one dir2 one dir1 two') + self.assertEqual(output.strip(), "three two one dir2 one dir1 two") def test_mixing2(self): engine = Engine(dirs=[RELATIVE]) - template = engine.get_template('dir1/three.html') + template = engine.get_template("dir1/three.html") output = template.render(Context({})) - self.assertEqual(output.strip(), 'three dir1 three') + self.assertEqual(output.strip(), "three dir1 three") def test_mixing_loop(self): engine = Engine(dirs=[RELATIVE]) msg = ( "The relative path '\"./dir2/../looped.html\"' was translated to " - "template name \'dir1/looped.html\', the same template in which " + "template name 'dir1/looped.html', the same template in which " "the tag appears." ) with self.assertRaisesMessage(TemplateSyntaxError, msg): - engine.render_to_string('dir1/looped.html') + engine.render_to_string("dir1/looped.html") diff --git a/tests/template_tests/test_library.py b/tests/template_tests/test_library.py index 9fdb9b7aa1..7376832879 100644 --- a/tests/template_tests/test_library.py +++ b/tests/template_tests/test_library.py @@ -6,113 +6,121 @@ from django.test import SimpleTestCase class FilterRegistrationTests(SimpleTestCase): - def setUp(self): self.library = Library() def test_filter(self): @self.library.filter def func(): - return '' - self.assertEqual(self.library.filters['func'], func) + return "" + + self.assertEqual(self.library.filters["func"], func) def test_filter_parens(self): @self.library.filter() def func(): - return '' - self.assertEqual(self.library.filters['func'], func) + return "" + + self.assertEqual(self.library.filters["func"], func) def test_filter_name_arg(self): - @self.library.filter('name') + @self.library.filter("name") def func(): - return '' - self.assertEqual(self.library.filters['name'], func) + return "" + + self.assertEqual(self.library.filters["name"], func) def test_filter_name_kwarg(self): - @self.library.filter(name='name') + @self.library.filter(name="name") def func(): - return '' - self.assertEqual(self.library.filters['name'], func) + return "" + + self.assertEqual(self.library.filters["name"], func) def test_filter_call(self): def func(): - return '' - self.library.filter('name', func) - self.assertEqual(self.library.filters['name'], func) + return "" + + self.library.filter("name", func) + self.assertEqual(self.library.filters["name"], func) def test_filter_invalid(self): msg = "Unsupported arguments to Library.filter: (None, '')" with self.assertRaisesMessage(ValueError, msg): - self.library.filter(None, '') + self.library.filter(None, "") class InclusionTagRegistrationTests(SimpleTestCase): - def setUp(self): self.library = Library() def test_inclusion_tag(self): - @self.library.inclusion_tag('template.html') + @self.library.inclusion_tag("template.html") def func(): - return '' - self.assertIn('func', self.library.tags) + return "" + + self.assertIn("func", self.library.tags) def test_inclusion_tag_name(self): - @self.library.inclusion_tag('template.html', name='name') + @self.library.inclusion_tag("template.html", name="name") def func(): - return '' - self.assertIn('name', self.library.tags) + return "" + + self.assertIn("name", self.library.tags) def test_inclusion_tag_wrapped(self): - @self.library.inclusion_tag('template.html') + @self.library.inclusion_tag("template.html") @functools.lru_cache(maxsize=32) def func(): - return '' - func_wrapped = self.library.tags['func'].__wrapped__ + return "" + + func_wrapped = self.library.tags["func"].__wrapped__ self.assertIs(func_wrapped, func) - self.assertTrue(hasattr(func_wrapped, 'cache_info')) + self.assertTrue(hasattr(func_wrapped, "cache_info")) class SimpleTagRegistrationTests(SimpleTestCase): - def setUp(self): self.library = Library() def test_simple_tag(self): @self.library.simple_tag def func(): - return '' - self.assertIn('func', self.library.tags) + return "" + + self.assertIn("func", self.library.tags) def test_simple_tag_parens(self): @self.library.simple_tag() def func(): - return '' - self.assertIn('func', self.library.tags) + return "" + + self.assertIn("func", self.library.tags) def test_simple_tag_name_kwarg(self): - @self.library.simple_tag(name='name') + @self.library.simple_tag(name="name") def func(): - return '' - self.assertIn('name', self.library.tags) + return "" + + self.assertIn("name", self.library.tags) def test_simple_tag_invalid(self): msg = "Invalid arguments provided to simple_tag" with self.assertRaisesMessage(ValueError, msg): - self.library.simple_tag('invalid') + self.library.simple_tag("invalid") def test_simple_tag_wrapped(self): @self.library.simple_tag @functools.lru_cache(maxsize=32) def func(): - return '' - func_wrapped = self.library.tags['func'].__wrapped__ + return "" + + func_wrapped = self.library.tags["func"].__wrapped__ self.assertIs(func_wrapped, func) - self.assertTrue(hasattr(func_wrapped, 'cache_info')) + self.assertTrue(hasattr(func_wrapped, "cache_info")) class TagRegistrationTests(SimpleTestCase): - def setUp(self): self.library = Library() @@ -120,33 +128,38 @@ class TagRegistrationTests(SimpleTestCase): @self.library.tag def func(parser, token): return Node() - self.assertEqual(self.library.tags['func'], func) + + self.assertEqual(self.library.tags["func"], func) def test_tag_parens(self): @self.library.tag() def func(parser, token): return Node() - self.assertEqual(self.library.tags['func'], func) + + self.assertEqual(self.library.tags["func"], func) def test_tag_name_arg(self): - @self.library.tag('name') + @self.library.tag("name") def func(parser, token): return Node() - self.assertEqual(self.library.tags['name'], func) + + self.assertEqual(self.library.tags["name"], func) def test_tag_name_kwarg(self): - @self.library.tag(name='name') + @self.library.tag(name="name") def func(parser, token): return Node() - self.assertEqual(self.library.tags['name'], func) + + self.assertEqual(self.library.tags["name"], func) def test_tag_call(self): def func(parser, token): return Node() - self.library.tag('name', func) - self.assertEqual(self.library.tags['name'], func) + + self.library.tag("name", func) + self.assertEqual(self.library.tags["name"], func) def test_tag_invalid(self): msg = "Unsupported arguments to Library.tag: (None, '')" with self.assertRaisesMessage(ValueError, msg): - self.library.tag(None, '') + self.library.tag(None, "") diff --git a/tests/template_tests/test_loaders.py b/tests/template_tests/test_loaders.py index 6f9c4c938e..219c331738 100644 --- a/tests/template_tests/test_loaders.py +++ b/tests/template_tests/test_loaders.py @@ -13,31 +13,37 @@ from .utils import TEMPLATE_DIR class CachedLoaderTests(SimpleTestCase): - def setUp(self): self.engine = Engine( dirs=[TEMPLATE_DIR], loaders=[ - ('django.template.loaders.cached.Loader', [ - 'django.template.loaders.filesystem.Loader', - ]), + ( + "django.template.loaders.cached.Loader", + [ + "django.template.loaders.filesystem.Loader", + ], + ), ], ) def test_get_template(self): - template = self.engine.get_template('index.html') - self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, 'index.html')) - self.assertEqual(template.origin.template_name, 'index.html') - self.assertEqual(template.origin.loader, self.engine.template_loaders[0].loaders[0]) + template = self.engine.get_template("index.html") + self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, "index.html")) + self.assertEqual(template.origin.template_name, "index.html") + self.assertEqual( + template.origin.loader, self.engine.template_loaders[0].loaders[0] + ) cache = self.engine.template_loaders[0].get_template_cache - self.assertEqual(cache['index.html'], template) + self.assertEqual(cache["index.html"], template) # Run a second time from cache - template = self.engine.get_template('index.html') - self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, 'index.html')) - self.assertEqual(template.origin.template_name, 'index.html') - self.assertEqual(template.origin.loader, self.engine.template_loaders[0].loaders[0]) + template = self.engine.get_template("index.html") + self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, "index.html")) + self.assertEqual(template.origin.template_name, "index.html") + self.assertEqual( + template.origin.loader, self.engine.template_loaders[0].loaders[0] + ) def test_get_template_missing_debug_off(self): """ @@ -47,8 +53,10 @@ class CachedLoaderTests(SimpleTestCase): """ self.engine.debug = False with self.assertRaises(TemplateDoesNotExist): - self.engine.get_template('prod-template-missing.html') - e = self.engine.template_loaders[0].get_template_cache['prod-template-missing.html'] + self.engine.get_template("prod-template-missing.html") + e = self.engine.template_loaders[0].get_template_cache[ + "prod-template-missing.html" + ] self.assertEqual(e, TemplateDoesNotExist) def test_get_template_missing_debug_on(self): @@ -58,10 +66,12 @@ class CachedLoaderTests(SimpleTestCase): """ self.engine.debug = True with self.assertRaises(TemplateDoesNotExist): - self.engine.get_template('debug-template-missing.html') - e = self.engine.template_loaders[0].get_template_cache['debug-template-missing.html'] + self.engine.get_template("debug-template-missing.html") + e = self.engine.template_loaders[0].get_template_cache[ + "debug-template-missing.html" + ] self.assertIsInstance(e, TemplateDoesNotExist) - self.assertEqual(e.args[0], 'debug-template-missing.html') + self.assertEqual(e.args[0], "debug-template-missing.html") def test_cached_exception_no_traceback(self): """ @@ -71,8 +81,10 @@ class CachedLoaderTests(SimpleTestCase): """ self.engine.debug = True with self.assertRaises(TemplateDoesNotExist): - self.engine.get_template('no-traceback-in-cache.html') - e = self.engine.template_loaders[0].get_template_cache['no-traceback-in-cache.html'] + self.engine.get_template("no-traceback-in-cache.html") + e = self.engine.template_loaders[0].get_template_cache[ + "no-traceback-in-cache.html" + ] error_msg = "Cached TemplateDoesNotExist must not have been thrown." self.assertIsNone(e.__traceback__, error_msg) @@ -84,25 +96,34 @@ class CachedLoaderTests(SimpleTestCase): #26536 -- A leading dash in a template name shouldn't be stripped from its cache key. """ - self.assertEqual(self.engine.template_loaders[0].cache_key('-template.html', []), '-template.html') + self.assertEqual( + self.engine.template_loaders[0].cache_key("-template.html", []), + "-template.html", + ) def test_template_name_lazy_string(self): """ #26603 -- A template name specified as a lazy string should be forced to text before computing its cache key. """ - self.assertEqual(self.engine.template_loaders[0].cache_key(lazystr('template.html'), []), 'template.html') + self.assertEqual( + self.engine.template_loaders[0].cache_key(lazystr("template.html"), []), + "template.html", + ) def test_get_dirs(self): inner_dirs = self.engine.template_loaders[0].loaders[0].get_dirs() - self.assertSequenceEqual(list(self.engine.template_loaders[0].get_dirs()), list(inner_dirs)) + self.assertSequenceEqual( + list(self.engine.template_loaders[0].get_dirs()), list(inner_dirs) + ) class FileSystemLoaderTests(SimpleTestCase): - @classmethod def setUpClass(cls): - cls.engine = Engine(dirs=[TEMPLATE_DIR], loaders=['django.template.loaders.filesystem.Loader']) + cls.engine = Engine( + dirs=[TEMPLATE_DIR], loaders=["django.template.loaders.filesystem.Loader"] + ) super().setUpClass() @contextmanager @@ -129,64 +150,71 @@ class FileSystemLoaderTests(SimpleTestCase): yield check_sources def test_get_template(self): - template = self.engine.get_template('index.html') - self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, 'index.html')) - self.assertEqual(template.origin.template_name, 'index.html') + template = self.engine.get_template("index.html") + self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, "index.html")) + self.assertEqual(template.origin.template_name, "index.html") self.assertEqual(template.origin.loader, self.engine.template_loaders[0]) - self.assertEqual(template.origin.loader_name, 'django.template.loaders.filesystem.Loader') + self.assertEqual( + template.origin.loader_name, "django.template.loaders.filesystem.Loader" + ) def test_loaders_dirs(self): - engine = Engine(loaders=[('django.template.loaders.filesystem.Loader', [TEMPLATE_DIR])]) - template = engine.get_template('index.html') - self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, 'index.html')) + engine = Engine( + loaders=[("django.template.loaders.filesystem.Loader", [TEMPLATE_DIR])] + ) + template = engine.get_template("index.html") + self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, "index.html")) def test_loaders_dirs_empty(self): """An empty dirs list in loaders overrides top level dirs.""" - engine = Engine(dirs=[TEMPLATE_DIR], loaders=[('django.template.loaders.filesystem.Loader', [])]) + engine = Engine( + dirs=[TEMPLATE_DIR], + loaders=[("django.template.loaders.filesystem.Loader", [])], + ) with self.assertRaises(TemplateDoesNotExist): - engine.get_template('index.html') + engine.get_template("index.html") def test_directory_security(self): - with self.source_checker(['/dir1', '/dir2']) as check_sources: - check_sources('index.html', ['/dir1/index.html', '/dir2/index.html']) - check_sources('/etc/passwd', []) - check_sources('etc/passwd', ['/dir1/etc/passwd', '/dir2/etc/passwd']) - check_sources('../etc/passwd', []) - check_sources('../../../etc/passwd', []) - check_sources('/dir1/index.html', ['/dir1/index.html']) - check_sources('../dir2/index.html', ['/dir2/index.html']) - check_sources('/dir1blah', []) - check_sources('../dir1blah', []) + with self.source_checker(["/dir1", "/dir2"]) as check_sources: + check_sources("index.html", ["/dir1/index.html", "/dir2/index.html"]) + check_sources("/etc/passwd", []) + check_sources("etc/passwd", ["/dir1/etc/passwd", "/dir2/etc/passwd"]) + check_sources("../etc/passwd", []) + check_sources("../../../etc/passwd", []) + check_sources("/dir1/index.html", ["/dir1/index.html"]) + check_sources("../dir2/index.html", ["/dir2/index.html"]) + check_sources("/dir1blah", []) + check_sources("../dir1blah", []) def test_unicode_template_name(self): - with self.source_checker(['/dir1', '/dir2']) as check_sources: - check_sources('Ångström', ['/dir1/Ångström', '/dir2/Ångström']) + with self.source_checker(["/dir1", "/dir2"]) as check_sources: + check_sources("Ångström", ["/dir1/Ångström", "/dir2/Ångström"]) def test_bytestring(self): loader = self.engine.template_loaders[0] msg = "Can't mix strings and bytes in path components" with self.assertRaisesMessage(TypeError, msg): - list(loader.get_template_sources(b'\xc3\x85ngstr\xc3\xb6m')) + list(loader.get_template_sources(b"\xc3\x85ngstr\xc3\xb6m")) def test_unicode_dir_name(self): - with self.source_checker(['/Straße']) as check_sources: - check_sources('Ångström', ['/Straße/Ångström']) + with self.source_checker(["/Straße"]) as check_sources: + check_sources("Ångström", ["/Straße/Ångström"]) @unittest.skipUnless( - os.path.normcase('/TEST') == os.path.normpath('/test'), + os.path.normcase("/TEST") == os.path.normpath("/test"), "This test only runs on case-sensitive file systems.", ) def test_case_sensitivity(self): - with self.source_checker(['/dir1', '/DIR2']) as check_sources: - check_sources('index.html', ['/dir1/index.html', '/DIR2/index.html']) - check_sources('/DIR1/index.HTML', ['/DIR1/index.HTML']) + with self.source_checker(["/dir1", "/DIR2"]) as check_sources: + check_sources("index.html", ["/dir1/index.html", "/DIR2/index.html"]) + check_sources("/DIR1/index.HTML", ["/DIR1/index.HTML"]) def test_file_does_not_exist(self): with self.assertRaises(TemplateDoesNotExist): - self.engine.get_template('doesnotexist.html') + self.engine.get_template("doesnotexist.html") @unittest.skipIf( - sys.platform == 'win32', + sys.platform == "win32", "Python on Windows doesn't have working os.chmod().", ) def test_permissions_error(self): @@ -195,50 +223,55 @@ class FileSystemLoaderTests(SimpleTestCase): tmppath = os.path.join(tmpdir, tmpfile.name) os.chmod(tmppath, 0o0222) with self.set_dirs([tmpdir]): - with self.assertRaisesMessage(PermissionError, 'Permission denied'): + with self.assertRaisesMessage(PermissionError, "Permission denied"): self.engine.get_template(tmpfile.name) def test_notafile_error(self): # Windows raises PermissionError when trying to open a directory. - with self.assertRaises(PermissionError if sys.platform == 'win32' else IsADirectoryError): - self.engine.get_template('first') + with self.assertRaises( + PermissionError if sys.platform == "win32" else IsADirectoryError + ): + self.engine.get_template("first") class AppDirectoriesLoaderTests(SimpleTestCase): - @classmethod def setUpClass(cls): cls.engine = Engine( - loaders=['django.template.loaders.app_directories.Loader'], + loaders=["django.template.loaders.app_directories.Loader"], ) super().setUpClass() - @override_settings(INSTALLED_APPS=['template_tests']) + @override_settings(INSTALLED_APPS=["template_tests"]) def test_get_template(self): - template = self.engine.get_template('index.html') - self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, 'index.html')) - self.assertEqual(template.origin.template_name, 'index.html') + template = self.engine.get_template("index.html") + self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, "index.html")) + self.assertEqual(template.origin.template_name, "index.html") self.assertEqual(template.origin.loader, self.engine.template_loaders[0]) @override_settings(INSTALLED_APPS=[]) def test_not_installed(self): with self.assertRaises(TemplateDoesNotExist): - self.engine.get_template('index.html') + self.engine.get_template("index.html") class LocmemLoaderTests(SimpleTestCase): - @classmethod def setUpClass(cls): cls.engine = Engine( - loaders=[('django.template.loaders.locmem.Loader', { - 'index.html': 'index', - })], + loaders=[ + ( + "django.template.loaders.locmem.Loader", + { + "index.html": "index", + }, + ) + ], ) super().setUpClass() def test_get_template(self): - template = self.engine.get_template('index.html') - self.assertEqual(template.origin.name, 'index.html') - self.assertEqual(template.origin.template_name, 'index.html') + template = self.engine.get_template("index.html") + self.assertEqual(template.origin.name, "index.html") + self.assertEqual(template.origin.template_name, "index.html") self.assertEqual(template.origin.loader, self.engine.template_loaders[0]) diff --git a/tests/template_tests/test_logging.py b/tests/template_tests/test_logging.py index a5bdebaf16..357cf2c70b 100644 --- a/tests/template_tests/test_logging.py +++ b/tests/template_tests/test_logging.py @@ -18,7 +18,7 @@ class VariableResolveLoggingTests(SimpleTestCase): @property def template(self): - return Engine().from_string('') + return Engine().from_string("") @property def article(self): @@ -30,37 +30,37 @@ class VariableResolveLoggingTests(SimpleTestCase): def __getitem__(self, item): return self.__dict__[item] - with self.assertLogs('django.template', self.loglevel) as cm: - Variable('article').resolve(TestObject()) + with self.assertLogs("django.template", self.loglevel) as cm: + Variable("article").resolve(TestObject()) self.assertEqual(len(cm.records), 1) log_record = cm.records[0] self.assertEqual( log_record.getMessage(), - "Exception while resolving variable 'article' in template 'template_name'." + "Exception while resolving variable 'article' in template 'template_name'.", ) self.assertIsNotNone(log_record.exc_info) raised_exception = log_record.exc_info[1] - self.assertEqual(str(raised_exception), 'Attribute does not exist.') + self.assertEqual(str(raised_exception), "Attribute does not exist.") def test_log_on_variable_does_not_exist_not_silent(self): - with self.assertLogs('django.template', self.loglevel) as cm: + with self.assertLogs("django.template", self.loglevel) as cm: with self.assertRaises(VariableDoesNotExist): - Variable('article.author').resolve({'article': {'section': 'News'}}) + Variable("article.author").resolve({"article": {"section": "News"}}) self.assertEqual(len(cm.records), 1) log_record = cm.records[0] self.assertEqual( log_record.getMessage(), - "Exception while resolving variable 'author' in template 'unknown'." + "Exception while resolving variable 'author' in template 'unknown'.", ) self.assertIsNotNone(log_record.exc_info) raised_exception = log_record.exc_info[1] self.assertEqual( str(raised_exception), - "Failed lookup for key [author] in {'section': 'News'}" + "Failed lookup for key [author] in {'section': 'News'}", ) def test_no_log_when_variable_exists(self): - with self.assertNoLogs('django.template', self.loglevel): - Variable('article.section').resolve({'article': {'section': 'News'}}) + with self.assertNoLogs("django.template", self.loglevel): + Variable("article.section").resolve({"article": {"section": "News"}}) diff --git a/tests/template_tests/test_nodelist.py b/tests/template_tests/test_nodelist.py index 03c0d99651..429d1dca23 100644 --- a/tests/template_tests/test_nodelist.py +++ b/tests/template_tests/test_nodelist.py @@ -4,30 +4,28 @@ from django.test import SimpleTestCase class NodelistTest(SimpleTestCase): - @classmethod def setUpClass(cls): cls.engine = Engine() super().setUpClass() def test_for(self): - template = self.engine.from_string('{% for i in 1 %}{{ a }}{% endfor %}') + template = self.engine.from_string("{% for i in 1 %}{{ a }}{% endfor %}") vars = template.nodelist.get_nodes_by_type(VariableNode) self.assertEqual(len(vars), 1) def test_if(self): - template = self.engine.from_string('{% if x %}{{ a }}{% endif %}') + template = self.engine.from_string("{% if x %}{{ a }}{% endif %}") vars = template.nodelist.get_nodes_by_type(VariableNode) self.assertEqual(len(vars), 1) def test_ifchanged(self): - template = self.engine.from_string('{% ifchanged x %}{{ a }}{% endifchanged %}') + template = self.engine.from_string("{% ifchanged x %}{{ a }}{% endifchanged %}") vars = template.nodelist.get_nodes_by_type(VariableNode) self.assertEqual(len(vars), 1) class TextNodeTest(SimpleTestCase): - def test_textnode_repr(self): engine = Engine() for temptext, reprtext in [ @@ -44,35 +42,48 @@ class ErrorIndexTest(SimpleTestCase): Checks whether index of error is calculated correctly in template debugger in for loops. Refs ticket #5831 """ + def test_correct_exception_index(self): tests = [ - ('{% load bad_tag %}{% for i in range %}{% badsimpletag %}{% endfor %}', (38, 56)), ( - '{% load bad_tag %}{% for i in range %}{% for j in range %}' - '{% badsimpletag %}{% endfor %}{% endfor %}', - (58, 76) + "{% load bad_tag %}{% for i in range %}{% badsimpletag %}{% endfor %}", + (38, 56), + ), + ( + "{% load bad_tag %}{% for i in range %}{% for j in range %}" + "{% badsimpletag %}{% endfor %}{% endfor %}", + (58, 76), + ), + ( + "{% load bad_tag %}{% for i in range %}{% badsimpletag %}" + "{% for j in range %}Hello{% endfor %}{% endfor %}", + (38, 56), ), ( - '{% load bad_tag %}{% for i in range %}{% badsimpletag %}' - '{% for j in range %}Hello{% endfor %}{% endfor %}', - (38, 56) + "{% load bad_tag %}{% for i in range %}{% for j in five %}" + "{% badsimpletag %}{% endfor %}{% endfor %}", + (38, 57), ), ( - '{% load bad_tag %}{% for i in range %}{% for j in five %}' - '{% badsimpletag %}{% endfor %}{% endfor %}', - (38, 57) + "{% load bad_tag %}{% for j in five %}{% badsimpletag %}{% endfor %}", + (18, 37), ), - ('{% load bad_tag %}{% for j in five %}{% badsimpletag %}{% endfor %}', (18, 37)), ] - context = Context({ - 'range': range(5), - 'five': 5, - }) - engine = Engine(debug=True, libraries={'bad_tag': 'template_tests.templatetags.bad_tag'}) + context = Context( + { + "range": range(5), + "five": 5, + } + ) + engine = Engine( + debug=True, libraries={"bad_tag": "template_tests.templatetags.bad_tag"} + ) for source, expected_error_source_index in tests: template = engine.from_string(source) try: template.render(context) except (RuntimeError, TypeError) as e: debug = e.template_debug - self.assertEqual((debug['start'], debug['end']), expected_error_source_index) + self.assertEqual( + (debug["start"], debug["end"]), expected_error_source_index + ) diff --git a/tests/template_tests/test_origin.py b/tests/template_tests/test_origin.py index f71178e955..9a42cb60e0 100644 --- a/tests/template_tests/test_origin.py +++ b/tests/template_tests/test_origin.py @@ -11,22 +11,22 @@ class OriginTestCase(TestCase): self.engine = Engine(dirs=[TEMPLATE_DIR]) def test_origin_compares_equal(self): - a = self.engine.get_template('index.html') - b = self.engine.get_template('index.html') + a = self.engine.get_template("index.html") + b = self.engine.get_template("index.html") self.assertEqual(a.origin, b.origin) # Use assertIs() to test __eq__/__ne__. self.assertIs(a.origin == b.origin, True) self.assertIs(a.origin != b.origin, False) def test_origin_compares_not_equal(self): - a = self.engine.get_template('first/test.html') - b = self.engine.get_template('second/test.html') + a = self.engine.get_template("first/test.html") + b = self.engine.get_template("second/test.html") self.assertNotEqual(a.origin, b.origin) # Use assertIs() to test __eq__/__ne__. self.assertIs(a.origin == b.origin, False) self.assertIs(a.origin != b.origin, True) def test_repr(self): - a = self.engine.get_template('index.html') - name = os.path.join(TEMPLATE_DIR, 'index.html') - self.assertEqual(repr(a.origin), '<Origin name=%r>' % name) + a = self.engine.get_template("index.html") + name = os.path.join(TEMPLATE_DIR, "index.html") + self.assertEqual(repr(a.origin), "<Origin name=%r>" % name) diff --git a/tests/template_tests/test_parser.py b/tests/template_tests/test_parser.py index 23d8795d7f..ee9b9b1b12 100644 --- a/tests/template_tests/test_parser.py +++ b/tests/template_tests/test_parser.py @@ -3,33 +3,41 @@ Testing some internals of the template processing. These are *not* examples to b """ from django.template import Library, TemplateSyntaxError from django.template.base import ( - FilterExpression, Lexer, Parser, Token, TokenType, Variable, + FilterExpression, + Lexer, + Parser, + Token, + TokenType, + Variable, ) from django.template.defaultfilters import register as filter_library from django.test import SimpleTestCase class ParserTests(SimpleTestCase): - def test_token_smart_split(self): """ #7027 -- _() syntax should work with spaces """ - token = Token(TokenType.BLOCK, 'sometag _("Page not found") value|yesno:_("yes,no")') + token = Token( + TokenType.BLOCK, 'sometag _("Page not found") value|yesno:_("yes,no")' + ) split = token.split_contents() - self.assertEqual(split, ["sometag", '_("Page not found")', 'value|yesno:_("yes,no")']) + self.assertEqual( + split, ["sometag", '_("Page not found")', 'value|yesno:_("yes,no")'] + ) def test_repr(self): - token = Token(TokenType.BLOCK, 'some text') + token = Token(TokenType.BLOCK, "some text") self.assertEqual(repr(token), '<Block token: "some text...">') parser = Parser([token], builtins=[filter_library]) self.assertEqual( repr(parser), '<Parser tokens=[<Block token: "some text...">]>', ) - filter_expression = FilterExpression('news|upper', parser) + filter_expression = FilterExpression("news|upper", parser) self.assertEqual(repr(filter_expression), "<FilterExpression 'news|upper'>") - lexer = Lexer('{% for i in 1 %}{{ a }}\n{% endfor %}') + lexer = Lexer("{% for i in 1 %}{{ a }}\n{% endfor %}") self.assertEqual( repr(lexer), '<Lexer template_string="{% for i in 1 %}{{ a...", verbatim=False>', @@ -56,7 +64,9 @@ class ParserTests(SimpleTestCase): # Filtered variables should reject access of attributes beginning with # underscores. - msg = "Variables and attributes may not begin with underscores: 'article._hidden'" + msg = ( + "Variables and attributes may not begin with underscores: 'article._hidden'" + ) with self.assertRaisesMessage(TemplateSyntaxError, msg): FilterExpression("article._hidden|upper", p) @@ -81,13 +91,15 @@ class ParserTests(SimpleTestCase): # Variables should reject access of attributes and variables beginning # with underscores. - for name in ['article._hidden', '_article']: + for name in ["article._hidden", "_article"]: msg = f"Variables and attributes may not begin with underscores: '{name}'" with self.assertRaisesMessage(TemplateSyntaxError, msg): Variable(name) # Variables should raise on non string type - with self.assertRaisesMessage(TypeError, "Variable must be a string or number, got <class 'dict'>"): + with self.assertRaisesMessage( + TypeError, "Variable must be a string or number, got <class 'dict'>" + ): Variable({}) def test_filter_args_count(self): @@ -113,23 +125,24 @@ class ParserTests(SimpleTestCase): @register.filter def two_one_opt_arg(value, arg, arg2=False): pass + parser.add_library(register) for expr in ( - '1|no_arguments:"1"', - '1|two_arguments', - '1|two_arguments:"1"', - '1|two_one_opt_arg', + '1|no_arguments:"1"', + "1|two_arguments", + '1|two_arguments:"1"', + "1|two_one_opt_arg", ): with self.assertRaises(TemplateSyntaxError): FilterExpression(expr, parser) for expr in ( - # Correct number of arguments - '1|no_arguments', - '1|one_argument:"1"', - # One optional - '1|one_opt_argument', - '1|one_opt_argument:"1"', - # Not supplying all - '1|two_one_opt_arg:"1"', + # Correct number of arguments + "1|no_arguments", + '1|one_argument:"1"', + # One optional + "1|one_opt_argument", + '1|one_opt_argument:"1"', + # Not supplying all + '1|two_one_opt_arg:"1"', ): FilterExpression(expr, parser) diff --git a/tests/template_tests/test_response.py b/tests/template_tests/test_response.py index 8ac629f3bd..89361be284 100644 --- a/tests/template_tests/test_response.py +++ b/tests/template_tests/test_response.py @@ -4,10 +4,15 @@ from datetime import datetime from django.template import engines from django.template.response import ( - ContentNotRenderedError, SimpleTemplateResponse, TemplateResponse, + ContentNotRenderedError, + SimpleTemplateResponse, + TemplateResponse, ) from django.test import ( - RequestFactory, SimpleTestCase, modify_settings, override_settings, + RequestFactory, + SimpleTestCase, + modify_settings, + override_settings, ) from django.test.utils import require_jinja2 @@ -15,39 +20,39 @@ from .utils import TEMPLATE_DIR def test_processor(request): - return {'processors': 'yes'} + return {"processors": "yes"} -test_processor_name = 'template_tests.test_response.test_processor' +test_processor_name = "template_tests.test_response.test_processor" # A test middleware that installs a temporary URLConf def custom_urlconf_middleware(get_response): def middleware(request): - request.urlconf = 'template_tests.alternate_urls' + request.urlconf = "template_tests.alternate_urls" return get_response(request) + return middleware class SimpleTemplateResponseTest(SimpleTestCase): - - def _response(self, template='foo', *args, **kwargs): - template = engines['django'].from_string(template) + def _response(self, template="foo", *args, **kwargs): + template = engines["django"].from_string(template) return SimpleTemplateResponse(template, *args, **kwargs) def test_template_resolving(self): - response = SimpleTemplateResponse('first/test.html') + response = SimpleTemplateResponse("first/test.html") response.render() - self.assertEqual(response.content, b'First template\n') + self.assertEqual(response.content, b"First template\n") - templates = ['foo.html', 'second/test.html', 'first/test.html'] + templates = ["foo.html", "second/test.html", "first/test.html"] response = SimpleTemplateResponse(templates) response.render() - self.assertEqual(response.content, b'Second template\n') + self.assertEqual(response.content, b"Second template\n") response = self._response() response.render() - self.assertEqual(response.content, b'foo') + self.assertEqual(response.content, b"foo") def test_explicit_baking(self): # explicit baking @@ -59,18 +64,18 @@ class SimpleTemplateResponseTest(SimpleTestCase): def test_render(self): # response is not re-rendered without the render call response = self._response().render() - self.assertEqual(response.content, b'foo') + self.assertEqual(response.content, b"foo") # rebaking doesn't change the rendered content - template = engines['django'].from_string('bar{{ baz }}') + template = engines["django"].from_string("bar{{ baz }}") response.template_name = template response.render() - self.assertEqual(response.content, b'foo') + self.assertEqual(response.content, b"foo") # but rendered content can be overridden by manually # setting content - response.content = 'bar' - self.assertEqual(response.content, b'bar') + response.content = "bar" + self.assertEqual(response.content, b"bar") def test_iteration_unrendered(self): # unrendered response raises an exception on iteration @@ -80,7 +85,7 @@ class SimpleTemplateResponseTest(SimpleTestCase): def iteration(): list(response) - msg = 'The response content must be rendered before it can be iterated over.' + msg = "The response content must be rendered before it can be iterated over." with self.assertRaisesMessage(ContentNotRenderedError, msg): iteration() self.assertFalse(response.is_rendered) @@ -88,7 +93,7 @@ class SimpleTemplateResponseTest(SimpleTestCase): def test_iteration_rendered(self): # iteration works for rendered responses response = self._response().render() - self.assertEqual(list(response), [b'foo']) + self.assertEqual(list(response), [b"foo"]) def test_content_access_unrendered(self): # unrendered response raises an exception when content is accessed @@ -101,71 +106,79 @@ class SimpleTemplateResponseTest(SimpleTestCase): def test_content_access_rendered(self): # rendered response content can be accessed response = self._response().render() - self.assertEqual(response.content, b'foo') + self.assertEqual(response.content, b"foo") def test_set_content(self): # content can be overridden response = self._response() self.assertFalse(response.is_rendered) - response.content = 'spam' + response.content = "spam" self.assertTrue(response.is_rendered) - self.assertEqual(response.content, b'spam') - response.content = 'baz' - self.assertEqual(response.content, b'baz') + self.assertEqual(response.content, b"spam") + response.content = "baz" + self.assertEqual(response.content, b"baz") def test_dict_context(self): - response = self._response('{{ foo }}{{ processors }}', - {'foo': 'bar'}) - self.assertEqual(response.context_data, {'foo': 'bar'}) + response = self._response("{{ foo }}{{ processors }}", {"foo": "bar"}) + self.assertEqual(response.context_data, {"foo": "bar"}) response.render() - self.assertEqual(response.content, b'bar') + self.assertEqual(response.content, b"bar") def test_kwargs(self): - response = self._response(content_type='application/json', status=504, charset='ascii') - self.assertEqual(response.headers['content-type'], 'application/json') + response = self._response( + content_type="application/json", status=504, charset="ascii" + ) + self.assertEqual(response.headers["content-type"], "application/json") self.assertEqual(response.status_code, 504) - self.assertEqual(response.charset, 'ascii') + self.assertEqual(response.charset, "ascii") def test_args(self): - response = SimpleTemplateResponse('', {}, 'application/json', 504) - self.assertEqual(response.headers['content-type'], 'application/json') + response = SimpleTemplateResponse("", {}, "application/json", 504) + self.assertEqual(response.headers["content-type"], "application/json") self.assertEqual(response.status_code, 504) @require_jinja2 def test_using(self): - response = SimpleTemplateResponse('template_tests/using.html').render() - self.assertEqual(response.content, b'DTL\n') - response = SimpleTemplateResponse('template_tests/using.html', using='django').render() - self.assertEqual(response.content, b'DTL\n') - response = SimpleTemplateResponse('template_tests/using.html', using='jinja2').render() - self.assertEqual(response.content, b'Jinja2\n') + response = SimpleTemplateResponse("template_tests/using.html").render() + self.assertEqual(response.content, b"DTL\n") + response = SimpleTemplateResponse( + "template_tests/using.html", using="django" + ).render() + self.assertEqual(response.content, b"DTL\n") + response = SimpleTemplateResponse( + "template_tests/using.html", using="jinja2" + ).render() + self.assertEqual(response.content, b"Jinja2\n") def test_post_callbacks(self): "Rendering a template response triggers the post-render callbacks" post = [] def post1(obj): - post.append('post1') + post.append("post1") def post2(obj): - post.append('post2') + post.append("post2") - response = SimpleTemplateResponse('first/test.html', {}) + response = SimpleTemplateResponse("first/test.html", {}) response.add_post_render_callback(post1) response.add_post_render_callback(post2) # When the content is rendered, all the callbacks are invoked, too. response.render() - self.assertEqual(response.content, b'First template\n') - self.assertEqual(post, ['post1', 'post2']) + self.assertEqual(response.content, b"First template\n") + self.assertEqual(post, ["post1", "post2"]) def test_pickling(self): # Create a template response. The context is # known to be unpicklable (e.g., a function). - response = SimpleTemplateResponse('first/test.html', { - 'value': 123, - 'fn': datetime.now, - }) + response = SimpleTemplateResponse( + "first/test.html", + { + "value": 123, + "fn": datetime.now, + }, + ) with self.assertRaises(ContentNotRenderedError): pickle.dumps(response) @@ -175,12 +188,14 @@ class SimpleTemplateResponseTest(SimpleTestCase): unpickled_response = pickle.loads(pickled_response) self.assertEqual(unpickled_response.content, response.content) - self.assertEqual(unpickled_response.headers['content-type'], response.headers['content-type']) + self.assertEqual( + unpickled_response.headers["content-type"], response.headers["content-type"] + ) self.assertEqual(unpickled_response.status_code, response.status_code) # ...and the unpickled response doesn't have the # template-related attributes, so it can't be re-rendered - template_attrs = ('template_name', 'context_data', '_post_render_callbacks') + template_attrs = ("template_name", "context_data", "_post_render_callbacks") for attr in template_attrs: self.assertFalse(hasattr(unpickled_response, attr)) @@ -190,10 +205,13 @@ class SimpleTemplateResponseTest(SimpleTestCase): getattr(unpickled_response, attr) def test_repickling(self): - response = SimpleTemplateResponse('first/test.html', { - 'value': 123, - 'fn': datetime.now, - }) + response = SimpleTemplateResponse( + "first/test.html", + { + "value": 123, + "fn": datetime.now, + }, + ) with self.assertRaises(ContentNotRenderedError): pickle.dumps(response) @@ -203,88 +221,101 @@ class SimpleTemplateResponseTest(SimpleTestCase): pickle.dumps(unpickled_response) def test_pickling_cookie(self): - response = SimpleTemplateResponse('first/test.html', { - 'value': 123, - 'fn': datetime.now, - }) + response = SimpleTemplateResponse( + "first/test.html", + { + "value": 123, + "fn": datetime.now, + }, + ) - response.cookies['key'] = 'value' + response.cookies["key"] = "value" response.render() pickled_response = pickle.dumps(response, pickle.HIGHEST_PROTOCOL) unpickled_response = pickle.loads(pickled_response) - self.assertEqual(unpickled_response.cookies['key'].value, 'value') + self.assertEqual(unpickled_response.cookies["key"].value, "value") def test_headers(self): response = SimpleTemplateResponse( - 'first/test.html', - {'value': 123, 'fn': datetime.now}, - headers={'X-Foo': 'foo'}, + "first/test.html", + {"value": 123, "fn": datetime.now}, + headers={"X-Foo": "foo"}, ) - self.assertEqual(response.headers['X-Foo'], 'foo') + self.assertEqual(response.headers["X-Foo"], "foo") -@override_settings(TEMPLATES=[{ - 'BACKEND': 'django.template.backends.django.DjangoTemplates', - 'DIRS': [TEMPLATE_DIR], - 'OPTIONS': { - 'context_processors': [test_processor_name], - }, -}]) +@override_settings( + TEMPLATES=[ + { + "BACKEND": "django.template.backends.django.DjangoTemplates", + "DIRS": [TEMPLATE_DIR], + "OPTIONS": { + "context_processors": [test_processor_name], + }, + } + ] +) class TemplateResponseTest(SimpleTestCase): factory = RequestFactory() - def _response(self, template='foo', *args, **kwargs): - self._request = self.factory.get('/') - template = engines['django'].from_string(template) + def _response(self, template="foo", *args, **kwargs): + self._request = self.factory.get("/") + template = engines["django"].from_string(template) return TemplateResponse(self._request, template, *args, **kwargs) def test_render(self): - response = self._response('{{ foo }}{{ processors }}').render() - self.assertEqual(response.content, b'yes') + response = self._response("{{ foo }}{{ processors }}").render() + self.assertEqual(response.content, b"yes") def test_render_with_requestcontext(self): - response = self._response('{{ foo }}{{ processors }}', - {'foo': 'bar'}).render() - self.assertEqual(response.content, b'baryes') + response = self._response("{{ foo }}{{ processors }}", {"foo": "bar"}).render() + self.assertEqual(response.content, b"baryes") def test_context_processor_priority(self): # context processors should be overridden by passed-in context - response = self._response('{{ foo }}{{ processors }}', - {'processors': 'no'}).render() - self.assertEqual(response.content, b'no') + response = self._response( + "{{ foo }}{{ processors }}", {"processors": "no"} + ).render() + self.assertEqual(response.content, b"no") def test_kwargs(self): - response = self._response(content_type='application/json', status=504) - self.assertEqual(response.headers['content-type'], 'application/json') + response = self._response(content_type="application/json", status=504) + self.assertEqual(response.headers["content-type"], "application/json") self.assertEqual(response.status_code, 504) def test_args(self): - response = TemplateResponse(self.factory.get('/'), '', {}, - 'application/json', 504) - self.assertEqual(response.headers['content-type'], 'application/json') + response = TemplateResponse( + self.factory.get("/"), "", {}, "application/json", 504 + ) + self.assertEqual(response.headers["content-type"], "application/json") self.assertEqual(response.status_code, 504) @require_jinja2 def test_using(self): - request = self.factory.get('/') - response = TemplateResponse(request, 'template_tests/using.html').render() - self.assertEqual(response.content, b'DTL\n') - response = TemplateResponse(request, 'template_tests/using.html', using='django').render() - self.assertEqual(response.content, b'DTL\n') - response = TemplateResponse(request, 'template_tests/using.html', using='jinja2').render() - self.assertEqual(response.content, b'Jinja2\n') + request = self.factory.get("/") + response = TemplateResponse(request, "template_tests/using.html").render() + self.assertEqual(response.content, b"DTL\n") + response = TemplateResponse( + request, "template_tests/using.html", using="django" + ).render() + self.assertEqual(response.content, b"DTL\n") + response = TemplateResponse( + request, "template_tests/using.html", using="jinja2" + ).render() + self.assertEqual(response.content, b"Jinja2\n") def test_pickling(self): # Create a template response. The context is # known to be unpicklable (e.g., a function). response = TemplateResponse( - self.factory.get('/'), - 'first/test.html', { - 'value': 123, - 'fn': datetime.now, - } + self.factory.get("/"), + "first/test.html", + { + "value": 123, + "fn": datetime.now, + }, ) with self.assertRaises(ContentNotRenderedError): pickle.dumps(response) @@ -295,16 +326,18 @@ class TemplateResponseTest(SimpleTestCase): unpickled_response = pickle.loads(pickled_response) self.assertEqual(unpickled_response.content, response.content) - self.assertEqual(unpickled_response.headers['content-type'], response.headers['content-type']) + self.assertEqual( + unpickled_response.headers["content-type"], response.headers["content-type"] + ) self.assertEqual(unpickled_response.status_code, response.status_code) # ...and the unpickled response doesn't have the # template-related attributes, so it can't be re-rendered template_attrs = ( - 'template_name', - 'context_data', - '_post_render_callbacks', - '_request', + "template_name", + "context_data", + "_post_render_callbacks", + "_request", ) for attr in template_attrs: self.assertFalse(hasattr(unpickled_response, attr)) @@ -315,10 +348,13 @@ class TemplateResponseTest(SimpleTestCase): getattr(unpickled_response, attr) def test_repickling(self): - response = SimpleTemplateResponse('first/test.html', { - 'value': 123, - 'fn': datetime.now, - }) + response = SimpleTemplateResponse( + "first/test.html", + { + "value": 123, + "fn": datetime.now, + }, + ) with self.assertRaises(ContentNotRenderedError): pickle.dumps(response) @@ -329,41 +365,43 @@ class TemplateResponseTest(SimpleTestCase): def test_headers(self): response = TemplateResponse( - self.factory.get('/'), - 'first/test.html', - {'value': 123, 'fn': datetime.now}, - headers={'X-Foo': 'foo'}, + self.factory.get("/"), + "first/test.html", + {"value": 123, "fn": datetime.now}, + headers={"X-Foo": "foo"}, ) - self.assertEqual(response.headers['X-Foo'], 'foo') + self.assertEqual(response.headers["X-Foo"], "foo") -@modify_settings(MIDDLEWARE={'append': ['template_tests.test_response.custom_urlconf_middleware']}) -@override_settings(ROOT_URLCONF='template_tests.urls') +@modify_settings( + MIDDLEWARE={"append": ["template_tests.test_response.custom_urlconf_middleware"]} +) +@override_settings(ROOT_URLCONF="template_tests.urls") class CustomURLConfTest(SimpleTestCase): - def test_custom_urlconf(self): - response = self.client.get('/template_response_view/') - self.assertContains(response, 'This is where you can find the snark: /snark/') + response = self.client.get("/template_response_view/") + self.assertContains(response, "This is where you can find the snark: /snark/") @modify_settings( MIDDLEWARE={ - 'append': [ - 'django.middleware.cache.FetchFromCacheMiddleware', - 'django.middleware.cache.UpdateCacheMiddleware', + "append": [ + "django.middleware.cache.FetchFromCacheMiddleware", + "django.middleware.cache.UpdateCacheMiddleware", ], }, ) -@override_settings(CACHE_MIDDLEWARE_SECONDS=2.0, ROOT_URLCONF='template_tests.alternate_urls') +@override_settings( + CACHE_MIDDLEWARE_SECONDS=2.0, ROOT_URLCONF="template_tests.alternate_urls" +) class CacheMiddlewareTest(SimpleTestCase): - def test_middleware_caching(self): - response = self.client.get('/template_response_view/') + response = self.client.get("/template_response_view/") self.assertEqual(response.status_code, 200) time.sleep(1.0) - response2 = self.client.get('/template_response_view/') + response2 = self.client.get("/template_response_view/") self.assertEqual(response2.status_code, 200) self.assertEqual(response.content, response2.content) @@ -371,7 +409,7 @@ class CacheMiddlewareTest(SimpleTestCase): time.sleep(2.0) # Let the cache expire and test again - response2 = self.client.get('/template_response_view/') + response2 = self.client.get("/template_response_view/") self.assertEqual(response2.status_code, 200) self.assertNotEqual(response.content, response2.content) diff --git a/tests/template_tests/test_smartif.py b/tests/template_tests/test_smartif.py index 9115acef4e..b690ce3547 100644 --- a/tests/template_tests/test_smartif.py +++ b/tests/template_tests/test_smartif.py @@ -4,7 +4,6 @@ from django.template.smartif import IfParser class SmartIfTests(unittest.TestCase): - def assertCalcEqual(self, expected, tokens): self.assertEqual(expected, IfParser(tokens).parse().eval({})) @@ -25,31 +24,33 @@ class SmartIfTests(unittest.TestCase): def test_in(self): list_ = [1, 2, 3] - self.assertCalcEqual(True, [1, 'in', list_]) - self.assertCalcEqual(False, [1, 'in', None]) - self.assertCalcEqual(False, [None, 'in', list_]) + self.assertCalcEqual(True, [1, "in", list_]) + self.assertCalcEqual(False, [1, "in", None]) + self.assertCalcEqual(False, [None, "in", list_]) def test_not_in(self): list_ = [1, 2, 3] - self.assertCalcEqual(False, [1, 'not', 'in', list_]) - self.assertCalcEqual(True, [4, 'not', 'in', list_]) - self.assertCalcEqual(False, [1, 'not', 'in', None]) - self.assertCalcEqual(True, [None, 'not', 'in', list_]) + self.assertCalcEqual(False, [1, "not", "in", list_]) + self.assertCalcEqual(True, [4, "not", "in", list_]) + self.assertCalcEqual(False, [1, "not", "in", None]) + self.assertCalcEqual(True, [None, "not", "in", list_]) def test_precedence(self): # (False and False) or True == True <- we want this one, like Python # False and (False or True) == False - self.assertCalcEqual(True, [False, 'and', False, 'or', True]) + self.assertCalcEqual(True, [False, "and", False, "or", True]) # True or (False and False) == True <- we want this one, like Python # (True or False) and False == False - self.assertCalcEqual(True, [True, 'or', False, 'and', False]) + self.assertCalcEqual(True, [True, "or", False, "and", False]) # (1 or 1) == 2 -> False # 1 or (1 == 2) -> True <- we want this one - self.assertCalcEqual(True, [1, 'or', 1, '==', 2]) + self.assertCalcEqual(True, [1, "or", 1, "==", 2]) - self.assertCalcEqual(True, [True, '==', True, 'or', True, '==', False]) + self.assertCalcEqual(True, [True, "==", True, "or", True, "==", False]) - self.assertEqual("(or (and (== (literal 1) (literal 2)) (literal 3)) (literal 4))", - repr(IfParser([1, '==', 2, 'and', 3, 'or', 4]).parse())) + self.assertEqual( + "(or (and (== (literal 1) (literal 2)) (literal 3)) (literal 4))", + repr(IfParser([1, "==", 2, "and", 3, "or", 4]).parse()), + ) diff --git a/tests/template_tests/tests.py b/tests/template_tests/tests.py index 33837114c6..b849b4a2e7 100644 --- a/tests/template_tests/tests.py +++ b/tests/template_tests/tests.py @@ -1,8 +1,6 @@ import sys -from django.template import ( - Context, Engine, TemplateDoesNotExist, TemplateSyntaxError, -) +from django.template import Context, Engine, TemplateDoesNotExist, TemplateSyntaxError from django.template.base import UNKNOWN_SOURCE from django.test import SimpleTestCase, override_settings from django.urls import NoReverseMatch @@ -15,10 +13,10 @@ class TemplateTestMixin: return Engine(debug=self.debug_engine, **kwargs) def test_string_origin(self): - template = self._engine().from_string('string template') + template = self._engine().from_string("string template") self.assertEqual(template.origin.name, UNKNOWN_SOURCE) self.assertIsNone(template.origin.loader_name) - self.assertEqual(template.source, 'string template') + self.assertEqual(template.source, "string template") @override_settings(SETTINGS_MODULE=None) def test_url_reverse_no_settings_module(self): @@ -26,7 +24,7 @@ class TemplateTestMixin: #9005 -- url tag shouldn't require settings.SETTINGS_MODULE to be set. """ - t = self._engine().from_string('{% url will_not_match %}') + t = self._engine().from_string("{% url will_not_match %}") c = Context() with self.assertRaises(NoReverseMatch): t.render(c) @@ -36,7 +34,7 @@ class TemplateTestMixin: #19827 -- url tag should keep original strack trace when reraising exception. """ - t = self._engine().from_string('{% url will_not_match %}') + t = self._engine().from_string("{% url will_not_match %}") c = Context() try: t.render(c) @@ -46,7 +44,9 @@ class TemplateTestMixin: while tb.tb_next is not None: tb = tb.tb_next depth += 1 - self.assertGreater(depth, 5, "The traceback context was lost when reraising the traceback.") + self.assertGreater( + depth, 5, "The traceback context was lost when reraising the traceback." + ) def test_no_wrapped_exception(self): """ @@ -62,8 +62,8 @@ class TemplateTestMixin: if self.debug_engine: debug = e.exception.template_debug - self.assertEqual(debug['start'], 0) - self.assertEqual(debug['end'], 14) + self.assertEqual(debug["start"], 0) + self.assertEqual(debug["end"], 14) def test_invalid_block_suggestion(self): """ @@ -75,7 +75,7 @@ class TemplateTestMixin: "Invalid block tag on line 1: 'endblock', expected 'elif', 'else' " "or 'endif'. Did you forget to register or load this tag?" ) - with self.settings(USE_I18N=True), translation.override('de'): + with self.settings(USE_I18N=True), translation.override("de"): with self.assertRaisesMessage(TemplateSyntaxError, msg): engine.from_string("{% if 1 %}lala{% endblock %}{% endif %}") @@ -101,8 +101,8 @@ class TemplateTestMixin: if self.debug_engine: debug = e.exception.template_debug - self.assertEqual((debug['start'], debug['end']), (10, 23)) - self.assertEqual((debug['during']), '{{ foo@bar }}') + self.assertEqual((debug["start"], debug["end"]), (10, 23)) + self.assertEqual((debug["during"]), "{{ foo@bar }}") def test_compile_tag_error(self): """ @@ -110,46 +110,46 @@ class TemplateTestMixin: information. """ engine = self._engine( - libraries={'bad_tag': 'template_tests.templatetags.bad_tag'}, + libraries={"bad_tag": "template_tests.templatetags.bad_tag"}, ) with self.assertRaises(RuntimeError) as e: engine.from_string("{% load bad_tag %}{% badtag %}") if self.debug_engine: - self.assertEqual(e.exception.template_debug['during'], '{% badtag %}') + self.assertEqual(e.exception.template_debug["during"], "{% badtag %}") def test_compile_tag_error_27584(self): engine = self._engine( app_dirs=True, - libraries={'tag_27584': 'template_tests.templatetags.tag_27584'}, + libraries={"tag_27584": "template_tests.templatetags.tag_27584"}, ) - t = engine.get_template('27584_parent.html') + t = engine.get_template("27584_parent.html") with self.assertRaises(TemplateSyntaxError) as e: t.render(Context()) if self.debug_engine: - self.assertEqual(e.exception.template_debug['during'], '{% badtag %}') + self.assertEqual(e.exception.template_debug["during"], "{% badtag %}") def test_compile_tag_error_27956(self): """Errors in a child of {% extends %} are displayed correctly.""" engine = self._engine( app_dirs=True, - libraries={'tag_27584': 'template_tests.templatetags.tag_27584'}, + libraries={"tag_27584": "template_tests.templatetags.tag_27584"}, ) - t = engine.get_template('27956_child.html') + t = engine.get_template("27956_child.html") with self.assertRaises(TemplateSyntaxError) as e: t.render(Context()) if self.debug_engine: - self.assertEqual(e.exception.template_debug['during'], '{% badtag %}') + self.assertEqual(e.exception.template_debug["during"], "{% badtag %}") def test_render_tag_error_in_extended_block(self): """Errors in extended block are displayed correctly.""" e = self._engine(app_dirs=True) - template = e.get_template('test_extends_block_error.html') + template = e.get_template("test_extends_block_error.html") context = Context() with self.assertRaises(TemplateDoesNotExist) as cm: template.render(context) if self.debug_engine: self.assertEqual( - cm.exception.template_debug['during'], + cm.exception.template_debug["during"], escape('{% include "missing.html" %}'), ) @@ -158,7 +158,7 @@ class TemplateTestMixin: #18169 -- NoReverseMatch should not be silence in block.super. """ engine = self._engine(app_dirs=True) - t = engine.get_template('included_content.html') + t = engine.get_template("included_content.html") with self.assertRaises(NoReverseMatch): t.render(Context()) @@ -168,17 +168,18 @@ class TemplateTestMixin: objects. """ engine = self._engine() - parent = engine.from_string('{% block content %}parent{% endblock %}') + parent = engine.from_string("{% block content %}parent{% endblock %}") child = engine.from_string( - '{% extends parent %}{% block content %}child{% endblock %}') - self.assertEqual(child.render(Context({'parent': parent})), 'child') + "{% extends parent %}{% block content %}child{% endblock %}" + ) + self.assertEqual(child.render(Context({"parent": parent})), "child") def test_node_origin(self): """ #25848 -- Set origin on Node so debugging tools can determine which template the node came from even if extending or including templates. """ - template = self._engine().from_string('content') + template = self._engine().from_string("content") for node in template.nodelist: self.assertEqual(node.origin, template.origin) diff --git a/tests/template_tests/urls.py b/tests/template_tests/urls.py index c9d6900baf..02d7937fe2 100644 --- a/tests/template_tests/urls.py +++ b/tests/template_tests/urls.py @@ -4,20 +4,27 @@ from . import views ns_patterns = [ # Test urls for testing reverse lookups - path('', views.index, name='index'), - re_path(r'^client/([0-9,]+)/$', views.client, name='client'), - re_path(r'^client/(?P<id>[0-9]+)/(?P<action>[^/]+)/$', views.client_action, name='client_action'), - re_path(r'^client/(?P<client_id>[0-9]+)/(?P<action>[^/]+)/$', views.client_action, name='client_action'), - re_path(r'^named-client/([0-9]+)/$', views.client2, name="named.client"), + path("", views.index, name="index"), + re_path(r"^client/([0-9,]+)/$", views.client, name="client"), + re_path( + r"^client/(?P<id>[0-9]+)/(?P<action>[^/]+)/$", + views.client_action, + name="client_action", + ), + re_path( + r"^client/(?P<client_id>[0-9]+)/(?P<action>[^/]+)/$", + views.client_action, + name="client_action", + ), + re_path(r"^named-client/([0-9]+)/$", views.client2, name="named.client"), ] urlpatterns = ns_patterns + [ # Unicode strings are permitted everywhere. - re_path(r'^Юникод/(\w+)/$', views.client2, name="метка_оператора"), - re_path(r'^Юникод/(?P<tag>\S+)/$', views.client2, name="метка_оператора_2"), - + re_path(r"^Юникод/(\w+)/$", views.client2, name="метка_оператора"), + re_path(r"^Юникод/(?P<tag>\S+)/$", views.client2, name="метка_оператора_2"), # Test urls for namespaces and current_app - path('ns1/', include((ns_patterns, 'app'), 'ns1')), - path('ns2/', include((ns_patterns, 'app'))), + path("ns1/", include((ns_patterns, "app"), "ns1")), + path("ns2/", include((ns_patterns, "app"))), ] diff --git a/tests/template_tests/utils.py b/tests/template_tests/utils.py index ad77eae1dd..2e78ec9894 100644 --- a/tests/template_tests/utils.py +++ b/tests/template_tests/utils.py @@ -6,7 +6,7 @@ from django.test.utils import override_settings from django.utils.safestring import mark_safe ROOT = os.path.dirname(os.path.abspath(__file__)) -TEMPLATE_DIR = os.path.join(ROOT, 'templates') +TEMPLATE_DIR = os.path.join(ROOT, "templates") def setup(templates, *args, test_once=False): @@ -34,9 +34,12 @@ def setup(templates, *args, test_once=False): templates["inclusion.html"] = "{{ result }}" loaders = [ - ('django.template.loaders.cached.Loader', [ - ('django.template.loaders.locmem.Loader', templates), - ]), + ( + "django.template.loaders.cached.Loader", + [ + ("django.template.loaders.locmem.Loader", templates), + ], + ), ] def decorator(func): @@ -46,7 +49,7 @@ def setup(templates, *args, test_once=False): @functools.wraps(func) def inner(self): # Set up custom template tag libraries if specified - libraries = getattr(self, 'libraries', {}) + libraries = getattr(self, "libraries", {}) self.engine = Engine( libraries=libraries, @@ -60,7 +63,7 @@ def setup(templates, *args, test_once=False): self.engine = Engine( libraries=libraries, loaders=loaders, - string_if_invalid='INVALID', + string_if_invalid="INVALID", ) func(self) func(self) @@ -98,7 +101,7 @@ class SomeClass: self.otherclass = OtherClass() def method(self): - return 'SomeClass.method' + return "SomeClass.method" def method2(self, o): return o @@ -113,9 +116,9 @@ class SomeClass: raise TypeError def __getitem__(self, key): - if key == 'silent_fail_key': + if key == "silent_fail_key": raise SomeException - elif key == 'noisy_fail_key': + elif key == "noisy_fail_key": raise SomeOtherException raise KeyError @@ -138,7 +141,7 @@ class SomeClass: class OtherClass: def method(self): - return 'OtherClass.method' + return "OtherClass.method" class TestObj: @@ -160,21 +163,23 @@ class SilentGetItemClass: class SilentAttrClass: def b(self): raise SomeException + b = property(b) class UTF8Class: "Class whose __str__ returns non-ASCII data" + def __str__(self): - return 'ŠĐĆŽćžšđ' + return "ŠĐĆŽćžšđ" # These two classes are used to test auto-escaping of string output. class UnsafeClass: def __str__(self): - return 'you & me' + return "you & me" class SafeClass: def __str__(self): - return mark_safe('you > me') + return mark_safe("you > me") diff --git a/tests/template_tests/views.py b/tests/template_tests/views.py index 4e32ada7c5..c6684b9a32 100644 --- a/tests/template_tests/views.py +++ b/tests/template_tests/views.py @@ -20,8 +20,8 @@ def client2(request, tag): def template_response_view(request): - return TemplateResponse(request, 'response.html', {}) + return TemplateResponse(request, "response.html", {}) def snark(request): - return HttpResponse('Found them!') + return HttpResponse("Found them!") |
