title: How to test a Django custom filter?
body: <p>This question is similar to <a href="https://stackoverflow.com/questions/4496109/testing-a-custom-django-template-filter">Testing a custom Django template filter</a>, but unlike in that example, the filter is actually defined in a module in the <code>templatetags</code> directory as described in <a href="https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/#writing-custom-template-filters" rel="nofollow noreferrer">https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/#writing-custom-template-filters</a>. Here is the filter code in <code>templatetags/label_with_classes.py</code>:</p>
  
  <pre><code>from django import template
  
  register = template.Library()
  
  
  @register.filter(is_safe=True)
  def label_with_classes(bound_field):
      classes = f"{'active' if bound_field.value() else ''} {'invalid' if bound_field.errors else ''}"
      return bound_field.label_tag(attrs={'class': classes})
  </code></pre>
  
  <p>Here is my first stab at a test for it:</p>
  
  <pre><code>from ..templatetags.label_with_classes import label_with_classes
  from django.test import SimpleTestCase
  from django.template import Context, Template
  
  
  from ..forms.sessions import SessionForm
  
  
  class CustomFilterTest(SimpleTestCase):
      def test_1(self):
          form = SessionForm(data={})
          self.assertFalse(form.is_valid())
          self.assertEqual(
              form.errors,
              {'session_number': ['This field is required.'],
               'family': ['This field is required.'],
               'session_type': ['This field is required.']})
  
  
          template = Template('{{ form.session_number|label_with_classes }}')
          context = Context({'form': form})
  
          output = template.render(context)
  </code></pre>
  
  <p>The problem is that I get an error that the filter was not found:</p>
  
  <pre><code>django.template.exceptions.TemplateSyntaxError: Invalid filter: 'label_with_classes'
  </code></pre>
  
  <p>This is because the test case doesn't mimic the behavior of registering the filter and loading it in the template. It seems like in the Django source code, for example <a href="https://github.com/django/django/blob/master/tests/template_tests/filter_tests/test_join.py" rel="nofollow noreferrer">https://github.com/django/django/blob/master/tests/template_tests/filter_tests/test_join.py</a>, there is an elaborate <code>setup</code> decorator which provides the test class with a <code>self.engine</code> whose <code>render_to_string</code> method has the required filters already installed.</p>
  
  <p>Do I basically have to copy the Django source code to write an integration-style test for my custom filter? Or is there a simpler way (besides just testing it as a function)?</p>