Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform a Django test with a request.post?

I'm using Django 1.8 and Python 3.5.

I have 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?

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 that this test works because it gets the response. But the line that is commented out is what I want to use.

However, I cant seem to feed the information to the DriverForm. Any help will be greatly appreciated.

like image 314
Blue Avatar asked Mar 06 '17 14:03

Blue


1 Answers

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

like image 106
Martin Bierbaum Avatar answered Sep 21 '22 23:09

Martin Bierbaum