質問

Im setting up a project with Google App Engine in python.

At the moment it just looks like this

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)

Im trying to learn how to work the TDD way, so i tested the get following this example by Google.

It has this test case

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

That works great and returns 200 as expected. Then i figured i should test post as well. I tried to test it like this

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

Because post is not implemented i expect it to return status 405 and the test case to report success. However the console shows this and quits

The method POST is not allowed for this resouce.

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

FAILED (errors=1)

Why does it stop there and not return the 405 to my test case? Am i doing it wrong? Is there an other(better) way to test for method not allowed codes?

役に立ちましたか?

解決

An exception is being raised for any response that is not a 2xx or 3xx status code.

You assert that it is being raised instead:

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

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

Alternatively, set expect_errors to True:

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

or tell the post method to expect a 405:

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

where AppError would be raised if the response status was not a 405. status here can be a list or tuple of statuses as well.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top