Handler Testing For Python 2 Stay organized with collections Save and categorize content based on your preferences.
TheLocal UnitTesting for Python article described how to run unit tests for yourapplication. While unit tests are great for testing the separate units of yourcode, the integration of those code units is what makes your application run—so integration testing is just as important.
For App Engine applications, request handlers are critical integrationpoints. While a WSGI application routes requests to the right handler, thehandler itself processes the request data and generates a response (read moreaboutRequestHandlers). Request handlers are normal Python objects like any otherfunction or class, which makes them easy to use in automated tests. But becausea WSGI application wraps them like a shell, we will use a similar shell in ourtests.
WebTest
For our tests, we will utilize theWebTest framework. WebTest is alibrary that gives you a simple interface for testing WSGI-based applicationsand therefore the request handlers. It does so by wrapping a WSGI applicationin a special test app which can then be used for testing. WebTest allows you tointeract with your handlers without a full App Engine environment; you caneasily issue requests and modify the request environment. The responses have atest-friendly interface as well. You don't have to use WebTest, but it suremakes your life a lot easier.
Before you can start, install WebTest on your local machine or wherever youintend to run handler tests. Instructions can be found athttp://webtest.pythonpaste.org/#installation
Testing a Simple "Hello World"Handler
Let's begin with testing a simple "Hello World!" handler that responds to auser request with a plain-text reply. The handle's response is "Hello World!"and the content type is "text/plain":
importwebapp2importwebtestclassHelloWorldHandler(webapp2.RequestHandler):defget(self):# Create the handler's response "Hello World!" in plain text.self.response.headers['Content-Type']='text/plain'self.response.out.write('Hello World!')
Next, create the test case and initialize a test application that uses yourhandler:
...classAppTest(unittest.TestCase):defsetUp(self):# Create a WSGI application.app=webapp2.WSGIApplication([('/',HelloWorldHandler)])# Wrap the app with WebTest’s TestApp.self.testapp=webtest.TestApp(app)# Test the handler.deftestHelloWorldHandler(self):response=self.testapp.get('/')self.assertEqual(response.status_int,200)self.assertEqual(response.normal_body,'Hello World!')self.assertEqual(response.content_type,'text/plain')
As you can see, WebTest allows you to make GET requests with a simple get()call (other request methods have similar methods). The return value is aresponse object with which you can test the status code, body, content type,and much more—check outtheWebTest homepage for adetailed description of all the things you can do.
Creating aHandler Test that Uses an App Engine Service
Now let's have a look at how to test a handler that uses an App Engineservice. This means we must now deal with two components that may affect ourtests: the handler and the service we are using. As described intheLocal Unit Testingfor Python article, the best way to deal with services in tests is tousetestbed.
The following example uses Memcache, but it is the same in principle forother services like Datastore or Task Queue.
The handler we test caches the given key and value. Notice that we parseboth values from the request parameters.
fromgoogle.appengine.apiimportmemcachefromgoogle.appengine.extimporttestbedimportwebapp2importwebtestclassCacheHandler(webapp2.RequestHandler):defpost(self):key=self.request.get('key')value=self.request.get('value')memcache.set(key,value)
In the test, just like before, first create an application and wrap it withWebTest. Additionally, activateaTestbedinstance and take care to deactivate after the test.
...classAppTest(unittest.TestCase):defsetUp(self):app=webapp2.WSGIApplication([('/cache/',CacheHandler)])self.testapp=webtest.TestApp(app)self.testbed=testbed.Testbed()self.testbed.activate()deftearDown(self):self.testbed.deactivate()deftestCacheHandler(self):# First define a key and value to be cached.key='answer'value='42'self.testbed.init_memcache_stub()params={'key':key,'value':value}# Then pass those values to the handler.response=self.testapp.post('/cache/',params)# Finally verify that the passed-in values are actually stored in Memcache.self.assertEqual(value,memcache.get(key))
Setting Up a Testing Framework
You can set up a testing framework if you like. Tests for handlers that useWebTest can beexecutedlikeyour unit tests for App Engine. The only difference is that you need tomake sure you have WebTest installed.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-12-15 UTC.