I'm struggling on how to setup my environment for TDD with Google App Engine - Python. (I'm also pretty new to Python). My environment is as follows:
- Google App Engine 1.5.0
- IntelliJ 10.2
- IntelliJ setup to use Python 2.5.4 for this project
I am using IntelliJ with the Python plugin, so running unittests is as simple as hitting ctrl-shft-f10.
I've also read the documentation on testbed and have successfully tested the datastore and memcache. However, where I am stuck is how do i unittest my RequestHandlers. I've scanned a lot of articles on Google and most of them seem to be pre merging of gaetestbed into gae as testbed.
In the following code sample, i would like to know how to write a unit test (which is runnable in intellij) which tests that a call to '/' returns -> Home Page
from google.appengine.ext import webapp
import wsgiref.handlers
class MainHandler(webapp.RequestHandler):
def get(self):
self.response.out.write('Home Page')
paths = [
('/', MainHandler)
开发者_JAVA百科 ]
application = webapp.WSGIApplication(paths, debug=True)
def main():
wsgiref.handlers.CGIHandler().run(application)
if __name__ == '__main__':
main()
From Nick Johnson's answer below, I added a new folder named test and added a file to that folder called unit_test.py. To that file I added the following code (Modified from Kris' answer below):
from StringIO import StringIO
from main import MainHandler
import unittest
from google.appengine.ext import webapp
class MyTestCase(unittest.TestCase):
def test_get(self):
request = webapp.Request({
"wsgi.input": StringIO(),
"CONTENT_LENGTH": 0,
"METHOD": "GET",
"PATH_INFO": "/",
})
response = webapp.Response()
handler = MainHandler()
handler.initialize(request, response)
handler.get()
self.assertEqual(response.out.getvalue(), "Home Page")
And it now works!
I found that I needed a slightly-modified version of Nick Johnson's code:
request = webapp.Request({
"wsgi.input": StringIO.StringIO(),
"CONTENT_LENGTH": 0,
"METHOD": "GET",
"PATH_INFO": "/",
})
response = webapp.Response()
handler = MainHandler()
handler.initialize(request, response)
handler.get()
self.assertEqual(response.out.getvalue(), "Home Page")
The easiest way to do this is to instantiate the handler and pass it request and response objects, then assert on the results:
request = webapp.Request({
"wsgi.input": StringIO.StringIO(),
"CONTENT_LENGTH": 0,
"METHOD": "GET",
})
request.path = '/'
response = webapp.Response()
handler = MainHandler()
handler.initialize(request, response)
handler.get()
self.assertEqual(response.body, "Home Page")
精彩评论