如何在Django单元测试中验证我的上下文包含表单对象?

时间:2019-05-08 20:27:17

标签: django python-3.x unit-testing view

我正在使用Django和Python 3.7。我有这种看法...

def get(request):
    context = {}
    if not request.GET:
        tax_calculator_form = TaxCalculatorForm()
    else:
        ...

    context['form'] = tax_calculator_form
    return render(request, "tax_calculator.html", context)

我想在单元测试中编写某种断言,以验证模型是否包含我的表单对象。我怎么做?到目前为止,我有

# Simple test to verify we can get the tax form
def test_get_tax_form(self):
    response = self.client.get("/form")
    self.assertEqual(response.status_code, 200)
    self.assertTemplateUsed(response, "tax_calculator.html")

1 个答案:

答案 0 :(得分:1)

响应的context attribute包含用于呈现模板的上下文。

self.assertIn('form', response.context)