Django测试视图模板上下文

时间:2018-05-08 02:21:54

标签: django unit-testing

我试图测试

return render(request, 'template.html', context)

似乎没有达到目标。测试时不值得吗?或者如果在测试时值得,我该如何实现呢?

view.py

def create_employee_profile(request):
    name_form = EmployeeNameForm()
    context = {'name_form':name_form}
    return render(request,
                'template_create_employee_profile.html',
                context
                )

我知道if: else:语句丢失了。我并不认为它们与测试有关。

test.py

# TEST:  context({'name_form':name_form})
def test_CreateEmployeeProfileView_context(self):
    name_form = EmployeeNameForm()
    response = self.client.get(reverse(
                            'create_employee_profile'))
    self.assertEquals(response.context['name_form'], name_form)

这让我最接近成功。这是我的错误:

AssertionError: <Empl[27 chars]alid=False,
                fields=(employee_choices;first_nam[20 chars]ame)> != 
                <Empl[27 chars]alid=Unknown,
                fields=(employee_choices;first_n[22 chars]ame)>

细节视图怎么样?

# TEST:  context({'name':name})
def test_CustomerEmployeeProfileView_context(self):
    name = CustomerEmployeeName.objects.get(pk=1)
    response = self.client.get(
        reverse('service:customer_employee_profile_detail', kwargs={'pk': 1}))

    self.assertIsInstance(response.context['name'], name)

出现此错误:

TypeError: isinstance() arg 2 must be a type or tuple of types

1 个答案:

答案 0 :(得分:2)

您正在比较EmployeeNameForm的两个不同实例,这就是断言失败的原因。

如果您只想测试上下文变量确实是EmployeeNameForm,那么您可以使用assertIsInstance进行测试:

def test_CreateEmployeeProfileView_context(self):
    response = self.client.get(reverse('create_employee_profile'))
    self.assertIsInstance(response.context['name_form'], EmployeeNameForm)