chris Frisina
chris Frisina

Reputation: 19688

test a custom template tag filter in django

To use a template filter like so in a sample_template.html :

{% load truck_filters %}
<div data-toggle="tooltip" data-placement="bottom" data-ten-condition='{{model.0|tenRange}}'>{{model.0}}</div>
# would render
<div data-toggle="tooltip" data-placement="bottom" data-ten-condition='0'>10</div>

I have an app_filter.py in a folder templatetags in the app:

from django import template
register = template.Library()

@register.filter(name='tenRange')
def tenRange(numberString):
  # If it is blank
  if numberString == '':
    return -1
  number = int(numberString)
  lowerLimit  = 3
  mediumLimit = 5
  medium2Limit = 8
  newLimit  = 10
  if number < -1:
    return -2
  elif 0 <= number and number < lowerLimit:
    return 3
  elif lowerLimit <= number and number < mediumLimit:
    return 2
  elif mediumLimit <= number and number <= medium2Limit:
    return 1
  elif medium2Limit <= number and number <= newLimit:
    return 0
  # If above the new limit
  elif number > newLimit:
    return -1
  # If there is an error
  else:
    return -1

How would I [unit?] test the conditions (with different ints, variable types, etc...) in test_template_tags.py in the tests folder?

My current limited understanding... I can't seem to find a good working example, and the docs hint at rendering a template with a specific context. I'm not sure that is required, but if it is (convention), then can you please help provide how to provide a template and context? (is it the same as rendering it from the view?, if so, how do you just find the one portion that I am trying to test without bloating the other required variables to be rendered?)

Upvotes: 0

Views: 1284

Answers (1)

solarissmoke
solarissmoke

Reputation: 31414

You can just test the function itself, directly:

from django.test import TestCase

from myproject.myapp.templatetags.app_filter import tenRange

class tenRangeTestCase(TestCase):

    def test_blank_string(self):
        result = tenRange("")
        self.assertEqual(result, -1)

    def test_input_smaller_than_minus_one(self):
        result = tenRange(-15)
        self.assertEqual(result, -2)

    # etc for your other conditions.

I don't think you need to render a template in order to test your filter logic. Django already has well-tested template rendering logic, which the unit-tests for your filter shouldn't have to worry about since the "job" done by your filter is not to render to a template, but to take an input and return an output.

Upvotes: 2

Related Questions