Python webapp2.WSGIApplication() Examples

The following are 30 code examples of webapp2.WSGIApplication(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module webapp2 , or try the search function .
Example #1
Source File: oss_fuzz_generate_certs_test.py    From clusterfuzz with Apache License 2.0 6 votes vote down vote up
def setUp(self):
    test_helpers.patch_environ(self)
    test_helpers.patch(self, [
        'handlers.base_handler.Handler.is_cron',
    ])

    self.mock.is_cron.return_value = True
    self.app = webtest.TestApp(
        webapp2.WSGIApplication([('/generate-certs',
                                  oss_fuzz_generate_certs.Handler)]))

    data_types.OssFuzzProject(name='project1').put()
    data_types.OssFuzzProject(name='project2').put()

    data_types.WorkerTlsCert(
        id='project2',
        project_name='project2',
        cert_contents=b'cert_contents',
        key_contents=b'key_contents').put() 
Example #2
Source File: create_issue_test.py    From clusterfuzz with Apache License 2.0 6 votes vote down vote up
def setUp(self):
    test_helpers.patch(self, [
        'handlers.testcase_detail.show.get_testcase_detail',
        'libs.access.has_access',
        'libs.auth.get_current_user',
        'libs.issue_management.issue_filer.file_issue',
        'libs.issue_management.issue_tracker_utils.'
        'get_issue_tracker_for_testcase',
    ])
    self.mock.has_access.return_value = True
    self.mock.get_testcase_detail.return_value = {'testcase': 'yes'}
    self.mock.get_current_user().email = 'test@user.com'

    self.app = webtest.TestApp(
        webapp2.WSGIApplication([('/', create_issue.Handler)]))

    self.testcase = data_types.Testcase()
    self.testcase.put() 
Example #3
Source File: i18n.py    From googleapps-message-recall with Apache License 2.0 6 votes vote down vote up
def __init__(self, app, config=None):
        """Initializes the i18n store.

        :param app:
            A :class:`webapp2.WSGIApplication` instance.
        :param config:
            A dictionary of configuration values to be overridden. See
            the available keys in :data:`default_config`.
        """
        config = app.config.load_config(self.config_key,
            default_values=default_config, user_values=config,
            required_keys=None)
        self.translations = {}
        self.translations_path = config['translations_path']
        self.domains = config['domains']
        self.default_locale = config['default_locale']
        self.default_timezone = config['default_timezone']
        self.date_formats = config['date_formats']
        self.set_locale_selector(config['locale_selector'])
        self.set_timezone_selector(config['timezone_selector']) 
Example #4
Source File: i18n.py    From googleapps-message-recall with Apache License 2.0 6 votes vote down vote up
def get_store(factory=I18nStore, key=_store_registry_key, app=None):
    """Returns an instance of :class:`I18nStore` from the app registry.

    It'll try to get it from the current app registry, and if it is not
    registered it'll be instantiated and registered. A second call to this
    function will return the same instance.

    :param factory:
        The callable used to build and register the instance if it is not yet
        registered. The default is the class :class:`I18nStore` itself.
    :param key:
        The key used to store the instance in the registry. A default is used
        if it is not set.
    :param app:
        A :class:`webapp2.WSGIApplication` instance used to store the instance.
        The active app is used if it is not set.
    """
    app = app or webapp2.get_app()
    store = app.registry.get(key)
    if not store:
        store = app.registry[key] = factory(app)

    return store 
Example #5
Source File: download_testcase_test.py    From clusterfuzz with Apache License 2.0 6 votes vote down vote up
def _test_download(self, handler_class):
    """Test download."""
    testcase = data_types.Testcase()
    testcase.minimized_keys = 'key'
    testcase.put()

    self.mock.check_access_and_get_testcase.return_value = testcase

    app = webtest.TestApp(webapp2.WSGIApplication([('/', handler_class)]))
    resp = app.get('/?id=%s' % testcase.key.id())

    self.assertEqual(302, resp.status_int)
    # pylint: disable=line-too-long
    # According to https://cloud.google.com/appengine/docs/go/how-requests-are-handled
    # Appengine replaces X-AppEngine-BlobKey with the blob content.
    self.assertEqual(
        'https://SIGNED_URL&response-content-disposition=attachment'
        '%3B+filename%3Dtestcase-1-file.tar.gz', resp.location) 
Example #6
Source File: jinja2.py    From googleapps-message-recall with Apache License 2.0 6 votes vote down vote up
def get_jinja2(factory=Jinja2, key=_registry_key, app=None):
    """Returns an instance of :class:`Jinja2` from the app registry.

    It'll try to get it from the current app registry, and if it is not
    registered it'll be instantiated and registered. A second call to this
    function will return the same instance.

    :param factory:
        The callable used to build and register the instance if it is not yet
        registered. The default is the class :class:`Jinja2` itself.
    :param key:
        The key used to store the instance in the registry. A default is used
        if it is not set.
    :param app:
        A :class:`webapp2.WSGIApplication` instance used to store the instance.
        The active app is used if it is not set.
    """
    app = app or webapp2.get_app()
    jinja2 = app.registry.get(key)
    if not jinja2:
        jinja2 = app.registry[key] = factory(app)

    return jinja2 
Example #7
Source File: find_similar_issues_test.py    From clusterfuzz with Apache License 2.0 6 votes vote down vote up
def setUp(self):
    test_helpers.patch(self, [
        'libs.access.check_access_and_get_testcase',
        'libs.issue_management.issue_tracker_utils.'
        'get_issue_tracker_for_testcase',
        'libs.issue_management.issue_tracker_utils.get_issue_url',
        'libs.issue_management.issue_tracker_utils.get_search_keywords',
        'libs.issue_management.issue_tracker_utils.get_similar_issues',
        'libs.issue_management.issue_tracker_utils.get_similar_issues_url',
    ])
    self.app = webtest.TestApp(
        webapp2.WSGIApplication([('/', find_similar_issues.Handler)]))

    self.testcase = data_types.Testcase()
    self.testcase.put()
    self.mock.check_access_and_get_testcase.return_value = self.testcase

    self.invalid_testcase_id = self.testcase.key.id() + 1 
Example #8
Source File: update_from_trunk_test.py    From clusterfuzz with Apache License 2.0 6 votes vote down vote up
def setUp(self):
    test_helpers.patch(self, [
        'base.tasks.add_task',
        'base.tasks.queue_for_job',
        'libs.auth.get_current_user',
        'handlers.testcase_detail.show.get_testcase_detail',
        'libs.access.check_access_and_get_testcase',
    ])
    self.app = webtest.TestApp(
        webapp2.WSGIApplication([('/', update_from_trunk.Handler)]))

    self.testcase = data_types.Testcase(queue='old-queue')
    self.testcase.put()
    self.mock.check_access_and_get_testcase.return_value = self.testcase
    self.mock.get_testcase_detail.return_value = {'testcase': 'yes'}
    self.mock.get_current_user().email = 'test@user.com' 
Example #9
Source File: oss_fuzz_build_status_test.py    From clusterfuzz with Apache License 2.0 6 votes vote down vote up
def setUp(self):
    self.app = webtest.TestApp(
        webapp2.WSGIApplication([('/build-status',
                                  oss_fuzz_build_status.Handler)]))

    test_helpers.patch(self, [
        'base.utils.utcnow',
        'handlers.base_handler.Handler.is_cron',
        'libs.issue_management.issue_tracker_utils.get_issue_tracker',
        'metrics.logs.log_error',
        'requests.get',
    ])

    self.mock.utcnow.return_value = datetime.datetime(2018, 2, 1)
    self.mock.is_cron.return_value = True

    self.itm = IssueTrackerManager('oss-fuzz')
    self.mock.get_issue_tracker.return_value = monorail.IssueTracker(self.itm)

    self.maxDiff = None  # pylint: disable=invalid-name 
Example #10
Source File: update_issue_test.py    From clusterfuzz with Apache License 2.0 6 votes vote down vote up
def setUp(self):
    test_helpers.patch(self, [
        'datastore.data_handler.get_issue_description',
        'datastore.data_handler.get_issue_summary',
        'datastore.data_handler.get_stacktrace',
        'datastore.data_handler.update_group_bug',
        'libs.helpers.get_issue_tracker_for_testcase',
        'libs.auth.get_current_user',
        'handlers.testcase_detail.show.get_testcase_detail',
        'libs.access.get_access',
        'libs.issue_management.issue_tracker_policy.get',
        'libs.issue_management.issue_filer.get_memory_tool_labels',
    ])
    self.mock.get_access.return_value = access.UserAccess.Allowed
    self.mock.get_testcase_detail.return_value = {'testcase': 'yes'}
    self.mock.get_current_user().email = 'test@test.com'
    self.mock.get.return_value = CHROMIUM_POLICY

    self.app = webtest.TestApp(
        webapp2.WSGIApplication([('/', update_issue.Handler)]))

    self.testcase = data_types.Testcase()
    self.testcase.bug_information = ''
    self.testcase.crash_state = 'fake_crash_state'
    self.testcase.put() 
Example #11
Source File: auth.py    From googleapps-message-recall with Apache License 2.0 6 votes vote down vote up
def get_store(factory=AuthStore, key=_store_registry_key, app=None):
    """Returns an instance of :class:`AuthStore` from the app registry.

    It'll try to get it from the current app registry, and if it is not
    registered it'll be instantiated and registered. A second call to this
    function will return the same instance.

    :param factory:
        The callable used to build and register the instance if it is not yet
        registered. The default is the class :class:`AuthStore` itself.
    :param key:
        The key used to store the instance in the registry. A default is used
        if it is not set.
    :param app:
        A :class:`webapp2.WSGIApplication` instance used to store the instance.
        The active app is used if it is not set.
    """
    app = app or webapp2.get_app()
    store = app.registry.get(key)
    if not store:
        store = app.registry[key] = factory(app)

    return store 
Example #12
Source File: load_bigquery_stats_test.py    From clusterfuzz with Apache License 2.0 6 votes vote down vote up
def setUp(self):
    self.app = webtest.TestApp(
        webapp2.WSGIApplication([('/load-bigquery-stats',
                                  load_bigquery_stats.Handler)]))

    data_types.Fuzzer(name='fuzzer', jobs=['job']).put()
    data_types.Job(name='job').put()

    test_helpers.patch(self, [
        'google_cloud_utils.big_query.get_api_client',
        'handlers.base_handler.Handler.is_cron',
        'handlers.cron.load_bigquery_stats.Handler._utc_now',
    ])

    self.mock._utc_now.return_value = datetime.datetime(2016, 9, 8)  # pylint: disable=protected-access
    self.mock_bigquery = mock.MagicMock()
    self.mock.get_api_client.return_value = self.mock_bigquery 
Example #13
Source File: testcase_list_test.py    From clusterfuzz with Apache License 2.0 6 votes vote down vote up
def setUp(self):
    test_helpers.patch(self, [
        'base.external_users._allowed_entities_for_user',
        'base.external_users._get_permissions_query_for_user',
        'libs.access.get_user_job_type',
        'libs.access.has_access',
        'libs.helpers.get_user_email',
    ])
    self.app = webtest.TestApp(
        webapp2.WSGIApplication([('/', testcase_list.JsonHandler)]))

    self.testcases = []
    for i in range(10):
      t = data_types.Testcase()
      t.crash_type = ''
      t.crash_state = ''
      t.status = 'Processed'
      t.security_flag = True
      t.is_a_duplicate_flag = False
      t.one_time_crasher_flag = False
      t.open = True
      t.is_leader = True
      t.timestamp = datetime.datetime.fromtimestamp(100 - i)
      t.put()
      self.testcases.append(t) 
Example #14
Source File: landing_handler_test.py    From googleapps-message-recall with Apache License 2.0 5 votes vote down vote up
def setUp(self):
    super(AppLandingHandlerTest, self).setUp()
    self._testapp = webtest.TestApp(webapp2.WSGIApplication([
        (r'/', frontend_views.LandingPageHandler),
        ], debug=True)) 
Example #15
Source File: rest_api_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def call_get(request_handler, uri=None, **kwargs):
  """Calls request_handler's 'get' in a context of webtest app."""
  uri = uri or '/dummy_path'
  assert uri.startswith('/')
  path = uri.rsplit('?', 1)[0]
  app = webtest.TestApp(
      webapp2.WSGIApplication([(path, request_handler)], debug=True),
      extra_environ={'REMOTE_ADDR': '127.0.0.1'})
  return app.get(uri, **kwargs) 
Example #16
Source File: main_frontend.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def create_application():
  ereporter2.register_formatter()

  # Zap out the ndb in-process cache by default.
  # This cache causes excessive memory usage in in handler where a lot of
  # entities are fetched in one query. When coupled with high concurrency
  # as specified via max_concurrent_requests in app.yaml, this may cause out of
  # memory errors.
  ndb.Context.default_cache_policy = staticmethod(lambda _key: False)
  ndb.Context._cache_policy = staticmethod(lambda _key: False)

  # App that serves HTML pages and old API.
  frontend = handlers_frontend.create_application(False)

  def is_enabled_callback():
    return config.settings().enable_ts_monitoring

  gae_ts_mon.initialize(frontend, is_enabled_fn=is_enabled_callback)
  # App that serves new endpoints API.
  endpoints_api = endpoints_webapp2.api_server([
      handlers_endpoints_v1.IsolateService,
      # components.config endpoints for validation and configuring of
      # luci-config service URL.
      config.ConfigApi,
  ])
  gae_ts_mon.instrument_wsgi_application(endpoints_api)

  prpc_api = webapp2.WSGIApplication(handlers_prpc.get_routes())
  return frontend, endpoints_api, prpc_api 
Example #17
Source File: handlers_frontend.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def create_application(debug):
  """Creates the url router.

  The basic layouts is as follow:
  - /restricted/.* requires being an instance administrator.
  - /stats/.* has statistics.
  """
  acl.bootstrap()
  template.bootstrap()
  return webapp2.WSGIApplication(get_routes(), debug=debug) 
Example #18
Source File: stats_framework_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def setUp(self):
    super(StatsFrameworkLogTest, self).setUp()
    stats_framework_logs_mock.configure(self)
    self.h = stats_framework.StatisticsFramework(
        'test_framework', Snapshot, generate_snapshot)

    class GenerateHandler(webapp2.RequestHandler):
      def get(self2):
        stats_logs.add_entry('Hello')
        self2.response.write('Yay')

    class JsonHandler(webapp2.RequestHandler):
      def get(self2):
        self2.response.headers['Content-Type'] = (
            'application/json; charset=utf-8')
        duration = int(self2.request.get('duration', 120))
        now = self2.request.get('now')
        resolution = self2.request.get('resolution')
        data = stats_framework.get_stats(
            self.h, resolution, now, duration, True)
        self2.response.write(stats_framework.utils.encode_to_json(data))

    routes = [
        ('/generate', GenerateHandler),
        ('/json', JsonHandler),
    ]
    real_app = webapp2.WSGIApplication(routes, debug=True)
    self.app = webtest.TestApp(
        real_app, extra_environ={'REMOTE_ADDR': 'fake-ip'})
    self.now = datetime.datetime(2010, 1, 2, 3, 4, 5, 6)
    self.mock_now(self.now, 0) 
Example #19
Source File: app.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def create_wsgi_application(debug=False):
  routes = []
  routes.extend(rest_api.get_rest_api_routes())
  routes.extend(ui.get_ui_routes())
  routes.extend(change_log.get_backend_routes())
  return webapp2.WSGIApplication(routes, debug=debug) 
Example #20
Source File: handler_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def make_test_app(self, path, request_handler):
    """Returns webtest.TestApp with single route."""
    return webtest.TestApp(
        webapp2.WSGIApplication([(path, request_handler)], debug=True),
        extra_environ={'REMOTE_ADDR': '127.0.0.1'}) 
Example #21
Source File: auth.py    From googleapps-message-recall with Apache License 2.0 5 votes vote down vote up
def set_store(store, key=_store_registry_key, app=None):
    """Sets an instance of :class:`AuthStore` in the app registry.

    :param store:
        An instance of :class:`AuthStore`.
    :param key:
        The key used to retrieve the instance from the registry. A default
        is used if it is not set.
    :param request:
        A :class:`webapp2.WSGIApplication` instance used to retrieve the
        instance. The active app is used if it is not set.
    """
    app = app or webapp2.get_app()
    app.registry[key] = store 
Example #22
Source File: about_handler_test.py    From googleapps-message-recall with Apache License 2.0 5 votes vote down vote up
def setUp(self):
    super(AppAboutHandlerTest, self).setUp()
    self._testapp = webtest.TestApp(webapp2.WSGIApplication([
        (r'/about', frontend_views.AboutPageHandler),
        ], debug=True)) 
Example #23
Source File: appengine.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def callback_application(self):
        """WSGI application for handling the OAuth 2.0 redirect callback.

        If you need finer grained control use `callback_handler` which returns
        just the webapp.RequestHandler.

        Returns:
            A webapp.WSGIApplication that handles the redirect back from the
            server during the OAuth 2.0 dance.
        """
        return webapp.WSGIApplication([
            (self.callback_path, self.callback_handler())
        ]) 
Example #24
Source File: test_graphql_handler.py    From graphene-gae with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_noSchema_returns500(self):
        graphql_application = webapp2.WSGIApplication([
            ('/graphql', GraphQLHandler)
        ])

        app = webtest.TestApp(graphql_application)
        for method in (app.get, app.post):
            response = method('/graphql', expect_errors=True)
            self.assertEqual(response.status_int, 500)
            self.assertEqual(response.json_body['errors'][0]['message'], 'GraphQL Schema is missing.') 
Example #25
Source File: model_creator_handler_test.py    From gcp-census with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        patch('googleapiclient.discovery.build').start()
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_memcache_stub()
        app = webapp2.WSGIApplication(
            [('/createModels', ModelCreatorHandler)]
        )
        self.under_test = webtest.TestApp(app) 
Example #26
Source File: test.py    From billing-export-python with Apache License 2.0 5 votes vote down vote up
def setUp(self):
    #logging.basicConfig(level=logging.DEBUG)
    self.testbed = testbed.Testbed()
    self.testbed.setup_env(app_id='_')
    self.testbed.activate()
    self.testbed.init_all_stubs()
    main.UseLocalGCS()
    self.LoadTestData()
    app = webapp2.WSGIApplication([('/objectChangeNotification',
                                    main.ObjectChangeNotification)])
    self.testapp = webtest.TestApp(app) 
Example #27
Source File: fuzzer_stats_test.py    From clusterfuzz with Apache License 2.0 5 votes vote down vote up
def setUp(self):
    test_helpers.patch(self, [
        'libs.auth.get_current_user',
        'libs.auth.is_current_user_admin',
        'handlers.fuzzer_stats.build_results',
    ])

    self.mock.build_results.return_value = json.dumps({})

    self.app = webtest.TestApp(
        webapp2.WSGIApplication([('/fuzzer-stats/load',
                                  fuzzer_stats.LoadHandler)]))

    data_types.ExternalUserPermission(
        email='test@user.com',
        entity_kind=data_types.PermissionEntityKind.JOB,
        entity_name='job1',
        is_prefix=False,
        auto_cc=data_types.AutoCCType.ALL).put()

    data_types.ExternalUserPermission(
        email='test@user.com',
        entity_kind=data_types.PermissionEntityKind.JOB,
        entity_name='job2',
        is_prefix=False,
        auto_cc=data_types.AutoCCType.ALL).put()

    data_types.Job(name='job1').put()
    data_types.Job(name='job2').put()
    data_types.Job(name='job3').put() 
Example #28
Source File: base_handler_test.py    From clusterfuzz with Apache License 2.0 5 votes vote down vote up
def test_redirect_another_domain(self):
    """Test redirect to another domain."""
    app = webtest.TestApp(webapp2.WSGIApplication([('/', RedirectHandler)]))
    response = app.get('/?redirect=https%3A%2F%2Fblah.com%2Ftest')
    self.assertEqual('https://blah.com/test', response.headers['Location']) 
Example #29
Source File: base_handler_test.py    From clusterfuzz with Apache License 2.0 5 votes vote down vote up
def test_redirect_another_page(self):
    """Test redirect to another page."""
    app = webtest.TestApp(webapp2.WSGIApplication([('/', RedirectHandler)]))
    response = app.get('/?redirect=%2Fanother-page')
    self.assertEqual('http://localhost/another-page',
                     response.headers['Location']) 
Example #30
Source File: base_handler_test.py    From clusterfuzz with Apache License 2.0 5 votes vote down vote up
def test_forbidden_logged_in(self):
    """Ensure it renders forbidden response correctly (when logged in)."""
    app = webtest.TestApp(
        webapp2.WSGIApplication([('/', AccessDeniedExceptionHandler)]))
    response = app.get('/', expect_errors=True)
    self.assertEqual(response.status_int, 403)
    self.assertRegex(response.body, b'.*Access Denied.*')
    self.assertRegex(response.body, b'.*this_random_message.*')