首页 > 解决方案 > 如何将模拟对象传递给自定义 simple_tag 的单元测试?

问题描述

我有一个自定义的 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)

AttributeError: 'NoneType' object has no attribute 'contact_choice'在点击时上升render(test_customer),所以我知道我没有正确传递模拟对象。我也试过传递{'user': test_customer}没有效果。

我究竟做错了什么?

标签: pythondjangodjango-templatespytest

解决方案


您需要传递一个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)

推荐阅读