测试HTTP 405不允许

时间:2014-02-17 13:08:52

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

我在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代码?

1 个答案:

答案 0 :(得分:5)

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,则会引发AppErrorstatus此处也可以是状态列表或元组。