Пример #1
0
 def runTest(self):
     from servlets import event
     from app import app
     router = app.router
     env = {'PATH_INFO': '/events/55/'}
     route = router.match(webapp2.Request(env))
     self.assertEqual(route[0].handler, event.ShowEventHandler)
Пример #2
0
    def __call__(self, environ, start_response):
        additional_headers = []

        def custom_start_response(status, headers, exc_info=None):
            headers.extend(additional_headers)
            # keep session cookies private
            headers.extend([
                # Note App Engine automatically sets a 'Date' header for us. See
                # https://developers.google.com/appengine/docs/python/runtime#Responses
                ('Expires', settings.LONG_AGO),
                ('Cache-Control', 'private, max-age=0'),
            ])
            return start_response(status, headers, exc_info)

        # 1. ensure we have a session
        request = webapp2.Request(environ, app=self.app)
        session = environ['playground.session'] = GetOrMakeSession(request)

        if session.modified:
            additional_headers.extend([
                self.MakeSessionCookieHeader(session),
                self.MakeXsrfCookieHeader(session),
            ])

        # 2. ensure we have an user entity
        user_key = GetUserKey(session)
        assert user_key
        # TODO: avoid creating a datastore entity on every anonymous request
        environ['playground.user'] = model.GetOrCreateUser(user_key)

        # 3. perform CSRF checks
        if not shared.IsHttpReadMethod(environ):
            _PerformCsrfRequestValidation(session, environ)

        return self.app(environ, custom_start_response)
Пример #3
0
 def test_applicable(self):
   request = webapp2.Request({
     'HTTP_X_APPENGINE_INBOUND_APPID': 'some-app',
   })
   self.assertEqual(
     model.Identity(model.IDENTITY_SERVICE, 'some-app'),
     handler.service_to_service_authentication(request))
Пример #4
0
 def test_applicable(self):
     os.environ.update({
         'USER_EMAIL': '*****@*****.**',
         'USER_ID': '123',
         'USER_IS_ADMIN': '0',
     })
     # Actual request is not used by CookieAuthentication.
     self.assertEqual(
         model.Identity(model.IDENTITY_USER, '*****@*****.**'),
         handler.gae_cookie_authentication(webapp2.Request({})))
Пример #5
0
 def test_decode_message_post(self):
   request = webapp2.Request(
       {
         'QUERY_STRING': 's2=b',
       },
       method='POST',
       body='{"s": "a"}',
   )
   msg = adapter.decode_message(EndpointsService.post.remote, request)
   self.assertEqual(msg.s, 'a')
   self.assertEqual(msg.s2, None)  # because it is not a ResourceContainer.
Пример #6
0
 def test_decode_message_get(self):
   request = webapp2.Request(
       {
         'QUERY_STRING': 's=a',
       },
       method='GET',
       route_kwargs={'s2': 'b'},
   )
   msg = adapter.decode_message(EndpointsService.get.remote, request)
   self.assertEqual(msg.s, 'a')
   self.assertEqual(msg.s2, 'b')
Пример #7
0
 def runTest(self):
     from dancedeets.servlets import event
     from dancedeets.app import app
     router = app.router
     env = {
         'SERVER_NAME': 'dev.dancedeets.com',
         'SERVER_PORT': '80',
         'PATH_INFO': '/events/55/',
     }
     route = router.match(webapp2.Request(env))
     self.assertEqual(route[0].handler, event.ShowEventHandler)
Пример #8
0
def SetupHandler(url, handler, post_data=None):
    """Sets up a RequestHandler object for testing."""
    request = webapp2.Request(webob.Request.blank(url).environ)
    response = webapp2.Response()
    if post_data is not None:
        request.method = 'POST'
        request.body = post_data
        request.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    handler.initialize(request, response)

    return handler
Пример #9
0
 def test_applicable_admin(self):
     os.environ.update({
         'USER_EMAIL': '*****@*****.**',
         'USER_ID': '123',
         'USER_IS_ADMIN': '1',
     })
     # Actual request is not used by CookieAuthentication.
     self.assertEqual((
         model.Identity(model.IDENTITY_USER, '*****@*****.**'),
         api.new_auth_details(is_superuser=True),
     ), handler.gae_cookie_authentication(webapp2.Request({})))
 def call(self, body=None, raw_token=None):
   if body:
     env = machine_token_pb2.MachineTokenEnvelope()
     env.token_body = body.SerializeToString()
     env.key_id = 'signing_key'
     env.rsa_sha256 = 'signature'
     raw_token = base64.b64encode(env.SerializeToString())
   req = webapp2.Request({})
   if raw_token:
     req.headers['X-Luci-Machine-Token'] = raw_token
   return machine_auth.machine_authentication(req)
Пример #11
0
def SetupRequest(path, lang='en', cookie_jar=None):
    """Sets up a webapp2.Request object for testing."""
    request = webapp2.Request(webob.Request.blank(ROOT_URL + path).environ)
    request.root_url = ROOT_URL
    request.root_path = ROOT_PATH
    request.lang = lang
    if cookie_jar is not None:
        # Cobble up a urllib2.Request for the CookieJar to put cookies in.
        req = urllib2.Request(request.url)
        cookie_jar.add_cookie_header(req)
        request.headers['Cookie'] = req.get_header('Cookie')
    return request
Пример #12
0
 def test_decode_message_get_resource_container(self):
   request = webapp2.Request(
       {
         'QUERY_STRING': 's=a',
       },
       method='GET',
       route_kwargs={'s2': 'b', 'x': 'c'},
   )
   rc = adapter.decode_message(
       EndpointsService.get_container.remote, request)
   self.assertEqual(rc.s, 'a')
   self.assertEqual(rc.s2, 'b')
   self.assertEqual(rc.x, 'c')
Пример #13
0
    def call(self, payload):
        def mocked_verify_jwt(token, certs):
            self.assertEqual(token, self.TOKEN)
            self.assertIs(certs, self.CERTS)
            if isinstance(payload, Exception):
                raise payload
            return None, payload

        self.mock(tokens, 'verify_jwt', mocked_verify_jwt)

        req = webapp2.Request({})
        if payload is not None:
            req.headers[gce_vm_auth.GCE_VM_TOKEN_HEADER] = self.TOKEN
        return gce_vm_auth.gce_vm_authentication(req)
Пример #14
0
 def __call__(self, environ, start_response):
     environ["TAILBONE_AUTH"] = "true"
     u = api.users.get_current_user()
     if u:
         # USER_ID is the only required var for authentication middleware compliance
         environ["TAILBONE_USER_ID"] = u.user_id()
         environ["TAILBONE_USER_EMAIL"] = u.email()
         environ["TAILBONE_USER_NICKNAME"] = u.nickname()
         environ["TAILBONE_USER_FEDERATED_IDENTITY"] = u.federated_identity(
         )
         environ["TAILBONE_USER_FEDERATED_PROVIDER"] = u.federated_provider(
         )
     req = webapp2.Request(environ)
     resp = req.get_response(self.app)
     return resp(environ, start_response)
Пример #15
0
    def __call__(self, environ, start_response):
        req = webapp2.Request(environ)
        resp = req.get_response(self.app)

        def copy_header(k):
            v = req.headers.get(k)
            if v:
                resp.headers[k] = v

        for x in ["Country", "Region", "City", "CityLatLong"]:
            k = "X-AppEngine-" + x
            copy_header(k)

        resp.headers["REMOTE_ADDR"] = req.remote_addr

        return resp(environ, start_response)
Пример #16
0
    def __call__(self, environ, start_response):
        request = webapp2.Request(environ, app=self.app)
        access_key = (request.get(settings.ACCESS_KEY_SET_COOKIE_PARAM_NAME)
                      or request.cookies.get(settings.ACCESS_KEY_COOKIE_NAME))
        if access_key:
            environ['mimic.access_key'] = access_key

        def custom_start_response(status, headers, exc_info=None):
            if access_key:
                # keep session cookies private
                headers.extend([
                    MakeCookieHeader(settings.ACCESS_KEY_COOKIE_NAME,
                                     access_key,
                                     settings.ACCESS_KEY_COOKIE_ARGS),
                    # Note App Engine automatically sets a 'Date' header for us. See
                    # https://developers.google.com/appengine/docs/python/runtime#Responses
                    ('Expires', settings.LONG_AGO),
                    ('Cache-Control', 'private, max-age=0'),
                ])
            return start_response(status, headers, exc_info)

        return self.app(environ, custom_start_response)
Пример #17
0
        #password = self.request.get('password') or None
        # Change #1281 - emergency maintenance due to security issues
        # user = redo auth.
        self.session['user'] = username
        #return webapp2.redirect('/', response=self.response)


config = {
    'webapp2_extras.sessions': {
        'secret_key': 'a793134b-c2c5-4cbf-973b-64ff7eea863a',
        'name': 'mannequin-moments',
    }
}

app = webapp2.WSGIApplication(
    [webapp2.Route('/', HomeHandler),
     webapp2.Route('/login', LoginHandler)],
    config=config)

p = os.environ.__dict__

request = webapp2.Request(p)
response = webapp2.Response()
request.app = app
a = LoginHandler(request, response)
a.dispatch()
a.post()
a.dispatch()
#a.session.set('user','admin')
print a.response
Пример #18
0
        self.status_code = 100

    def write(self, *argv):
        #log.info("DUMMYWRITE")
        pass


"""class dummystring (StringIO.StringIO):
    def __init__(self,x):
        super(dummystring,self).__init__()
    def __len__(self):
        return 0
"""
#dummyrequest = webapp2.RequestHandler(webapp2.Request({}),dummyresponse())
unit = ShowUnit()
unit.request = webapp2.Request({})
unit.response = dummyresponse()
setArguments(["_pageFlush"])
setAppVar("DEVELOPVERSION", "True")

setAppVar("DocsLocationOverride", "/docs/")
setAppVar(
    "DEBUGOUT",
    "<!-- Build for version: %s -->\n<!-- Build date: %s -->\n<!-- Build location: %s -->"
    % (TARGETVERSION, now, os.getcwd()))

setAppVar("LocationOverride", "docs")
for ext in [
        "", "auto", "bib", "health-lifesci", "meta", "pending", "iot", "attic"
]:
    setHostExt(ext)
Пример #19
0
 def test_non_applicable(self):
     request = webapp2.Request({})
     self.assertEqual((None, False),
                      handler.service_to_service_authentication(request))
Пример #20
0
 def test_non_applicable(self):
     request = webapp2.Request({})
     self.assertIsNone(handler.service_to_service_authentication(request))
Пример #21
0
 def test_non_applicable(self):
     self.assertEqual(
         (None, None),
         handler.gae_cookie_authentication(webapp2.Request({})))
Пример #22
0
 def test_non_applicable(self):
     self.assertIsNone(
         handler.gae_cookie_authentication(webapp2.Request({})))
Пример #23
0
 def request(self):
     request = webapp2.Request(environ=dict(os.environ))
     request.app = self.app
     return request
Пример #24
0
from __future__ import absolute_import, unicode_literals
import json
import unittest
from google.appengine.api import files
from google.appengine.ext import testbed
import webapp2
from webapp2_extras import i18n

# workaround for i18n. without this test will not run

app = webapp2.WSGIApplication(
    [webapp2.Route('/', None, name='upload_handler')])

request = webapp2.Request({
    'SERVER_NAME': 'test',
    'SERVER_PORT': 80,
    'wsgi.url_scheme': 'http'
})
request.app = app
app.set_globals(app=app, request=request)

i18n.default_config['default_locale'] = 'en_US'
i18n.default_config['default_timezone'] = 'UTC'

# End of workaround


class GAETestCase(unittest.TestCase):
    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.setup_env(app_id="_")
Пример #25
0
 def create_handler(self, query_string):
     environ = {}
     request = webapp2.Request(environ)
     request.query_string = query_string
     return ApiHandler(request=request)
Пример #26
0
 def handler(self):
     if not getattr(self, '_handler', None):
         req = webapp2.Request(dict(os.environ))
         req.app = webapp2.WSGIApplication(config=main.config)
         self._handler = base.BaseHandler(request=req)
     return self._handler
Пример #27
0
 def __call__(self, environ, start_response):
     request = webapp2.Request(environ, app=self.app)
     access_key = request.headers.get(settings.ACCESS_KEY_HTTP_HEADER)
     if access_key:
         environ['mimic.access_key'] = access_key
     return self.app(environ, start_response)