Django Test Client post()返回302,尽管视图的帖子()有错误

lim*_*to0 14 python testing django post http-status-code-404

我目前正在编写一些基本测试,以确保中型Django应用程序中的页面正确地进行GET和POST.但是,使用django.test.client.Client时应该不会可靠地失败.即使我的代码中存在明显错误,它也会返回302响应.

在我的app/urls.py中:

url(r'^mymodel/create/$', 
views.MyModelView.as_view(),
name = 'my_model_create'),
Run Code Online (Sandbox Code Playgroud)

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

class MyModelCreateView(MyModelView, CreateView):

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

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

甚至还用"打印self.hello"取代了

return HttpResponse(status = 500)
Run Code Online (Sandbox Code Playgroud)

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

#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
Run Code Online (Sandbox Code Playgroud)

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

有没有人知道这里可能存在什么问题?作为参考,我使用的是Python 2.7和Django 1.5(尽管我可能需要与Django 1.4兼容).

Ham*_*ish 21

目前还不完全清楚你为什么要获得重定向,但是如果你想要遵循它,你需要告诉你RequestClient遵循重定向 - 根据文档:

如果设置followTrue客户端将遵循任何重定向,并且 redirect_chain将在包含中间URL和状态代码的元组的响应对象中设置属性.

所以你的测试代码应如下所示:

python response = client.post("/app/mymodel/create/", follow=True)

值得检查请求链以查看其确切路由的位置.