コード例 #1
0
    def setUp(self):
        # Create a consistency policy that will simulate the High Replication consistency model.
        self.policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(probability=0)
        self.policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(probability=1)

        self.testbed = testbed.Testbed()
        self.testbed.activate()

        self.testbed.init_datastore_v3_stub(consistency_policy=self.policy)
        self.testbed.init_taskqueue_stub()
        self.testbed.init_memcache_stub()
        self.testbed.init_search_stub()
コード例 #2
0
ファイル: testutil.py プロジェクト: kylewm/webutil
    def setUp(self):
        super(HandlerTest, self).setUp()

        os.environ['APPLICATION_ID'] = 'app_id'
        self.current_user_id = '123'
        self.current_user_email = '*****@*****.**'

        self.testbed = testbed.Testbed()
        self.testbed.setup_env(user_id=self.current_user_id,
                               user_email=self.current_user_email)
        self.testbed.activate()

        hrd_policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(
            probability=.5)
        self.testbed.init_datastore_v3_stub(consistency_policy=hrd_policy)
        self.testbed.init_taskqueue_stub(root_path='.')
        self.testbed.init_user_stub()
        self.testbed.init_mail_stub()
        self.testbed.init_memcache_stub()
        self.testbed.init_logservice_stub()

        self.mox.StubOutWithMock(urllib2, 'urlopen')

        # unofficial API, whee! this is so we can call
        # TaskQueueServiceStub.GetTasks() in tests. see
        # google/appengine/api/taskqueue/taskqueue_stub.py
        self.taskqueue_stub = self.testbed.get_stub('taskqueue')

        self.request = webapp2.Request.blank('/')
        self.response = webapp2.Response()
        self.handler = webapp2.RequestHandler(self.request, self.response)

        # set time zone to UTC so that tests don't depend on local time zone
        os.environ['TZ'] = 'UTC'
コード例 #3
0
    def setUp(self):
        self.policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(
            probability=1)
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub(consistency_policy=self.policy)
        self.testbed.init_memcache_stub()
        self.testbed.init_user_stub()
        self.testbed.init_urlfetch_stub()
        self.testbed.init_taskqueue_stub(_all_queues_valid=True)
        ndb.get_context().clear_cache(
        )  # Prevent data from leaking between tests

        app = webapp2.WSGIApplication([
            RedirectRoute(r'/mod/redeem',
                          TeamAdminRedeem,
                          'team-admin',
                          strict_slash=True),
        ])
        self.testapp = webtest.TestApp(app)

        self.team = Team(
            id="frc1124",
            name="Team",
            team_number=1124,
        )
        self.team.put()
        self.now = datetime.datetime.now()
    def setUp(self):
        self.policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(
            probability=1)
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub(consistency_policy=self.policy)
        self.testbed.init_memcache_stub()
        self.testbed.init_user_stub()
        self.testbed.init_urlfetch_stub()
        ndb.get_context().clear_cache(
        )  # Prevent data from leaking between tests

        app = webapp2.WSGIApplication([
            RedirectRoute(r'/suggest/cad/review',
                          SuggestDesignsReviewController,
                          'review-designs',
                          strict_slash=True),
            RedirectRoute(r'/suggest/review',
                          SuggestReviewHomeController,
                          'review-home',
                          strict_slash=True),
        ],
                                      debug=True)
        self.testapp = webtest.TestApp(app)

        self.team = Team(
            id="frc1124",
            team_number=1124,
        )
        self.team.put()
コード例 #5
0
ファイル: test_utils.py プロジェクト: oulan/oppia
    def setUp(self):
        empty_environ()

        from google.appengine.datastore import datastore_stub_util
        from google.appengine.ext import testbed

        self.testbed = testbed.Testbed()
        self.testbed.activate()

        # Configure datastore policy to emulate instantaneously and globally
        # consistent HRD.
        policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(
            probability=1)

        # Declare any relevant App Engine service stubs here.
        self.testbed.init_user_stub()
        self.testbed.init_memcache_stub()
        self.testbed.init_datastore_v3_stub(consistency_policy=policy)
        self.testbed.init_urlfetch_stub()
        self.testbed.init_files_stub()
        self.testbed.init_blobstore_stub()
        self.testbed.init_search_stub()

        # The root path tells the testbed where to find the queue.yaml file.
        self.testbed.init_taskqueue_stub(root_path=os.getcwd())
        self.taskqueue_stub = self.testbed.get_stub(
            testbed.TASKQUEUE_SERVICE_NAME)

        self.testbed.init_mail_stub()
        self.mail_stub = self.testbed.get_stub(testbed.MAIL_SERVICE_NAME)

        # Set up the app to be tested.
        self.testapp = webtest.TestApp(main.app)

        self.signup_superadmin_user()
コード例 #6
0
    def setUp(self):

        #the memcache will contain values that will break the tests
        #dont run this on production!
        memcache.flush_all()

        # First, create an instance of the Testbed class.
        self.testbed = testbed.Testbed()
        # Then activate the testbed, which prepares the service stubs for use.
        self.testbed.activate()
        # Create a consistency policy that will simulate the High Replication consistency model.
        self.policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(
            probability=0)
        # Initialize the datastore stub with this policy.
        self.testbed.init_datastore_v3_stub(consistency_policy=self.policy)

        millis = int(round(time.time() * 1000))

        tree_name = 'test_tree' + str(millis)

        username = '******' + str(millis)

        self.parent_branch = Branch(id=tree_name)

        self.parent_branch.author_name = username
        self.parent_branch.link = ''
        self.parent_branch.content = ''
        self.parent_branch.put()

        self.child_branchs = []
コード例 #7
0
    def setUp(self):
        super(AppEngineTestbedCase, self).setUp()

        if not APPENGINE_AVAILABLE:
            raise SkipTest()

        # A hack to prevent get_application_default from going GAE route.
        self._server_software_org = os.environ.get('SERVER_SOFTWARE')
        os.environ['SERVER_SOFTWARE'] = ''

        # Setup the datastore and memcache stub.
        # First, create an instance of the Testbed class.
        self.testbed = testbed.Testbed()
        # Then activate the testbed, which prepares the service stubs for
        # use.
        self.testbed.activate()
        # Create a consistency policy that will simulate the High
        # Replication consistency model.
        self.policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(
            probability=0)
        # Initialize the datastore stub with this policy.
        self.testbed.init_datastore_v3_stub(
            datastore_file=tempfile.mkstemp()[1],
            consistency_policy=self.policy)
        self.testbed.init_memcache_stub()

        # Setup remaining stubs.
        self.testbed.init_user_stub()
        self.testbed.init_taskqueue_stub(root_path='tests/resources')
        self.taskqueue_stub = self.testbed.get_stub(
            testbed.TASKQUEUE_SERVICE_NAME)
コード例 #8
0
    def test_invalid_update_campaign(self):
        self.policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(probability=0)
        self.testbed.init_datastore_v3_stub(consistency_policy=self.policy)
        # create new campaign
        response = self.admin_app.post("/api/admin/campaign", params=json.dumps(self.CAMPAIGN_SAMPLE),
                                       headers=self.ADMIN_HEADERS)
        campaign = json.loads(response.body)
        campaign_id = campaign["id"]
        campaign_url = response.headers["Location"]

        # simulate a user click
        self.tracker_app.get('/api/campaign/%d/platform/android' % campaign_id)
        # run the background task to store the click in Datastore
        [deferred.run(task.payload) for task in self.taskqueue_stub.get_filtered_tasks()]

        def check_missing_parameter(parameter):
            campaign_dict = deepcopy(self.CAMPAIGN_SAMPLE)
            del campaign_dict[parameter]
            response = self.admin_app.put(campaign_url, params=json.dumps(campaign_dict),
                                          headers=self.ADMIN_HEADERS)
            self.assertEqual(response.status_int, 200)

        map(check_missing_parameter, ["name", "link", "platforms"])

        campaign_update = {"platforms": ["android"]}
        response = self.admin_app.put(campaign_url, params=json.dumps(campaign_update),
                                      headers=self.ADMIN_HEADERS)
        campaign_updated = json.loads(response.body)
        self.assertEqual(response.status_int, 200)
        self.assertEqual({"id", "name", "link", "create_date", "update_date", "platform_counters"},
                         set(campaign_updated.keys()))
        self.assertEqual(["android"], campaign_updated["platform_counters"].keys())
コード例 #9
0
ファイル: basetest.py プロジェクト: shaunstanislauslau/upvote
  def setUp(self, wsgi_app=None, patch_generate_token=True):
    super(UpvoteTestCase, self).setUp()

    # Require index.yaml be observed so tests will fail if indices are absent.
    index_yaml_dir = os.path.join(
        os.path.dirname('.'), 'upvote/gae')
    policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(probability=1)
    self.testbed.init_datastore_v3_stub(
        consistency_policy=policy, require_indexes=True,
        root_path=index_yaml_dir)
    self.testbed.init_memcache_stub()

    if wsgi_app is not None:
      # Workaround for lack of "runtime" variable in test env.
      adapter = lambda r, h: webapp2.Webapp2HandlerAdapter(h)
      wsgi_app.router.set_adapter(adapter)
      handlers.CreateErrorHandlersForApplications([wsgi_app])
      self.testapp = webtest.TestApp(wsgi_app)
    else:
      self.testapp = None

    self.secret_key = 'test-secret'
    xsrf_utils.SiteXsrfSecret.SetInstance(secret=self.secret_key.encode('hex'))

    self._env_patcher = None

    if patch_generate_token:
      self.Patch(xsrfutil, 'generate_token', return_value='token')

    self.PatchEnv(settings.ProdEnv)
コード例 #10
0
ファイル: lib.py プロジェクト: ksdtech/gae-conferences
    def setUp(self):
        import ferris

        self.testbed = TestbedWithFiles()

        self.testbed.setup_env(AUTH_DOMAIN='example.com', APPLICATION_ID='_')

        self.testbed.activate()
        self.testbed.init_memcache_stub()

        policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(
            probability=1)
        self.testbed.init_datastore_v3_stub(consistency_policy=policy)
        self.testbed.init_taskqueue_stub(root_path=os.path.join(
            os.path.abspath(os.path.dirname(ferris.__file__)), '..'))
        self.testbed.init_blobstore_stub()
        self.testbed.init_images_stub()
        self.testbed.init_logservice_stub()
        self.testbed.init_mail_stub()
        self.testbed.init_urlfetch_stub()
        self.testbed.init_user_stub()

        stub = SearchServiceStub()
        self.testbed._register_stub('search', stub)

        self.taskqueue_stub = self.testbed.get_stub(
            testbed.TASKQUEUE_SERVICE_NAME)
コード例 #11
0
    def test_update_campaign(self):
        self.policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(probability=0)
        self.testbed.init_datastore_v3_stub(consistency_policy=self.policy)
        # create new campaign
        response = self.admin_app.post("/api/admin/campaign", params=json.dumps(self.CAMPAIGN_SAMPLE),
                                       headers=self.ADMIN_HEADERS)
        campaign = json.loads(response.body)
        campaign_id = campaign["id"]
        campaign_url = response.headers["Location"]

        # simulate a user click
        response = self.tracker_app.get('/api/campaign/%d/platform/android' % campaign_id)
        # run the background task to store the click in Datastore
        [deferred.run(task.payload) for task in self.taskqueue_stub.get_filtered_tasks()]

        campaign_new = deepcopy(self.CAMPAIGN_SAMPLE)
        campaign_new["name"] = "new name"
        response = self.admin_app.put(campaign_url, params=json.dumps(self.CAMPAIGN_SAMPLE),
                                      headers=self.ADMIN_HEADERS)

        campaign_updated = json.loads(response.body)
        # check if update resets counter (it should not)
        self.assertEqual(campaign_updated["platform_counters"]["android"], 1)
        # check if update_date is not null any more
        self.assertIsNotNone(campaign_updated["update_date"])
コード例 #12
0
ファイル: tests.py プロジェクト: ronw23/gae-boilerplate
    def setUp(self):

        webapp2_config = boilerplate_config.config

        # create a WSGI application.
        self.app = webapp2.WSGIApplication(config=webapp2_config)
        routes.add_routes(self.app)
        boilerplate_routes.add_routes(self.app)
        self.testapp = webtest.TestApp(self.app, extra_environ={'REMOTE_ADDR' : '127.0.0.1'})
        
        # activate GAE stubs
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        # Create a consistency policy that will simulate the High Replication consistency model.
        self.policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(probability=0)
        # Initialize the datastore stub with this policy.
        self.testbed.init_datastore_v3_stub(consistency_policy=self.policy)
        self.testbed.init_memcache_stub()
        self.testbed.init_urlfetch_stub()
        self.testbed.init_taskqueue_stub()
        self.testbed.init_mail_stub()
        self.mail_stub = self.testbed.get_stub(testbed.MAIL_SERVICE_NAME)
        self.taskqueue_stub = self.testbed.get_stub(testbed.TASKQUEUE_SERVICE_NAME)
        self.testbed.init_user_stub()

        self.headers = {'User-Agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) Version/6.0 Safari/536.25',
                        'Accept-Language' : 'en_US'}

        # fix configuration if this is still a raw boilerplate code - required by test with mails
        if not utils.is_email_valid(self.app.config.get('contact_sender')):
            self.app.config['contact_sender'] = "*****@*****.**"
        if not utils.is_email_valid(self.app.config.get('contact_recipient')):
            self.app.config['contact_recipient'] = "*****@*****.**"
コード例 #13
0
 def setUp(self):
     self.testbed = testbed.Testbed()
     self.testbed.activate()
     self.policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(probability=1)
     # Initialize the datastore stub with this policy.
     self.testbed.init_datastore_v3_stub(consistency_policy=self.policy)
     self.mkres = munkresCaller.MunkresCaller()
コード例 #14
0
def SetUpTestbedTestCase(case):
    """Set up appengine testbed enviroment."""
    case.testbed = testbed.Testbed()

    case.testbed.activate()
    # The oauth_aware decorator will 302 to login unless there is either
    # a current user _or_ a valid oauth header; this is easier to stub.
    case.testbed.setup_env(user_email='*****@*****.**',
                           user_id='1234',
                           overwrite=True)

    case.testbed.init_all_stubs()

    policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(probability=1)
    case.testbed.init_datastore_v3_stub(consistency_policy=policy)
    case.testbed.init_taskqueue_stub(_all_queues_valid=True)

    os.environ['AUTH_DOMAIN'] = 'example.com'

    # Lazily stub out key-fetching RPC dependency.
    def Stub(data, **_):
        return data

    case.patches = [
        mock.patch.object(crypto, 'Decrypt', side_effect=Stub),
        mock.patch.object(crypto, 'Encrypt', side_effect=Stub),
    ]
    for m in case.patches:
        m.start()
コード例 #15
0
def init_testbed():
    IGNORED_STUBS = []

    # We allow users to disable scattered IDs in tests. This primarily for running Django tests that
    # assume implicit ordering (yeah, annoying)
    use_scattered = not getattr(settings, "DJANGAE_SEQUENTIAL_IDS_IN_TESTS",
                                False)

    stub_kwargs = {
        "init_taskqueue_stub": {
            "root_path": environment.get_application_root()
        },
        "init_datastore_v3_stub": {
            "use_sqlite":
            True,
            "auto_id_policy":
            testbed.AUTO_ID_POLICY_SCATTERED
            if use_scattered else testbed.AUTO_ID_POLICY_SEQUENTIAL,
            "consistency_policy":
            datastore_stub_util.PseudoRandomHRConsistencyPolicy(probability=1)
        }
    }

    get_context().reset()
    # Reset any context caching
    bed = testbed.Testbed()
    bed.activate()
    for init_name in testbed.INIT_STUB_METHOD_NAMES.values():
        if init_name in IGNORED_STUBS:
            continue

        getattr(bed, init_name)(**stub_kwargs.get(init_name, {}))

    return bed
コード例 #16
0
    def _create_test_db(self, verbosity, autoclobber):
        from google.appengine.datastore import datastore_stub_util
        # Testbed exists in memory
        test_database_name = ':memory:'

        # Init test stubs
        self.testbed = testbed.Testbed()
        self.testbed.activate()

        self.testbed.init_app_identity_stub()
        self.testbed.init_blobstore_stub()
        self.testbed.init_capability_stub()
        self.testbed.init_channel_stub()

        self.testbed.init_datastore_v3_stub(datastore_stub_util.PseudoRandomHRConsistencyPolicy(probability=0))
        self.testbed.init_files_stub()
        # FIXME! dependencies PIL
        # self.testbed.init_images_stub()
        self.testbed.init_logservice_stub()
        self.testbed.init_mail_stub()
        self.testbed.init_memcache_stub()
        self.testbed.init_taskqueue_stub()
        self.testbed.init_urlfetch_stub()
        self.testbed.init_user_stub()
        self.testbed.init_xmpp_stub()
        # self.testbed.init_search_stub()

        # Init all the stubs!
        # self.testbed.init_all_stubs()

        return test_database_name
コード例 #17
0
    def setUp(self):
        environment.TEST = True

        lru_clear_all()

        if testbed:
            self.testbed = testbed.Testbed()
            self.testbed.setup_env(current_version_id='testbed.version')
            self.testbed.activate()

            # init stubs
            self.testbed.init_logservice_stub()
            self.testbed.init_memcache_stub()
            self.testbed.init_app_identity_stub()
            self.policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(
                probability=0)
            self.testbed.init_datastore_v3_stub(consistency_policy=self.policy)
            self.testbed.init_blobstore_stub()
            self.testbed.init_mail_stub()

            # get stubs
            self.task_queue_stub = self.testbed.get_stub(
                testbed.TASKQUEUE_SERVICE_NAME)
            self.mail_stub = self.testbed.get_stub(testbed.MAIL_SERVICE_NAME)

            # disable ndb cache
            context = ndb.get_context()
            context.set_cache_policy(lambda key: False)
            context.set_memcache_policy(lambda key: False)

        # api mock
        self.api_mock = ApiMock()
コード例 #18
0
ファイル: __init__.py プロジェクト: rogertalk/roger-api
    def setUp(self):
        self.policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(
            probability=1)
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_app_identity_stub()
        self.testbed.init_channel_stub()
        self.testbed.init_datastore_v3_stub(consistency_policy=self.policy)
        self.testbed.init_memcache_stub()
        self.memcache_stub = self.testbed.get_stub(
            testbed.MEMCACHE_SERVICE_NAME)
        self.testbed.init_taskqueue_stub(root_path='../')
        self.taskqueue_stub = self.testbed.get_stub(
            testbed.TASKQUEUE_SERVICE_NAME)
        self.testbed.init_urlfetch_stub()
        # Allow tests to handle urlfetch requests.
        urlfetch = self.testbed.get_stub('urlfetch')
        test = self

        def forward_fetch(self, request, response):
            test.handle_urlfetch(request, response)

        urlfetch._Dynamic_Fetch = types.MethodType(forward_fetch, urlfetch)
        # Reset caches.
        ndb.get_context().clear_cache()
        self.clear_memcache()
コード例 #19
0
def inconsistent_db(probability=0, connection='default'):
    """
        A context manager that allows you to make the datastore inconsistent during testing.
        This is vital for writing applications that deal with the Datastore's eventual consistency
    """

    from django.db import connections

    conn = connections[connection]

    if not hasattr(
            conn.creation, "testbed"
    ) or "datastore_v3" not in conn.creation.testbed._enabled_stubs:
        raise RuntimeError(
            "Tried to use the inconsistent_db stub when not testing")

    stub = apiproxy_stub_map.apiproxy.GetStub('datastore_v3')

    # Set the probability of the datastore stub
    original_policy = stub._consistency_policy
    stub.SetConsistencyPolicy(
        datastore_stub_util.PseudoRandomHRConsistencyPolicy(
            probability=probability))
    try:
        yield
    finally:
        # Restore to consistent mode
        stub.SetConsistencyPolicy(original_policy)
コード例 #20
0
ファイル: utils.py プロジェクト: gayancliyanage/education
    def setUp(self):
        self.testbed = testbed.Testbed()
        # Then activate the testbed, which prepares the service stubs for use.
        self.testbed.activate()
        # Next, declare which service stubs you want to use.

        self.policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(
            probability=0)
        self.testbed.init_datastore_v3_stub(consistency_policy=self.policy)
        self.testbed.init_memcache_stub()
        self.testbed.init_mail_stub()
        self.testbed.init_blobstore_stub()
        self.testbed.init_files_stub()
        self.testbed.init_taskqueue_stub(root_path="../.")  # 2.7
        self.testbed.init_user_stub()

        self.url_fetcher = URLFetchServiceMock()
        self.testbed._register_stub('urlfetch', self.url_fetcher)

        import main
        main.app.debug = True

        self.secret = main.wsgi_config['webapp2_extras.sessions']['secret_key']
        self.app = webtest.TestApp(main.app)

        self.taskqueue_stub = self.testbed.get_stub(
            testbed.TASKQUEUE_SERVICE_NAME)
        self.task_run = set([])
        self._id_count = 1
        core.config.VALID_DOMAINS = {"example.com": "*****@*****.**"}
コード例 #21
0
ファイル: stubs.py プロジェクト: george1912/ostproject
    def activate_test_stubs(self, connection):
        if self.active_stubs == 'test':
            return

        os.environ['HTTP_HOST'] = "%s.appspot.com" % appid

        appserver_opts = connection.settings_dict.get('DEV_APPSERVER_OPTIONS', {})
        high_replication = appserver_opts.get('high_replication', False)
        require_indexes = appserver_opts.get('require_indexes', False)

        datastore_opts = {'require_indexes': require_indexes}

        if high_replication:
            from google.appengine.datastore import datastore_stub_util
            datastore_opts['consistency_policy'] = datastore_stub_util.PseudoRandomHRConsistencyPolicy(probability=1)

        if self.testbed is None:
            from google.appengine.ext.testbed import Testbed
            self.testbed = Testbed()

        self.testbed.activate()
        self.pre_test_stubs = self.active_stubs
        self.active_stubs = 'test'
        self.testbed.init_datastore_v3_stub(root_path=PROJECT_DIR, **datastore_opts)
        self.testbed.init_memcache_stub()
        self.testbed.init_taskqueue_stub(auto_task_running=True, root_path=PROJECT_DIR)
        self.testbed.init_urlfetch_stub()
        self.testbed.init_user_stub()
        self.testbed.init_xmpp_stub()
        self.testbed.init_channel_stub()
コード例 #22
0
    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()

        policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(
            probability=1)
        self.testbed.init_datastore_v3_stub(consistency_policy=policy)
コード例 #23
0
ファイル: test_helper.py プロジェクト: n-dream/recordio
def setUp(self):
    self.testbed = testbed.Testbed()
    self.testbed.activate()
    policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(probability=1)
    self.testbed.init_datastore_v3_stub(consistency_policy=policy)
    self.testbed.init_memcache_stub()
    self.testbed.init_taskqueue_stub(root_path=os.path.dirname(__file__))
コード例 #24
0
def setup_testbed():
    """Sets up the GAE testbed and enables common stubs."""
    from google.appengine.datastore import datastore_stub_util
    from google.appengine.ext import testbed as gaetestbed

    # Setup the datastore and memcache stub.
    # First, create an instance of the Testbed class.
    tb = gaetestbed.Testbed()
    # Then activate the testbed, which prepares the service stubs for
    # use.
    tb.activate()
    # Create a consistency policy that will simulate the High
    # Replication consistency model.
    policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(
        probability=1.0)
    # Initialize the datastore stub with this policy.
    tb.init_datastore_v3_stub(datastore_file=tempfile.mkstemp()[1],
                              consistency_policy=policy)
    tb.init_memcache_stub()

    # Setup remaining stubs.
    tb.init_urlfetch_stub()
    tb.init_app_identity_stub()
    tb.init_blobstore_stub()
    tb.init_user_stub()
    tb.init_logservice_stub()
    # tb.init_taskqueue_stub(root_path='tests/resources')
    tb.init_taskqueue_stub()
    tb.taskqueue_stub = tb.get_stub(gaetestbed.TASKQUEUE_SERVICE_NAME)

    return tb
コード例 #25
0
    def _create_test_db(self, verbosity, autoclobber, *args):
        from google.appengine.ext import testbed  # Imported lazily to prevent warnings on GAE

        assert not self.testbed

        if args:
            logger.warning(
                "'keepdb' argument is not currently supported on the AppEngine backend"
            )

        # We allow users to disable scattered IDs in tests. This primarily for running Django tests that
        # assume implicit ordering (yeah, annoying)
        use_scattered = not getattr(settings,
                                    "DJANGAE_SEQUENTIAL_IDS_IN_TESTS", False)

        kwargs = {
            "use_sqlite":
            True,
            "auto_id_policy":
            testbed.AUTO_ID_POLICY_SCATTERED
            if use_scattered else testbed.AUTO_ID_POLICY_SEQUENTIAL,
            "consistency_policy":
            datastore_stub_util.PseudoRandomHRConsistencyPolicy(probability=1)
        }

        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub(**kwargs)
        self.testbed.init_memcache_stub()
        get_context().reset()
コード例 #26
0
    def setUp(self):

        # the memcache will contain values that will break the tests
        # dont run this on production!
        memcache.flush_all()

        # First, create an instance of the Testbed class.
        self.testbed = testbed.Testbed()
        # Then activate the testbed, which prepares the service stubs for use.
        self.testbed.activate()
        # Create a consistency policy that will simulate the High Replication consistency model.
        self.policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(
            probability=0)
        # Initialize the datastore stub with this policy.
        self.testbed.init_datastore_v3_stub(consistency_policy=self.policy)

        millis = int(round(time.time() * 1000))

        username = '******' + str(millis)

        self.testbed.setup_env(USER_EMAIL=username + '@example.com',
                               USER_ID='1',
                               USER_IS_ADMIN='0')
        self.testbed.init_user_stub()

        self.user_info = UserInfo.put_new(username, users.get_current_user())

        self.controller = LikeController()
        self.controller.user_info = self.user_info
        self.controller.google_user = users.get_current_user()

        self.branch = Branch(id="LikeControllerTestCase.branch" + str(millis))

        self.branch.put()
コード例 #27
0
def _test(**kwargs):
    """
        This stub uses the testbed to initialize the bare minimum to use the
        Datastore connector. Tests themselves should setup/tear down their own
        stubs by using DjangaeDiscoverRunner or the nose plugin.

        The stubs here are just for bootstrapping the tests. Obviously any data inserted
        between here, and the tests themselves will be wiped out when the tests begin!
    """

    from google.appengine.ext import testbed
    from google.appengine.datastore import datastore_stub_util

    MINIMAL_STUBS = {
        "init_memcache_stub": {},
        "init_datastore_v3_stub": {
            "use_sqlite": True,
            "auto_id_policy": testbed.AUTO_ID_POLICY_SCATTERED,
            "consistency_policy": datastore_stub_util.PseudoRandomHRConsistencyPolicy(probability=1)
        }
    }

    testbed = testbed.Testbed()
    testbed.activate()
    for init_name, stub_kwargs in MINIMAL_STUBS.items():
        getattr(testbed, init_name)(**stub_kwargs)

    yield

    if testbed:
        testbed.deactivate()
コード例 #28
0
 def activate(self):
     self.testbed.activate()
     policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(probability=1)
     self.testbed.init_datastore_v3_stub(consistency_policy=policy)
     self.testbed.init_urlfetch_stub()
     self.testbed.init_memcache_stub()
     self.testbed.init_logservice_stub()
コード例 #29
0
    def setUp(self):
        super(AppEngineTestBase, self).setUp()
        empty_environ()

        # setup an app to be tested
        self.testapp = webtest.TestApp(self.getApp())
        self.testbed = testbed.Testbed()
        self.testbed.activate()

        # configure datastore policy to emulate instantaneously and globally
        # consistent HRD; we also patch dev_appserver in main.py to run under
        # the same policy
        policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(
            probability=1)

        # declare any relevant App Engine service stubs here
        self.testbed.init_user_stub()
        self.testbed.init_memcache_stub()
        self.testbed.init_datastore_v3_stub(consistency_policy=policy)
        self.testbed.init_taskqueue_stub(root_path=os.environ['SOURCE_DIR'])
        self.taskq = self.testbed.get_stub(testbed.TASKQUEUE_SERVICE_NAME)
        self.testbed.init_urlfetch_stub()
        self.testbed.init_files_stub()
        self.testbed.init_blobstore_stub()
        self.testbed.init_mail_stub()
        # TODO(emichael): Fix this when an official stub is created
        self.testbed._register_stub('search',
                                    simple_search_stub.SearchServiceStub())
        self.task_dispatcher = task_queue.TaskQueueHandlerDispatcher(
            self.testapp, self.taskq)
コード例 #30
0
    def setUp(self):
        super(BaseTest, self).setUp()

        root_path = '.'
        application_id = 'graphene-gae-test'

        # First, create an instance of the Testbed class.
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.setup_env(app_id=application_id, overwrite=True)
        policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(
            probability=self.datastore_probability)
        self.testbed.init_datastore_v3_stub(root_path=root_path,
                                            consistency_policy=policy,
                                            require_indexes=True)
        self.testbed.init_app_identity_stub()
        self.testbed.init_blobstore_stub()
        self.testbed.init_memcache_stub()
        self.testbed.init_taskqueue_stub(root_path=root_path)
        self.testbed.init_urlfetch_stub()
        self.storage = cloudstorage_stub.CloudStorageStub(
            self.testbed.get_stub('blobstore').storage)
        self.testbed.init_mail_stub()
        self.testbed.init_user_stub()
        self.taskqueue_stub = self.testbed.get_stub(
            testbed.TASKQUEUE_SERVICE_NAME)

        ndb.get_context().clear_cache()
        ndb.get_context().set_cache_policy(lambda x: True)