Beispiel #1
0
    def setUp(self):
        # Start with a fresh api proxy.
        apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()

        # Use a fresh stub datastore.
        stub = datastore_file_stub.DatastoreFileStub(APP_ID, '/dev/null',
                                                     '/dev/null')
        apiproxy_stub_map.apiproxy.RegisterStub('datastore_v3', stub)

        # Use a fresh stub UserService.
        apiproxy_stub_map.apiproxy.RegisterStub(
            'user', user_service_stub.UserServiceStub())
        os.environ['AUTH_DOMAIN'] = AUTH_DOMAIN
        os.environ['USER_EMAIL'] = LOGGED_IN_USER

        # Use a fresh urlfetch stub.
        apiproxy_stub_map.apiproxy.RegisterStub(
            'urlfetch', urlfetch_stub.URLFetchServiceStub())

        # Use a fresh mail stub.
        apiproxy_stub_map.apiproxy.RegisterStub('mail',
                                                mail_stub.MailServiceStub())

        # Use a fresh memcache stub
        apiproxy_stub_map.apiproxy.RegisterStub(
            'memcache', memcache_stub.MemcacheServiceStub())

        # Create a fake remplate renderer
        self.render_calls = []

        def template_render(filename, params, debug, template_dirs):
            self.render_calls.append(params)

        template.render = template_render
    def setUp(self):
        testutil.HandlerTestBase.setUp(self)
        self.handler = copy_handler.DoCopyHandler()
        self.handler.initialize(mock_webapp.MockRequest(),
                                mock_webapp.MockResponse())

        self.handler.request.path = '/_ah/datastore_admin/%s' % (
            copy_handler.ConfirmCopyHandler.SUFFIX)

        self.app_id = 'test_app'
        self.target_app_id = 'test_app_target'
        self.remote_url = 'http://test_app_target.appspot.com/_ah/remote_api'

        os.environ['APPLICATION_ID'] = self.app_id
        ds_stub = datastore_file_stub.DatastoreFileStub('test_app',
                                                        '/dev/null',
                                                        '/dev/null',
                                                        trusted=True)
        self.memcache = memcache_stub.MemcacheServiceStub()
        self.taskqueue = taskqueue_stub.TaskQueueServiceStub()

        self.stubs = googletest.StubOutForTesting()
        self.exceptions = []
        self.stubs.Set(copy_handler.DoCopyHandler, '_HandleException',
                       self.ExceptionTrapper)
        self.expected_extra_headers = None
        self.stubs.Set(copy_handler.remote_api_put_stub, 'get_remote_appid',
                       self.MockGetRemoteAppid)

        apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
        apiproxy_stub_map.apiproxy.RegisterStub('datastore_v3', ds_stub)
        apiproxy_stub_map.apiproxy.RegisterStub("memcache", self.memcache)
        apiproxy_stub_map.apiproxy.RegisterStub("taskqueue", self.taskqueue)
    def setUp(self):
        """Sets up test environment and regisers stub."""

        # Set required environment variables
        os.environ['APPLICATION_ID'] = 'test'
        os.environ['AUTH_DOMAIN'] = 'mydomain.local'
        os.environ['USER_EMAIL'] = '*****@*****.**'
        os.environ['USER_IS_ADMIN'] = '1'

        # Read index definitions.
        index_yaml = open(
            os.path.join(os.path.dirname(__file__), 'index.yaml'), 'r')

        try:
            self.indices = datastore_index.IndexDefinitionsToProtos(
                'test',
                datastore_index.ParseIndexDefinitions(index_yaml).indexes)
        except TypeError:
            self.indices = []

        index_yaml.close()

        # Register API proxy stub.
        apiproxy_stub_map.apiproxy = (apiproxy_stub_map.APIProxyStubMap())

        datastore = typhoonae.mongodb.datastore_mongo_stub.DatastoreMongoStub(
            'test', '', require_indexes=True)

        try:
            apiproxy_stub_map.apiproxy.RegisterStub('datastore_v3', datastore)
        except apiproxy_errors.ApplicationError, e:
            raise RuntimeError('These tests require a running MongoDB server '
                               '(%s)' % e)
Beispiel #4
0
 def setUp(self):
     unittest.TestCase.setUp(self)
     # Regist API Proxy
     apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
     # Regist urlfetch stub
     stub = urlfetch_stub.URLFetchServiceStub()
     apiproxy_stub_map.apiproxy.RegisterStub("urlfetch", stub)
Beispiel #5
0
    def activate(self):
        """Activates the testbed.

    Invoking this method will also assign default values to environment
    variables that are required by App Engine services, such as
    `os.environ['APPLICATION_ID']`. You can set custom values with
    `setup_env()`.
    """
        self._orig_env = dict(os.environ)
        self.setup_env()

        self._original_stub_map = apiproxy_stub_map.apiproxy
        self._test_stub_map = apiproxy_stub_map.APIProxyStubMap()
        internal_map = self._original_stub_map._APIProxyStubMap__stub_map
        self._test_stub_map._APIProxyStubMap__stub_map = dict(internal_map)
        apiproxy_stub_map.apiproxy = self._test_stub_map
        self._activated = True

        if USE_DATASTORE_EMULATOR:
            self.remote_api_stub = testserver_util.remote_api_stub
            self.rpc_server = self.remote_api_stub.ConfigureRemoteApi(
                os.environ['APPLICATION_ID'],
                '/',
                lambda: ('', ''),
                'localhost:%d' % testserver_util.TESTSERVER_UTIL.api_port,
                services=[],
                apiproxy=self._test_stub_map,
                use_remote_datastore=False)
Beispiel #6
0
def main():
    if len(sys.argv) < 2:
        sys.stdout.write('loaddata.py yamlfile\n')
        sys.exit()

    sys.path.insert(0, search_sdk_path())
    import dev_appserver
    dev_appserver.fix_sys_path()
    from google.appengine.api import apiproxy_stub_map, datastore_file_stub
    from google.appengine.api.memcache import memcache_stub
    # from kay-fw
    appid = 'dev~%s' % get_appid()
    os.environ['APPLICATION_ID'] = appid
    os.environ['SERVER_SOFTWARE'] = 'Development/1.0'
    p = get_datastore_paths()
    datastore_path = p[0]
    history_path = p[1]
    apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
    stub = datastore_file_stub.DatastoreFileStub(appid, datastore_path,
                                                   history_path)
    apiproxy_stub_map.apiproxy.RegisterStub('datastore_v3', stub)
    apiproxy_stub_map.apiproxy.RegisterStub('memcache',
        memcache_stub.MemcacheServiceStub())

    loaddata_from_yaml(sys.argv[1])
Beispiel #7
0
    def setUp(self):
        """Set up test fixture."""
        self.when = time.time()
        self.gettime = lambda: self.when

        self.stub = memcache_stub.MemcacheServiceStub(gettime=self.gettime)
        apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
        apiproxy_stub_map.apiproxy.RegisterStub('memcache', self.stub)

        self.key1 = b'key1'
        self.value1 = b'value1'

        self.key2 = b'key2 is very very long' + b' pad' * 100
        self.value2 = b'value2'

        key2_bytes = self.key2
        if isinstance(key2_bytes, six.text_type):
            key2_bytes = key2_bytes.encode('utf-8')

        self.key2_hash = hashlib.sha1(key2_bytes).hexdigest()
        if isinstance(self.key2_hash, six.text_type):
            self.key2_hash = self.key2_hash.encode('utf-8')

        self.key3 = 'key3'
        self.value3 = 'value3'
Beispiel #8
0
 def __init__(self): 
     # Start with a fresh api proxy. 
     apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap() 
     
     # Use a fresh stub datastore. 
     stub = datastore_file_stub.DatastoreFileStub(APP_ID, '', '') 
     apiproxy_stub_map.apiproxy.RegisterStub('datastore_v3', stub) 
    def setUp(self, disabled_capabilities=None, disabled_methods=None):
        """Setup routine for App Engine test cases.
    
    Args:
      disabled_capabilities: A set of (package, capability) tuples defining
        capabilities that are disabled.
      disabled_methods: A set of (package, method) tuples defining methods that
        are disabled. An entry of ('package', '*') in disabled_capabilities is
        treated the same as finding the method being tested in this set.
    """
        # Set up a new set of stubs for each test
        self.stub_map = apiproxy_stub_map.APIProxyStubMap()
        apiproxy_stub_map.apiproxy = self.stub_map

        if disabled_capabilities:
            self.disabled_capabilities = disabled_capabilities
        else:
            self.disabled_capabilities = set()
        if disabled_methods:
            self.disabled_methods = disabled_methods
        else:
            self.disabled_methods = set()
        capability_stub = test_capabilities.CapabilityServiceStub(
            self.disabled_capabilities, self.disabled_methods)
        self.stub_map.RegisterStub('capability_service', capability_stub)
Beispiel #10
0
def setup_stub():
    apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
    stub = datastore_file_stub.DatastoreFileStub('test',
                                                 '/dev/null',
                                                 '/dev/null',
                                                 trusted=True)
    apiproxy_stub_map.apiproxy.RegisterStub('datastore_v3', stub)

    apiproxy_stub_map.apiproxy.RegisterStub(
        'user', user_service_stub.UserServiceStub())

    apiproxy_stub_map.apiproxy.RegisterStub(
        'memcache', memcache_stub.MemcacheServiceStub())

    apiproxy_stub_map.apiproxy.RegisterStub(
        'urlfetch', urlfetch_stub.URLFetchServiceStub())

    apiproxy_stub_map.apiproxy.RegisterStub(
        'taskqueue', taskqueue_stub.TaskQueueServiceStub())

    try:
        apiproxy_stub_map.apiproxy.RegisterStub(
            'images', images_stub.ImagesServiceStub())
    except NameError:
        pass
Beispiel #11
0
 def set_up_stubs(self):
     apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
     ds_stub = datastore_file_stub.DatastoreFileStub('_', None)
     apiproxy_stub_map.apiproxy.RegisterStub('datastore_v3', ds_stub)
     mc_stub = memcache_stub.MemcacheServiceStub()
     apiproxy_stub_map.apiproxy.RegisterStub('memcache', mc_stub)
     os.environ['APPLICATION_ID'] = '_'
Beispiel #12
0
    def setUp(self):
        """Setup TyphoonAE's Blobstore API proxy stub and test data."""

        os.environ['APPLICATION_ID'] = 'demo'
        os.environ['AUTH_DOMAIN'] = 'yourdomain.net'
        os.environ['SERVER_NAME'] = 'server'
        os.environ['SERVER_PORT'] = '9876'
        os.environ['USER_EMAIL'] = '*****@*****.**'

        apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()

        self.datastore_path = tempfile.mktemp('db')

        datastore_stub = datastore_file_stub.DatastoreFileStub(
            'demo', self.datastore_path, require_indexes=False,
            trusted=False)

        apiproxy_stub_map.apiproxy.RegisterStub('datastore_v3', datastore_stub)

        try:
            from google.appengine.api.images import images_stub
            apiproxy_stub_map.apiproxy.RegisterStub(
                'images',
                images_stub.ImagesServiceStub())
        except ImportError, e:
            logging.warning(
                'Could not initialize images API; you are likely '
                'missing the Python "PIL" module. ImportError: %s', e)
            from google.appengine.api.images import images_not_implemented_stub
            apiproxy_stub_map.apiproxy.RegisterStub(
                'images',
                images_not_implemented_stub.ImagesNotImplementedServiceStub())
Beispiel #13
0
    def setUp(self):
        super(UrlFetchTestCase, self).setUp()
        from google.appengine.api import apiproxy_stub_map, urlfetch_stub

        apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
        apiproxy_stub_map.apiproxy.RegisterStub('urlfetch', urlfetch_stub.URLFetchServiceStub())
        postmaster.http.HTTP_LIB = 'urlfetch'
Beispiel #14
0
def _convert_datastore_file_stub_data_to_sqlite(app_id, datastore_path):
    logging.info('Converting datastore stub data to sqlite.')
    previous_stub = apiproxy_stub_map.apiproxy.GetStub('datastore_v3')
    try:
        apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
        datastore_stub = datastore_file_stub.DatastoreFileStub(
            app_id, datastore_path, trusted=True, save_changes=False)
        apiproxy_stub_map.apiproxy.RegisterStub('datastore_v3', datastore_stub)

        entities = _fetch_all_datastore_entities()
        sqlite_datastore_stub = datastore_sqlite_stub.DatastoreSqliteStub(
            app_id, datastore_path + '.sqlite', trusted=True)
        apiproxy_stub_map.apiproxy.ReplaceStub('datastore_v3',
                                               sqlite_datastore_stub)
        datastore.Put(entities)
        sqlite_datastore_stub.Close()
    finally:
        apiproxy_stub_map.apiproxy.ReplaceStub('datastore_v3', previous_stub)

    shutil.copy(datastore_path, datastore_path + '.filestub')
    os.remove(datastore_path)
    shutil.move(datastore_path + '.sqlite', datastore_path)
    logging.info(
        'Datastore conversion complete. File stub data has been backed '
        'up in %s', datastore_path + '.filestub')
    def setUp(self):
        # Ensure we're in UTC.
        os.environ['TZ'] = 'UTC'
        time.tzset()

        # Start with a fresh api proxy.
        apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()

        # Use a fresh stub datastore.
        self.__datastore_stub = datastore_file_stub.DatastoreFileStub(
            APP_ID, '/dev/null', '/dev/null')
        apiproxy_stub_map.apiproxy.RegisterStub('datastore_v3',
                                                self.__datastore_stub)
        os.environ['APPLICATION_ID'] = APP_ID

        # Use a fresh stub UserService.
        apiproxy_stub_map.apiproxy.RegisterStub(
            'user', user_service_stub.UserServiceStub())
        os.environ['AUTH_DOMAIN'] = AUTH_DOMAIN
        os.environ['USER_EMAIL'] = LOGGED_IN_USER

        # Use a fresh urlfetch stub.
        apiproxy_stub_map.apiproxy.RegisterStub(
            'urlfetch', urlfetch_stub.URLFetchServiceStub())

        # Use a fresh mail stub.
        apiproxy_stub_map.apiproxy.RegisterStub('mail',
                                                mail_stub.MailServiceStub())
Beispiel #16
0
def _run_test_suite(runner, suite):
    """Run the test suite.

    Preserve the current development apiproxy, create a new apiproxy and
    replace the datastore with a temporary one that will be used for this
    test suite, run the test suite, and restore the development apiproxy.
    This isolates the test datastore from the development datastore.

    """
    original_apiproxy = apiproxy_stub_map.apiproxy
    try:
        apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
        apiproxy_stub_map.apiproxy.RegisterStub(
            'datastore',
            datastore_file_stub.DatastoreFileStub('GAEUnitDataStore',
                                                  datastore_file=None,
                                                  trusted=True))
        apiproxy_stub_map.apiproxy.RegisterStub(
            'memcache', memcache_stub.MemcacheServiceStub())
        apiproxy_stub_map.apiproxy.RegisterStub(
            'taskqueue', TestingTaskQueueService(root_path='.'))
        # Allow the other services to be used as-is for tests.
        for name in ('user', 'urlfetch', 'mail', 'images'):
            apiproxy_stub_map.apiproxy.RegisterStub(
                name, original_apiproxy.GetStub(name))
        # TODO(slamm): add coverage tool here.
        runner.run(suite)
    finally:
        apiproxy_stub_map.apiproxy = original_apiproxy
Beispiel #17
0
def _run_test_suite(runner, suite):
    """Run the test suite.

    Preserve the current development apiproxy, create a new apiproxy and
    replace the datastore with a temporary one that will be used for this
    test suite, run the test suite, and restore the development apiproxy.
    This isolates the test datastore from the development datastore.

    """
    from utils.gae import Debug
    if not Debug():
        raise ValueError('cannot run on production!')
    original_apiproxy = apiproxy_stub_map.apiproxy
    try:
        apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
        temp_stub = datastore_file_stub.DatastoreFileStub('GAEUnitDataStore',
                                                          None,
                                                          None,
                                                          trusted=True)
        apiproxy_stub_map.apiproxy.RegisterStub('datastore', temp_stub)
        # Allow the other services to be used as-is for tests.
        for name in [
                'user', 'urlfetch', 'mail', 'memcache', 'images', 'blobstore',
                'logservice'
        ]:
            apiproxy_stub_map.apiproxy.RegisterStub(
                name, original_apiproxy.GetStub(name))
        runner.run(suite)
    finally:
        apiproxy_stub_map.apiproxy = original_apiproxy
  def setUp(self):
    self.file_service = files_testutil.TestFileServiceStub()
    apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
    apiproxy_stub_map.apiproxy.RegisterStub(
        "file", self.file_service)

    self.pool = output_writers.RecordsPool("tempfile", flush_size_chars=30)
Beispiel #19
0
def setup_stub(high_replication=False):
  apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
  stub = datastore_file_stub.DatastoreFileStub('test','/dev/null',
                                               '/dev/null', trusted=True)
  if high_replication:
    stub.SetConsistencyPolicy(
        datastore_stub_util.TimeBasedHRConsistencyPolicy())
  apiproxy_stub_map.apiproxy.RegisterStub('datastore_v3', stub)

  apiproxy_stub_map.apiproxy.RegisterStub(
    'user', user_service_stub.UserServiceStub())

  apiproxy_stub_map.apiproxy.RegisterStub(
    'memcache', memcache_stub.MemcacheServiceStub())

  apiproxy_stub_map.apiproxy.RegisterStub(
    'urlfetch', urlfetch_stub.URLFetchServiceStub())

  apiproxy_stub_map.apiproxy.RegisterStub(
    'taskqueue', taskqueue_stub.TaskQueueServiceStub())

  try:
    apiproxy_stub_map.apiproxy.RegisterStub(
      'images', images_stub.ImagesServiceStub())
  except NameError:
    pass
Beispiel #20
0
def ConfigureRemoteDatastore(app_id,
                             path,
                             auth_func,
                             servername=None,
                             rpc_server_factory=appengine_rpc.HttpRpcServer):
    """Does necessary setup to allow easy remote access to an AppEngine datastore.

  Args:
    app_id: The app_id of your app, as declared in app.yaml.
    path: The path to the remote_api handler for your app
      (for example, '/remote_api').
    auth_func: A function that takes no arguments and returns a
      (username, password) tuple. This will be called if your application
      requires authentication to access the remote_api handler (it should!)
      and you do not already have a valid auth cookie.
    servername: The hostname your app is deployed on. Defaults to
      <app_id>.appspot.com.
    rpc_server_factory: A factory to construct the rpc server for the datastore.
  """
    if not servername:
        servername = '%s.appspot.com' % (app_id, )
    os.environ['APPLICATION_ID'] = app_id
    apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
    server = rpc_server_factory(servername, auth_func, GetUserAgent(),
                                GetSourceName())
    stub = RemoteDatastoreStub(server, path)
    apiproxy_stub_map.apiproxy.RegisterStub('datastore_v3', stub)
Beispiel #21
0
  def activate(self):
    """Activates the testbed.

    Invoking this method will also assign default values to environment
    variables that are required by App Engine services, such as
    `os.environ['APPLICATION_ID']`. You can set custom values with
    `setup_env()`.
    """
    self._orig_env = dict(os.environ)
    self.setup_env()






    self._original_stub_map = apiproxy_stub_map.apiproxy
    self._test_stub_map = apiproxy_stub_map.APIProxyStubMap()
    internal_map = self._original_stub_map._APIProxyStubMap__stub_map
    self._test_stub_map._APIProxyStubMap__stub_map = dict(internal_map)
    apiproxy_stub_map.apiproxy = self._test_stub_map
    self._activated = True

    self._use_datastore_emulator = EmulatorSupportChecker.check()
    if self._use_datastore_emulator:
      self.api_port = EmulatorSupportChecker.get_api_port()
      self.rpc_server = remote_api_stub.ConfigureRemoteApi(
          os.environ['APPLICATION_ID'],
          '/',
          lambda: ('', ''),
          'localhost:%d' % self.api_port,
          services=[],
          apiproxy=self._test_stub_map,
          use_remote_datastore=False)
Beispiel #22
0
def main():
    if len(sys.argv) < 2:
        sys.stdout.write('dumpdata.py model_name [fields]\n')
        sys.exit()

    sys.path.insert(0, search_sdk_path())
    import dev_appserver
    dev_appserver.fix_sys_path()
    from google.appengine.api import apiproxy_stub_map, datastore_file_stub
    from google.appengine.api.memcache import memcache_stub
    # from kay-fw
    appid = 'dev~%s' % get_appid()
    os.environ['APPLICATION_ID'] = appid
    os.environ['SERVER_SOFTWARE'] = 'Development/1.0'
    p = get_datastore_paths()
    datastore_path = p[0]
    history_path = p[1]
    apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
    stub = datastore_file_stub.DatastoreFileStub(appid, datastore_path,
                                                 history_path)
    apiproxy_stub_map.apiproxy.RegisterStub('datastore_v3', stub)
    apiproxy_stub_map.apiproxy.RegisterStub(
        'memcache', memcache_stub.MemcacheServiceStub())

    fields = None
    if len(sys.argv) > 2:
        fields = [field_name for field_name in sys.argv[2].split(',')]

    model_class = load_class(sys.argv[1])
    result = dumpdata_from_model(model_class, fields)
    sys.stdout.write(result + '\n')
Beispiel #23
0
def setup_gae_services():
    """Setups all google app engine services required for testing."""
    from google.appengine.api import apiproxy_stub_map
    from google.appengine.api import mail_stub
    from google.appengine.api import user_service_stub
    from google.appengine.api import urlfetch_stub
    from google.appengine.api.capabilities import capability_stub
    from google.appengine.api.memcache import memcache_stub
    from google.appengine.api.taskqueue import taskqueue_stub
    from google.appengine.api import datastore_file_stub

    apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
    apiproxy_stub_map.apiproxy.RegisterStub(
        'urlfetch', urlfetch_stub.URLFetchServiceStub())
    apiproxy_stub_map.apiproxy.RegisterStub(
        'user', user_service_stub.UserServiceStub())
    apiproxy_stub_map.apiproxy.RegisterStub(
        'memcache', memcache_stub.MemcacheServiceStub())
    apiproxy_stub_map.apiproxy.RegisterStub(
        'datastore',
        datastore_file_stub.DatastoreFileStub('test-app-run', None, None))
    apiproxy_stub_map.apiproxy.RegisterStub('mail',
                                            mail_stub.MailServiceStub())
    yaml_location = os.path.join(HERE, 'app')
    apiproxy_stub_map.apiproxy.RegisterStub(
        'taskqueue',
        taskqueue_stub.TaskQueueServiceStub(root_path=yaml_location))
    apiproxy_stub_map.apiproxy.RegisterStub(
        'capability_service', capability_stub.CapabilityServiceStub())
Beispiel #24
0
  def setUp(self):
    unittest.TestCase.setUp(self)
    self.mox = mox.Mox()

    self.appid = "testapp"
    self.version_id = "1.23456789"
    os.environ["APPLICATION_ID"] = self.appid
    os.environ["CURRENT_VERSION_ID"] = self.version_id
    os.environ["HTTP_HOST"] = "localhost"

    self.memcache = memcache_stub.MemcacheServiceStub()
    self.taskqueue = taskqueue_stub.TaskQueueServiceStub()
    self.taskqueue.queue_yaml_parser = (
        lambda x: queueinfo.LoadSingleQueue(
            "queue:\n"
            "- name: default\n"
            "  rate: 10/s\n"
            "- name: crazy-queue\n"
            "  rate: 2000/d\n"
            "  bucket_size: 10\n"))
    self.datastore = datastore_file_stub.DatastoreFileStub(
        self.appid, "/dev/null", "/dev/null")

    self.blob_storage_directory = tempfile.mkdtemp()
    blob_storage = file_blob_storage.FileBlobStorage(
        self.blob_storage_directory, self.appid)
    self.blobstore_stub = blobstore_stub.BlobstoreServiceStub(blob_storage)
    self.file_service = self.createFileServiceStub(blob_storage)

    apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
    apiproxy_stub_map.apiproxy.RegisterStub("taskqueue", self.taskqueue)
    apiproxy_stub_map.apiproxy.RegisterStub("memcache", self.memcache)
    apiproxy_stub_map.apiproxy.RegisterStub("datastore_v3", self.datastore)
    apiproxy_stub_map.apiproxy.RegisterStub("blobstore", self.blobstore_stub)
    apiproxy_stub_map.apiproxy.RegisterStub("file", self.file_service)
Beispiel #25
0
def set_up_basic_stubs(app_id):
    """Set up a basic set of stubs.

    Configures datastore and memcache stubs for testing.

    Args:
    app_id: Application ID to configure stubs with.

    Returns:
    Dictionary mapping stub name to stub.
    """
    apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()

    ds_stub = datastore_file_stub.DatastoreFileStub(app_id, None)
    apiproxy_stub_map.apiproxy.RegisterStub('datastore_v3', ds_stub)

    mc_stub = memcache_stub.MemcacheServiceStub()
    apiproxy_stub_map.apiproxy.RegisterStub('memcache', mc_stub)

    tq_stub = taskqueue_stub.TaskQueueServiceStub()
    apiproxy_stub_map.apiproxy.RegisterStub('taskqueue', tq_stub)

    user_stub = user_service_stub.UserServiceStub()
    apiproxy_stub_map.apiproxy.RegisterStub('user', user_stub)

    return {
        'datastore': ds_stub,
        'memcache': mc_stub,
        'taskqueue': tq_stub,
        'user': user_stub,
    }
Beispiel #26
0
  def test_get_access_token_on_refresh(self):
    app_identity_stub = self.AppIdentityStubImpl()
    apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
    apiproxy_stub_map.apiproxy.RegisterStub("app_identity_service",
                                            app_identity_stub)
    apiproxy_stub_map.apiproxy.RegisterStub(
      'memcache', memcache_stub.MemcacheServiceStub())

    scope = [
     "http://www.googleapis.com/scope",
     "http://www.googleapis.com/scope2"]
    credentials = AppAssertionCredentials(scope)
    http = httplib2.Http()
    credentials.refresh(http)
    self.assertEqual('a_token_123', credentials.access_token)

    json = credentials.to_json()
    credentials = Credentials.new_from_json(json)
    self.assertEqual(
      'http://www.googleapis.com/scope http://www.googleapis.com/scope2',
      credentials.scope)

    scope = "http://www.googleapis.com/scope http://www.googleapis.com/scope2"
    credentials = AppAssertionCredentials(scope)
    http = httplib2.Http()
    credentials.refresh(http)
    self.assertEqual('a_token_123', credentials.access_token)
    self.assertEqual(
      'http://www.googleapis.com/scope http://www.googleapis.com/scope2',
      credentials.scope)
    def setUp(self):

        os.environ['USER_EMAIL'] = ''
        os.environ['USER_ID'] = ''
        os.environ['USER_IS_ADMIN'] = '0'

        apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
        self.users_stub = user_service_stub.UserServiceStub()
        self.expected_login_request = user_service_pb2.CreateLoginURLRequest()
        self.expected_logout_request = user_service_pb2.CreateLogoutURLRequest(
        )

        class TestStub(apiproxy_stub.APIProxyStub):
            _ACCEPTS_REQUEST_ID = True

            def _Dynamic_CreateLoginURL(myself, request, response, request_id):
                if request != self.expected_login_request:
                    raise AssertionError(
                        'Expected: %s\nFound: %s' %
                        (str(self.expected_login_request), str(request)))
                self.users_stub._Dynamic_CreateLoginURL(
                    request, response, request_id)

            def _Dynamic_CreateLogoutURL(myself, request, response,
                                         request_id):
                if request != self.expected_logout_request:
                    raise AssertionError(
                        'Expected: %s\nFound: %s' %
                        (str(self.expected_logout_request), str(request)))
                self.users_stub._Dynamic_CreateLogoutURL(
                    request, response, request_id)

        apiproxy_stub_map.apiproxy.RegisterStub('user', TestStub('user'))
def test_setup_stubs(
    request_data=None,
    app_id='myapp',
    application_root='/tmp/root',
    trusted=False,
    blobstore_path='/dev/null',
    datastore_consistency=None,
    datastore_path=':memory:',
    datastore_require_indexes=False,
    datastore_auto_id_policy=datastore_stub_util.SCATTERED,
    images_host_prefix='http://localhost:8080',
    logs_path=':memory:',
    mail_smtp_host='',
    mail_smtp_port=25,
    mail_smtp_user='',
    mail_smtp_password='',
    mail_enable_sendmail=False,
    mail_show_mail_body=False,
    matcher_prospective_search_path='/dev/null',
    search_index_path=None,
    taskqueue_auto_run_tasks=False,
    taskqueue_default_http_server='http://localhost:8080',
    user_login_url='/_ah/login?continue=%s',
    user_logout_url='/_ah/login?continue=%s',
    default_gcs_bucket_name=None):
  """Similar to setup_stubs with reasonable test defaults and recallable."""

  # Reset the stub map between requests because a stub map only allows a
  # stub to be added once.
  apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()

  if datastore_consistency is None:
    datastore_consistency = (
        datastore_stub_util.PseudoRandomHRConsistencyPolicy())

  setup_stubs(request_data,
              app_id,
              application_root,
              trusted,
              blobstore_path,
              datastore_consistency,
              datastore_path,
              datastore_require_indexes,
              datastore_auto_id_policy,
              images_host_prefix,
              logs_path,
              mail_smtp_host,
              mail_smtp_port,
              mail_smtp_user,
              mail_smtp_password,
              mail_enable_sendmail,
              mail_show_mail_body,
              matcher_prospective_search_path,
              search_index_path,
              taskqueue_auto_run_tasks,
              taskqueue_default_http_server,
              user_login_url,
              user_logout_url,
              default_gcs_bucket_name)
def get_api_client():
    if 'APPENGINE_RUNTIME' in os.environ:
        from google.appengine.api import apiproxy_stub_map 
        from google.appengine.api import urlfetch_stub
        apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap() 
        apiproxy_stub_map.apiproxy.RegisterStub('urlfetch',  urlfetch_stub.URLFetchServiceStub())
    return Client(os.environ['ALGOLIA_APPLICATION_ID'],
                  os.environ['ALGOLIA_API_KEY'])
    def testCustomAuthDomain(self):

        apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
        users_stub = user_service_stub.UserServiceStub(
            auth_domain='google.com')
        apiproxy_stub_map.apiproxy.RegisterStub('user', users_stub)
        gow = users.User(email='*****@*****.**', _user_id='24546')
        self.assertEqual('google.com', gow.auth_domain())