Permalink
Browse files

Add tests for getattribute template tag.

  • Loading branch information...
1 parent 97a924f commit 87d8fc69c2d93af1c7c9a09ae0947ed7c17d2e52 @Osmose Osmose committed May 30, 2012
Showing with 42 additions and 7 deletions.
  1. +2 −7 apps/homesnippets/templatetags/getattribute.py
  2. +40 −0 apps/homesnippets/tests/test_templatetags.py
@@ -1,19 +1,14 @@
-import re
from django import template
from django.conf import settings
-numeric_test = re.compile("^\d+$")
+
register = template.Library()
+
def getattribute(value, arg):
"""Gets an attribute of an object dynamically from a string name"""
-
if hasattr(value, str(arg)):
return getattr(value, arg)
- elif hasattr(value, 'has_key') and value.has_key(arg):
- return value[arg]
- elif numeric_test.match(str(arg)) and len(value) > int(arg):
- return value[int(arg)]
else:
return settings.TEMPLATE_STRING_IF_INVALID
@@ -1,3 +1,6 @@
+from collections import namedtuple
+
+from django.conf import settings
from django.template import Context
from django.template.loader import get_template_from_string
from django.test import TestCase
@@ -25,3 +28,40 @@ def test_basic(self):
eq_(result, 'Nyan [Nyan] {{Nyan}} {{{Nyan}}}',
"Single brackets should' be preserved, but double and triple "
"brackets should be replaced.")
+
+
+class TestGetAttribute(TestCase):
+ def setUp(self):
+ """Create empty context to render test templates with."""
+ self.context = Context()
+
+ def test_basic(self):
+ """Test if getattribute can retrieve an object attribute."""
+ Point = namedtuple('Point', ['x', 'y'])
+ self.context['p'] = Point(4, 5)
+
+ template_str = """
+ {% load getattribute %}
+ {{ p|getattribute:'x' }}
+ """
+ template = get_template_from_string(template_str)
+ result = template.render(self.context).strip()
+
+ eq_(result, '4')
+
+ def test_nonexistant_attribute_returns_invalid(self):
+ """
+ If the requested attribute doesn't exist, return the invalid template
+ string.
+ """
+ Point = namedtuple('Point', ['x', 'y'])
+ self.context['p'] = Point(4, 5)
+
+ template_str = """
+ {% load getattribute %}
+ {{ p|getattribute:'q' }}
+ """
+ template = get_template_from_string(template_str)
+ result = template.render(self.context).strip()
+
+ eq_(result, settings.TEMPLATE_STRING_IF_INVALID)

0 comments on commit 87d8fc6

Please sign in to comment.