您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python – Django Test Client post()返回302,尽管视图的帖子()

5b51 2022/1/14 8:22:54 python 字数 2369 阅读 591 来源 www.jb51.cc/python

我正在编写一些基本测试,以确保中等大小的Django应用程序中的页面正确获取和POST.但是,使用 django.test.client.Client不可靠地失败.即使在我的代码中存在明显的错误,它也会返回302响应. 在我的app / urls.py中: url(r'^mymodel/create/$', views.MyModelView.as_view(), name = 'my_mode

概述

在我的app / urls.py中:

url(r'^mymodel/create/$',views.MyModelView.as_view(),name = 'my_model_create'),

然后,为了有意创造500响应,我做了以下:

class MyModelCreateView(MyModelView,CreateView):

    def post(self,request,*args,**kwargs):
        print self.hello
        self.object = MyModel()
        return super(MyModelCreateView,self).post(request,**kwargs)

显然,该视图没有任何名为hello的对象.尝试通过浏览器发送请求时,会如预期的那样失败.

甚至更换“print self.hello”

return HttpResponse(status = 500)

然而,我仍然得到以下内容

#We have a model called Client,so it 
#is imported as RequestClient to avoid conflicts
In [1]: from django.test.client import Client as RequestClient

In [2]: client = RequestClient()

In [3]: response = client.post("/app/mymodel/create/")

In [4]: response.status_code
Out[4]: 302

显然,这里的问题是在键盘和椅子之间,因为没有任何理由如果完成正确,Client()/ RequestClient()不应该返回500错误.即使出现一些问题,因为我收到了302个POST请求的响应,而不是200个响应,但这可能是因为我们使用HttpRedirect.

有谁在那里知道这里可能有什么问题吗?作为参考,我在Python 2.7和Django 1.5(虽然我可能需要与Django 1.4兼容).

If you set follow to True the client will follow any redirects and a
redirect_chain attribute will be set in the response object containing
tuples of the intermediate urls and status codes.

所以你的测试代码应该是:

Python
response = client.post(“/ app / mymodel / create /”,follow = True)

这是值得检查的请求链,以查看它在哪里路由.

总结

以上是编程之家为你收集整理的python – Django Test Client post()返回302,尽管视图的帖子()全部内容,希望文章能够帮你解决python – Django Test Client post()返回302,尽管视图的帖子()所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶