Note that there are some explanatory texts on larger screens.

plurals
  1. POUnitTesting the webapp.RequestHandler in GAE - Python
    text
    copied!<p>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:</p> <ul> <li>Google App Engine 1.5.0</li> <li>IntelliJ 10.2</li> <li>IntelliJ setup to use Python 2.5.4 for this project</li> </ul> <p>I am using IntelliJ with the Python plugin, so running unittests is as simple as hitting ctrl-shft-f10. </p> <p>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.</p> <p>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</p> <pre><code>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() </code></pre> <p>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):</p> <pre><code>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") </code></pre> <p>And it now works!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload