Unit testing model classes in Google App Engine
Posted: Last updated:I'm currently writing my first Google App Engine app. I've created a few model classes which inherit from db.Model and I wanted to unit test them. That works fine until you try to save them to the datastore or retrieve them. Then you might get this error:
BadArgumentError: app must not be empty.
The problem here is that you need an environment variable with your app id, which you can set with the following code:
os.environ['APPLICATION_ID'] = 'myapp'
After you do that you'll get this error:
AssertionError: No api proxy found for service "datastore_v3"
To fix that one you need the following lines in your test setup:
datastore_file = '/dev/null'
from google.appengine.api import apiproxy_stub_map,datastore_file_stub
apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
stub = datastore_file_stub.DatastoreFileStub('myapp', datastore_file, '/')
apiproxy_stub_map.apiproxy.RegisterStub('datastore_v3', stub)
Temp datastore is persisted just while you run your tests. But you can also give the datastore_file variable a real filename and then it will save the datastore between tests, or you could create different datastore files for different scenarios.
Finally, to put it all together, here is the setUp method for my TestCase classes:
class SomeTestCase(unittest.TestCase):
def setUp(self):
app_id = 'myapp'
os.environ['APPLICATION_ID'] = app_id
datastore_file = '/dev/null'
from google.appengine.api import apiproxy_stub_map,datastore_file_stub
apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
stub = datastore_file_stub.DatastoreFileStub(app_id, datastore_file, '/')
apiproxy_stub_map.apiproxy.RegisterStub('datastore_v3', stub)