如何将模拟对象传递给自定义简单标记的单元测试?

2024-06-16 10:19:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个自定义的简单\u标记,我定义如下:

@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',所以我知道我没有正确地传递mock对象。我也尝试过传递{'user': test_customer}但没有效果

我做错什么了


Tags: testselfgetstringdefcontactphonecustomer
1条回答
网友
1楼 · 发布于 2024-06-16 10:19:58

您需要传递一个^{}实例来呈现模板。试试看

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)

相关问题 更多 >