python - 如何将模拟对象传递给自定义 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}
没有效果。
我究竟做错了什么?
解决方案
您需要传递一个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)
推荐阅读
- parquet - 如何使用 pyarrow 更改列数据类型
- javascript - 如何覆盖js方法?
- css - 当我们可以通过水平和垂直偏移增加阴影大小时,spread-radius 有什么用?
- android - 从 Android DataStore 检索数据并保存到全局变量
- java - 如何将 char 序列替换为 "\n"
- java - 如何将一个包中的类导入另一个包中的另一个类?
- python - 以表格形式打印的 csv 文件内容
- python - 如何从不同的目录中选择每 20 个文件,Python?
- python - aioredis 任务已销毁,但处于待处理状态
- html - 登录:1 GET http://localhost:3000/manifest.webmanifest 404(未找到)