【问题标题】:Test for HTTP 405 Not allowed测试 HTTP 405 不允许
【发布时间】:2014-02-17 13:08:52
【问题描述】:

我在 python 中使用 Google App Engine 建立一个项目。

目前看起来是这样的

class MainPage(webapp2.RequestHandler):

def get(self):
    self.response.headers['Content-Type'] = 'text/plain'
    self.response.write('Hello World!')

application = webapp2.WSGIApplication([
    ('/', MainPage),
], debug=True)

我正在尝试学习如何以 TDD 方式工作,因此我在 Google 的 this 示例之后测试了 get

有这个测试用例

def test_MainPage_get(self):
    response = self.testapp.get('/')
    self.assertEqual(response.status_int, 200)

效果很好,并按预期返回 200。然后我想我也应该测试post。我试着像这样测试它

def test_MainPage_post(self):
    response = self.testapp.post('/')
    self.assertEqual(response.status_int, 405)

因为 post 未实现,我希望它返回状态 405 和测试用例报告成功。但是控制台显示并退出

The method POST is not allowed for this resouce.

------------------------------------------------
Ran 2 tests in 0.003s

FAILED (errors=1)

为什么它停在那里而不将 405 返回到我的测试用例?我做错了吗?还有其他(更好的)方法来测试method not allowed 代码吗?

【问题讨论】:

  • 这大概是用WebTest?
  • @Martijn 是的,忘了说

标签: python unit-testing http google-app-engine webtest


【解决方案1】:

exception is being raised 表示任何不是 2xx 或 3xx 状态代码的响应。

您断言它正在被提升:

def test_MainPage_post(self):
    with self.assertRaises(webtest.AppError) as exc:
        response = self.testapp.post('/')

    self.assertTrue(str(exc).startswith('Bad response: 405')

或者,将expect_errors 设置为True

def test_MainPage_post(self):
    response = self.testapp.post('/', expect_errors=True)
    self.assertEqual(response.status_int, 405)

或告诉post 方法期待 405:

def test_MainPage_post(self):
    response = self.testapp.post('/', status=405)

如果响应状态不是 405,则会引发 AppError。这里的status 也可以是状态列表或元组。

【讨论】:

  • 感谢您的链接。我使用了您的第二个建议,因为它更适合我当前的代码并且可以正常工作
  • @TimCastelijns:为您添加了一个选项。
猜你喜欢
  • 1970-01-01
  • 2014-06-22
  • 2018-12-20
  • 2016-08-05
  • 2016-03-08
  • 2015-07-22
  • 2011-06-21
  • 2017-06-15
  • 1970-01-01
相关资源
最近更新 更多