简体   繁体   English

如何使用request.post执行django测试?

[英]how to perform a django test with a request.post?

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. 我正在为数据提供self.client.get方法,但无法验证表单。 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. 但我似乎无法将信息提供给DriverForm。 any help will be greatly appreciated 任何帮助将不胜感激

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 . 您应该在测试中使用self.client.post(url, data) ,因为您的视图正在查找POST数据( request.POST )而不是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 我还建议重构您的视图以匹配此处给出的模板: 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 . 我对测试将数据传递给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>, ...}) . 假设您的表单包含carIDDriver_Last_Name等字段,则对self.client.get的调用应该类似于self.client.get(url, data={'carID': <id>, 'Driver_Last_Name': <driver_last_name>, ...}) The 'form' key should not be needed. 不需要'form'键。 The same goes for self.client.post . self.client.post See also here: https://docs.djangoproject.com/en/1.10/topics/testing/tools/#django.test.Client.get 另见: http//psocdddang。目录

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM