我有一个自定义 simple_tag,定义如下:
@register.simple_tag
# usage: {% get_contact_preference_string user %}
def get_contact_preference_string(user):
if user.contact_choice == 'C':
return '{} prefers phone calls.'.format(user.first_name)
# method continues
以及一个正确加载标签并使用它的模板。
但是,我很难在单元测试中将模拟用户传递给它。这是我尝试编写测试的方式:
def test_get_contact_preference_string_returns_correctly_formatted_content(self):
test_customer = Customer.objects.create('tfirst', 'C')
template_to_render = Template(
'{% load contact_preference_helpers %}'
'{% get_contact_preference_string test_customer %}'
)
rendered = template_to_render.render(test_customer)
expected = 'tfirst prefers phone calls.'
self.assertEqual(rendered, expected)
它在点击 render(test_customer)
时引发 AttributeError: 'NoneType' object has no attribute 'contact_choice'
,所以我知道我没有传递模拟对象正确地。我还尝试过传递 {'user': test_customer}
没有效果。
我做错了什么?
最佳答案
您需要传递Context
渲染模板的实例。尝试一下
from django.template import Context, Template
...
test_customer = Customer.objects.create('tfirst', 'C')
template_to_render = Template(
'{% load contact_preference_helpers %}'
'{% get_contact_preference_string test_customer %}'
)
ctx = Context({'test_customer': test_customer})
rendered = template_to_render.render(ctx)
关于python - 如何将模拟对象传递给自定义 simple_tag 的单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55997581/