View source on GitHub |
A module to use service stubs for testing.
To test applications that use App Engine services, such as datastore,
developers can use the available stub implementations. Service stubs behave like
the original service without causing permanent side effects. The datastore stub,
for example, allows you to write entities into memory without storing them to
the actual datastore. The testbed
module makes using those stubs for testing
easier.
Example:
import unittest
from google.appengine.ext import ndb from google.appengine.ext import testbed
class TestModel(ndb.Model): number = ndb.IntegerProperty(default=42)
class MyTestCase(unittest.TestCase):
def setUp(self): # First, create an instance of the Testbed class. self.testbed = testbed.Testbed() # Then activate the testbed, which will allow you to use # service stubs. self.testbed.activate() # Next, declare which service stubs you want to use. self.testbed.init_datastore_v3_stub() self.testbed.init_memcache_stub()
def tearDown(self): # Don't forget to deactivate the testbed after the tests are # completed. If the testbed is not deactivated, the original # stubs will not be restored. self.testbed.deactivate()
def testInsertEntity(self): # Because we use the datastore stub, this put() does not have # permanent side effects. TestModel().put() fetched_entities = TestModel.query().fetch(2) self.assertEqual(1, len(fetched_entities)) self.assertEqual(42, fetched_entities[0].number)
Enable stubs and disable services
The testbed
module allows you to use stubs for the following services:
- capability_service
- channel
- datastore_v3 (aka datastore)
- images (only for dev_appserver)
- mail (only for dev_appserver)
- memcache
- taskqueue
- urlfetch
- user
- xmpp
To use a particular service stub, call self.init_SERVICENAME_stub()
. Using
this call will replace calls to the service with calls to the service stub. If
you want to disable any calls to a particular service, call
self.init_SERVICENAME_stub(enable=False)
. This call can be useful if you want
to test code that must not use a certain service.
Environment variables
App Engine service stubs often depend on environment variables. For example, the
datastore stub uses an environment variable to store entities linked to a
particular app. testbed
will use default values if nothing else is provided,
but you can change those values with self.setup_env()
.
Classes
class EmulatorSupportChecker
: A static class. Checks whether datastore emulator is supported.
class Error
: Base testbed error type.
class NotActivatedError
: Raised if the used testbed instance is not activated.
class StubNotSupportedError
: Raised if an unsupported service stub is accessed.
class Testbed
: Class providing APIs to manipulate stubs for testing.
Functions
validate_project_id(...)
: Ensure that a GCP project ID is valid.