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:
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)
]
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With