[英]How to test a Django custom filter?
此問題類似於測試自定義 Django 模板過濾器,但與該示例不同的是,過濾器實際上是在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 源代碼來為我的自定義過濾器編寫集成樣式的測試嗎? 還是有更簡單的方法(除了將其作為函數進行測試之外)?
我懷疑您需要加載模板模塊:
...
template = Template("""{% load label_with_classes %}
{{ form.session_number|label_with_classes }}""")
...
請參閱相關文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.