当我使用Django test.client时,我做了类似的事情:
class MyTestCase(TestCase):
def test_this(self):
c = self.client
response = c.get('/')
assert False, response.context['name']
我收到一个错误:
assert False, response.context['name']
TypeError: 'NoneType' object is unsubscriptable
我唯一的猜测就是使用Jinja2可以防止上下文在我测试时出现 .
请注意,此测试是故意操纵失败的 .
4 回答
我一直想读
TestCase
. 仔细阅读文档后,您可能会遇到错误 . 断言是TestCase
类的方法 .Django的猴子修补
Template
类覆盖render
方法,以便能够发送template_rendered
信号并填充response.context
.如果您挖掘代码,您将能够为Jinja2的Template类执行此操作 .
我已经完成了@Rho建议的方式(在页面加载测试文件的开头)
然后你可以选择响应上下文和模板名称(但是在这种情况下response.template不是列表)而不是
response.template[0].name
你需要使用response.template.name
.Jinja设置context_data变量,而不是上下文: