38👍
This is a short passage of one of my test files, where self.render_template a simple helper method in the TestCase is:
rendered = self.render_template(
'{% load templatequery %}'
'{% displayquery django_templatequery.KeyValue all() with "list.html" %}'
)
self.assertEqual(rendered,"foo=0\nbar=50\nspam=100\negg=200\n")
self.assertRaises(
template.TemplateSyntaxError,
self.render_template,
'{% load templatequery %}'
'{% displayquery django_templatequery.KeyValue all() notwith "list.html" %}'
)
It is very basic and uses blackbox testing. It just takes a string as template source, renders it and checks if the output equals the expected string.
The render_template
method is quite simplistic:
from django.template import Context, Template
class MyTest(TestCase):
def render_template(self, string, context=None):
context = context or {}
context = Context(context)
return Template(string).render(context)
22👍
You guys got me on the right track. It’s possible to check that the context was correctly changed after the render:
class TemplateTagsTestCase(unittest.TestCase):
def setUp(self):
self.obj = TestObject.objects.create(title='Obj a')
def testViewsForOjbect(self):
ViewTracker.add_view_for(self.obj)
t = Template('{% load my_tags %}{% views_for_object obj as views %}')
c = Context({"obj": self.obj})
t.render(c)
self.assertEqual(c['views'], 1)
- [Django]-Django: order by position ignoring NULL
- [Django]-Filter by property
- [Django]-Django: permission denied when trying to access database after restore (migration)
- [Django]-Django admin ManyToMany inline "has no ForeignKey to" error
- [Django]-Django: Get list of model fields?
- [Django]-Django release 1.5: 'url' requires a non-empty first argument. The syntax changed in Django 1.5
0👍
Strings can be rendered as templates, so you could write a test that includes a simple ‘template’ using your templatetag as a string and just make sure it renders correctly given a certain context.
- [Django]-Making django server accessible in LAN
- [Django]-Inject errors into already validated form?
- [Django]-How to have a Python script for a Django app that accesses models without using the manage.py shell?
0👍
When I was testing my template tags, I would have the tag, itself, return a string containing the text or dict I was working with … sort of along the lines of the other suggestion.
Since tags can modify the context and/or return a string to be rendered — I found it was fastest just to view the rendered string.
Instead of:
return ''
Have it:
return str(my_data_that_I_am_testing)
Until you are happy.
- [Django]-Mac OS X – EnvironmentError: mysql_config not found
- [Django]-Django : Unable to import model from another App
- [Django]-Django contrib admin default admin and password