summaryrefslogtreecommitdiff
path: root/tests/template_tests/syntax_tests/test_basic.py
diff options
context:
space:
mode:
authorFabian Braun <fsbraun@gmx.de>2024-09-16 22:05:33 +0200
committerSarah Boyce <42296566+sarahboyce@users.noreply.github.com>2024-09-17 09:52:44 +0200
commitd2c97981fb40e0b324b064cd3561de8f5f1887b2 (patch)
treef00654e591cd1ba878e79648f985f2a655028d88 /tests/template_tests/syntax_tests/test_basic.py
parent8b9a2bf34e132ccf0ab0a074440dc55f90c76598 (diff)
Fixed #35735 -- Enabled template access to methods and properties of classes with __class_get_item__.
Diffstat (limited to 'tests/template_tests/syntax_tests/test_basic.py')
-rw-r--r--tests/template_tests/syntax_tests/test_basic.py46
1 files changed, 46 insertions, 0 deletions
diff --git a/tests/template_tests/syntax_tests/test_basic.py b/tests/template_tests/syntax_tests/test_basic.py
index 20bf30d55c..50e7a4c7b1 100644
--- a/tests/template_tests/syntax_tests/test_basic.py
+++ b/tests/template_tests/syntax_tests/test_basic.py
@@ -346,6 +346,52 @@ class BasicSyntaxTests(SimpleTestCase):
output = self.engine.render_to_string("tpl-weird-percent")
self.assertEqual(output, "% %s")
+ @setup(
+ {"template": "{{ class_var.class_property }} | {{ class_var.class_method }}"}
+ )
+ def test_subscriptable_class(self):
+ class MyClass(list):
+ # As of Python 3.9 list defines __class_getitem__ which makes it
+ # subscriptable.
+ class_property = "Example property"
+ do_not_call_in_templates = True
+
+ @classmethod
+ def class_method(cls):
+ return "Example method"
+
+ for case in (MyClass, lambda: MyClass):
+ with self.subTest(case=case):
+ output = self.engine.render_to_string("template", {"class_var": case})
+ self.assertEqual(output, "Example property | Example method")
+
+ @setup({"template": "{{ meals.lunch }}"})
+ def test_access_class_property_if_getitem_is_defined_in_metaclass(self):
+ """
+ If the metaclass defines __getitem__, the template system should use
+ it to resolve the dot notation.
+ """
+
+ class MealMeta(type):
+ def __getitem__(cls, name):
+ return getattr(cls, name) + " is yummy."
+
+ class Meals(metaclass=MealMeta):
+ lunch = "soup"
+ do_not_call_in_templates = True
+
+ # Make class type subscriptable.
+ def __class_getitem__(cls, key):
+ from types import GenericAlias
+
+ return GenericAlias(cls, key)
+
+ self.assertEqual(Meals.lunch, "soup")
+ self.assertEqual(Meals["lunch"], "soup is yummy.")
+
+ output = self.engine.render_to_string("template", {"meals": Meals})
+ self.assertEqual(output, "soup is yummy.")
+
class BlockContextTests(SimpleTestCase):
def test_repr(self):