Search code examples
djangopython-3.xunit-testingview

How do I verify in a Django unit test that my context contains a form object?


I'm using Django and Python 3.7. I have this view ...

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)

I want to write some kind of assertion in my unit test that verifies the model contains my form object. How do I do that? So far I have

# 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")

Solution

  • The response has a context attribute that contains the context used to render the template.

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