gpt4 book ai didi

python - Django 测试客户端 post() 返回 302,尽管 View 的 post() 出错

转载 作者:太空狗 更新时间:2023-10-29 17:27:50 25 4
gpt4 key购买 nike

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

在我的 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, *args, **kwargs)

显然, View 没有任何名为 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 错误。当我收到 POST 请求的 302 个响应而不是 200 个响应时,甚至会出现一些问题,但这可能是因为我们使用的是 HttpRedirect。

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

最佳答案

目前还不完全清楚您为什么会收到重定向,但如果您想遵循它,您需要告诉 RequestClient 遵循重定向 - 根据 the documentation :

If you set follow to True the client will follow any redirects and aredirect_chain attribute will be set in the response object containingtuples of the intermediate urls and status codes.

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

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

检查请求链以查看它的确切路由位置是值得的。

关于python - Django 测试客户端 post() 返回 302,尽管 View 的 post() 出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17352314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com