【发布时间】:2014-11-05 17:53:28
【问题描述】:
我正在 django 中开发一个 Web 应用程序,它使用表单 POST 将用户输入的数据放入数据库。
问题: 在 django.test.TestCase 中使用 self.client.post() 进行测试返回 405(不允许请求)。
排除:
- POST 不允许 - 应用程序在运行时成功发布(而不是在运行 tests.py 时)。
- CSRF 问题 - django.test.TestCase 在运行测试时默认禁用 CSRF 身份验证。
- 一般测试失败 - 我有几个使用 self.client.get() 可以正常工作的测试
问题: 当我期望 302(重定向)时,可能导致 405 的原因是什么?
这是以这种方式失败的测试之一:
def test_process_one_match_in_title(self):
#TODO: the server is refusing self.client.post requests in testing, although they work in the app proper. Why?
#create a user and an abstract
this_abstract = Abstract.objects.get(pk=5) #'hypoplasia' in both title and abstract text
this_annotator = create_annotator("Joe")
this_annotator.save()
userMatchesJSON = "{'hypoplasia': 8}"
resp = self.client.post(reverse('diseaseMatcherApp:abstractDetail', kwargs={'pk': this_abstract.id}),
{'inputSoFar': 'hypoplasia', 'abstract_pk': this_abstract.id, 'user.id': this_annotator.id,
'userMatches': userMatchesJSON})
self.assertEqual(resp.status_code, 302) #FAILS HERE; AssertionError: 405 != 302
【问题讨论】:
-
你发帖的网址是什么?
-
@ChrisHawkes 这是表单调用:
-
我只是好奇,因为您说一个应用程序在发布帖子时可以工作,而另一个则不能。我建议两者都发布到该网站的完整网址。 yoursite.com/post_form 可能是 url 是相对的,而不是完全限定的 url。
-
它实际上不是 2 个应用程序 - 它只是应用程序本身(通过浏览器体验)和该应用程序的测试套件(在 tests.py 中)。相同的页面,相同的表格。我猜在技术上不同的服务器 - 127.0.0.1:8000 与系统创建的 TestServer。但我不明白这是怎么回事,使用 reverse() 来解析 URL。
-
是的,我同意。我不太熟悉为什么测试服务器不能工作。我想知道这是否是浏览器问题,它没有让请求被发出,但我只是在猜测那里,希望有人解决了类似的问题并可以参与进来。
标签: python django post http-status-code-405