Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test custom template tags in Django?

I'm adding a set of template tags to a Django application and I'm not sure how to test them. I've used them in my templates and they seem to be working but I was looking for something more formal. The main logic is done in the models/model managers and has been tested. The tags simply retrieve data and store it in a context variable such as

{% views_for_object widget as views %} """ Retrieves the number of views and stores them in a context variable. """ # or {% most_viewed_for_model main.model_name as viewed_models %} """ Retrieves the ViewTrackers for the most viewed instances of the given model. """ 

So my question is do you typically test your template tags and if you do how do you do it?

like image 641
Mark Lavin Avatar asked Nov 06 '09 14:11

Mark Lavin


People also ask

How do I create a custom tag in Django?

Create a custom template tagUnder the application directory, create the templatetags package (it should contain the __init__.py file). For example, Django/DjangoApp/templatetags. In the templatetags package, create a . py file, for example my_custom_tags, and add some code to it to declare a custom tag.

What is Django template tags?

Django Code The template tags are a way of telling Django that here comes something else than plain HTML. The template tags allows us to to do some programming on the server before sending HTML to the client. template.html : <ul> {% for x in mymembers %} <li>{{ x. firstname }}</li> {% endfor %} </ul> Run Example »


1 Answers

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) 
like image 79
Gregor Müllegger Avatar answered Sep 29 '22 12:09

Gregor Müllegger