Ticket #16307: 16307_test_callable_variable_attribute_parsing.diff

File 16307_test_callable_variable_attribute_parsing.diff, 2.3 KB (added by Enrico, 13 years ago)

Tests and fix for accessing attributes on callables and classes

  • django/template/base.py

    diff --git a/django/template/base.py b/django/template/base.py
    index 49ef0b8..306f549 100644
    a b class Variable(object):  
    690690                                TypeError,  # unsubscriptable object
    691691                                ):
    692692                            raise VariableDoesNotExist("Failed lookup for key [%s] in %r", (bit, current)) # missing attribute
    693                 if callable(current):
     693                if callable(current) and not isinstance(current, type):
    694694                    if getattr(current, 'alters_data', False):
    695695                        current = settings.TEMPLATE_STRING_IF_INVALID
    696696                    else:
  • tests/regressiontests/templates/parser.py

    diff --git a/tests/regressiontests/templates/parser.py b/tests/regressiontests/templates/parser.py
    index 1609c67..a800fd6 100644
    a b class ParserTests(TestCase):  
    8181        self.assertRaises(TemplateSyntaxError,
    8282            Variable, "article._hidden"
    8383        )
     84
     85    def test_callable_variable_attribute_parsing(self):
     86        # Test for ticket https://code.djangoproject.com/ticket/16307
     87
     88        # Classes shouldn't be treated as callables.
     89        # Using a required argument to force a failure when calling.
     90
     91        # Class methods and static methods should get called normally.
     92        class SomeClass(object):
     93            verbose_name = "Some Class"
     94
     95            def __init__(self, required_arg):
     96                pass
     97
     98            @classmethod
     99            def class_method(cls):
     100                return 'class method'
     101
     102            @staticmethod
     103            def static_method():
     104                return 'static method'
     105
     106        # A simple function should get called normally
     107        def some_function():
     108            return {"verbose_name": "some function"}
     109
     110        c = {"some_class": SomeClass, "some_function": some_function}
     111
     112        self.assertEqual(Variable("some_class.verbose_name").resolve(c), "Some Class")
     113        self.assertEqual(Variable("some_class.class_method").resolve(c), "class method")
     114        self.assertEqual(Variable("some_class.static_method").resolve(c), "static method")
     115        self.assertEqual(Variable("some_function.verbose_name").resolve(c), "some function")
     116
Back to Top