python - 如何将模拟对象传递给自定义 simple_tag 的单元测试?

标签 python django django-templates pytest

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

相关文章:

django - 将Django的额外字段添加到Django身份验证组

python - django模板for循环某些表行仅显示一次

python - 在 Python 中验证名称的最佳方法

python - 如何在 Python 中使用 aiohttp 或 asyncio 创建并行循环?

django - 如何在 Django 中跨应用程序/项目注册 celery 任务?

python - Django 从 postgresql 数据库填充下拉菜单的完整示例

python - Django:如何在我的模板中有效显示数据?

python - 为什么从一个 ndarray 复制到另一个 ndarray 内存消耗?

python - Pandas 根据列的值有效地分块读取大型面板 CSV

python - 在 Django 中获取查询对象的外键值