【问题标题】:How to test a Django custom filter?如何测试 Django 自定义过滤器?
【发布时间】:2018-07-31 12:54:54
【问题描述】:

此问题与Testing a custom Django template filter 类似,但与该示例不同的是,过滤器实际上是在templatetags 目录中的一个模块中定义的,如https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/#writing-custom-template-filters 中所述。这是templatetags/label_with_classes.py中的过滤器代码:

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})

这是我对它的第一次测试:

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)

问题是我得到一个过滤器未找到的错误:

django.template.exceptions.TemplateSyntaxError: Invalid filter: 'label_with_classes'

这是因为测试用例没有模仿注册过滤器并将其加载到模板中的行为。似乎在 Django 源代码中,例如https://github.com/django/django/blob/master/tests/template_tests/filter_tests/test_join.py,有一个精心设计的setup 装饰器,它为测试类提供了一个self.engine,其render_to_string 方法已经安装了所需的过滤器。

我基本上必须复制 Django 源代码来为我的自定义过滤器编写集成式测试吗?还是有更简单的方法(除了将其作为函数进行测试)?

【问题讨论】:

    标签: python django django-templates django-testing


    【解决方案1】:

    我怀疑你需要加载你的模板模块:

    ...
    template = Template("""{% load label_with_classes %}
    {{ form.session_number|label_with_classes }}""")
    ...
    

    请参阅relevant documentation

    【讨论】:

      猜你喜欢
      • 2011-05-28
      • 1970-01-01
      • 1970-01-01
      • 2016-07-01
      • 1970-01-01
      • 2018-01-27
      • 1970-01-01
      • 1970-01-01
      • 2017-04-18
      相关资源
      最近更新 更多