Django 测试 View 模板上下文

标签 django unit-testing

我正在尝试测试

返回渲染(请求,'template.html',上下文)

而且似乎还不够。难道不值得测试一下吗?或者如果值得对此进行测试,我该如何实现?

查看.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: 语句。我认为它们与测试无关。

测试.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)>

详细 View 怎么样?

# 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

最佳答案

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

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

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

关于Django 测试 View 模板上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50224863/

相关文章:

python - Django 循环遍历所有项目来保存,但它只保存一条记录

c# - Visual Studio 2010 单元测试-断言失败后有什么方法可以继续 TestMethod 吗?

c# - 多个 AppDomains : Keeping the Console Open

ios - 每次运行单元测试时如何运行应用程序的全新安装?

python - 在 Django 中构建动态表单

python - postgis 距离函数和 google maps 距离计算器结果之间存在明显差异的原因是什么?

python - 您有 3 个未应用的迁移。在您为应用程序 : admin, auth 应用迁移之前,您的项目可能无法正常工作

django - 如何获取序列化器内的序列化器字段值

angular - Angular 单元测试中的错误 TypeError 和错误上下文 DebugContext_ - 模板产生错误

c# - 测试 MVC Controller 操作 HttpAcceptAttribute 动词