how to perform a django test with a request.post?

Blue picture Blue · Mar 6, 2017 · Viewed 15.9k times · Source

ive got a view method i would love to test. i am supplying the self.client.get method with the data but it fails to validate the form. what am i doing wrong?

using django 1.8
python 3.5

this is the view method

def saveNewDriverInfo(request):
    if  request.user.is_authenticated():
        form = DriverForm(request.POST)  
        if  form.is_valid():
            new_Driver = form.save()
            carid = form.cleaned_data['carID']
            Car = get_object_or_404(Car, pk=carid)
            return redirect('carmanager:carDetails', carID=carid
        else:
            return HttpResponse("something went wong some where! yes i said wong!")

this is the test method

 def test_saveNewDriverInfo(self):
            self.client.login(username="testuser",password="testuser321")
response= self.client.get(reverse('carmanager:saveNewDriverInfo'),data={'form':{'carID':'1034567','Driver_Last_Name':'daddy','Driver_First_Name':'daddy','Driver_Middle_Initial':'K','entered_by':'king'}})
            #self.assertRedirects(response, expected_url, status_code, target_status_code, host, msg_prefix, fetch_redirect_response)

            self.assertNotContains(response, 'something went wrong' ,200)

also note this test work cause it gets the response is what i got. but the line that is commented is what i want to use

But i cant seem to feed the information to the DriverForm. any help will be greatly appreciated

Answer

Martin Bierbaum picture Martin Bierbaum · Mar 6, 2017

You should use self.client.post(url, data) in your test, since your view is looking for the POST data (request.POST) and not for request.GET.

I'd also suggest to refactor your view to match the template given here: https://docs.djangoproject.com/en/1.10/topics/forms/#the-view

I am a little confused by the way your test passes data to self.client.get. Assuming your form has the fields carID, Driver_Last_Name, etc, the call to self.client.get should look like self.client.get(url, data={'carID': <id>, 'Driver_Last_Name': <driver_last_name>, ...}). The 'form' key should not be needed. The same goes for self.client.post. See also here: https://docs.djangoproject.com/en/1.10/topics/testing/tools/#django.test.Client.get