Saturday, February 4, 2012

App Engine datastore testbed with indexes

UPDATE (12 Mar 2012)
With SDK v.1.6.3 it's even easier. When you init datastore stub, pass root_path keyword argument, like this:

self.testbed.init_datastore_v3_stub(
  require_indexes=True,
  root_path="%s/../" % os.path.dirname(__file__)
)

root_path is your app root directory.
------------------------------------------------------------------------------

Just a quick note for those locally unit-testing your app written for Google App Engine, Python version.

While writing tests for my models I completely forgot that by default Datastore stub is being setup without requiring indexes - http://code.google.com/appengine/docs/python/tools/localunittesting.html

Well, turns out it's actually pretty easy to setup:


def setUp(self):
  super(GaeTestMixin, self).setUp()
  self.testbed = testbed.Testbed()
  self.testbed.activate()
  # we want to use datastore and memcache testbeds here
  self.testbed.init_datastore_v3_stub(require_indexes=True)
  self.testbed.init_memcache_stub()
  # setup indexes
  dev_appserver_index.SetupIndexes(None, "%s/../" % os.path.dirname(__file__))
The key thing here is the last line:
  dev_appserver_index.SetupIndexes(None, "%s/../" % os.path.dirname(__file__))

First argument is your app_id. By passing None you're telling it to use the default app_id, whatever you set it to in the app.yaml.
Second argument is the app root path. I'm walking one dir up here because I have my tests sit in APP_ROOT/tests.

Have fun with your tests!

PS dev_appserver_index lives in google.appengine.tools module.