简体   繁体   English

如何测试 Django 自定义过滤器?

[英]How to test a Django custom filter?

This question is similar to Testing a custom Django template filter , but unlike in that example, the filter is actually defined in a module in the templatetags directory as described in https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/#writing-custom-template-filters .此问题类似于测试自定义 Django 模板过滤器,但与该示例不同的是,过滤器实际上是在templatetags目录中的模块中定义的,如https://docs.djangoproject.com/en/2.0/howto/custom 中所述-template-tags/#writing-custom-template-filters Here is the filter code in templatetags/label_with_classes.py :这是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})

Here is my first stab at a test for it:这是我对它的第一次测试:

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)

The problem is that I get an error that the filter was not found:问题是我收到一个错误,提示找不到过滤器:

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

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 https://github.com/django/django/blob/master/tests/template_tests/filter_tests/test_join.py , there is an elaborate setup decorator which provides the test class with a self.engine whose render_to_string method has the required filters already installed.似乎在 Django 源代码中,例如https://github.com/django/django/blob/master/tests/template_tests/filter_tests/test_join.py ,有一个精心设计的setup装饰器,它为测试类提供了self.enginerender_to_string方法已经安装了所需的过滤器。

Do I basically have to copy the Django source code to write an integration-style test for my custom filter?我基本上必须复制 Django 源代码来为我的自定义过滤器编写集成样式的测试吗? Or is there a simpler way (besides just testing it as a function)?还是有更简单的方法(除了将其作为函数进行测试之外)?

I suspect you need to load your template module:我怀疑您需要加载模板模块:

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

See the relevant documentation .请参阅相关文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM