Search code examples
djangodjango-testing

Smartest way to test a view if form.is_valid?


Searching for a good way to test a part of a view that belongs to valid form:

Views.py:

def calendar_request(request):
    form = create_event(request.POST)
    if form.is_valid():
         date = request.POST['date']
         time = request.POST['time']
         return HttpResponseRedirect(request.path)
    else:
         print('Form not valid')

So I checked if the form is valid in my tests.py:

 def test_form_valid_request(self):
    date = '2019-04-16'
    time = '14:00'
    form_data = {'date':date,
                 'time':time,}
    form = create_event(data=form_data)
    self.assertTrue(form.is_valid)

This worked pretty good. So I continued by adding these lines to my test function:

   response = client.get(reverse('test_form'), form_data)
   self.assertEqual(response.status_code, 200)

What confuses me is that AssertTrue(form.is_valid) works while testing, but in my console I get always the print ('Form not valid').

How can I test the part in my view if the form.is_valid?


Solution

  • The assertTrue(expr, msg=None) checks bool(x) is True, not x is True

    So, You should have call the function (use paranthesis)

    self.assertTrue(form.is_valid())
                                 ^^ here