def _do_httplib_request(self, req):
        "Convert WebOb Request to httplib request."
        headers = {}

        for name, val in req.headers.items():
            if sys.version_info[0] == 2 and isinstance(name, unicode):
                name = str(name)
            headers[name] = val
        if req.scheme not in self.conn:
            self._load_conn(req.scheme)

        conn = self.conn[req.scheme]
        conn.request(req.method, req.path_qs, req.body, headers)

        if req.path_qs == '/kill':
            res = http.client.HTTPResponse(conn.sock)
            res.status_int = 200
            return res

        webresp = conn.getresponse()
        res = webtest.TestResponse()
        res.status = '%s %s' % (webresp.status, webresp.reason)
        res.body = webresp.read()
        response_headers = []
        if sys.version_info.major == 2:
            for headername in dict(webresp.getheaders()).keys():
                for headervalue in webresp.msg.getheaders(headername):
                    response_headers.append((headername, headervalue))
        else:
            response_headers = webresp.getheaders()
        res.headerlist = response_headers
        res.errors = ''
        return res
Ejemplo n.º 2
0
    def test_ndb_wsgi_middleware_properly_wraps_given_function(self) -> None:

        def wsgi_app_mock(
                environ: Dict[str, str],
                response: webtest.TestResponse
        ) -> webtest.TestResponse:
            """Mock WSGI app.

            Args:
                environ: dict. Environment variables.
                response: webtest.TestResponse. Response to return.

            Returns:
                webtest.TestResponse. Response.
            """
            self.assertEqual(environ, {'key': 'value'})
            self.assertEqual(type(response), webtest.TestResponse)
            return response

        def get_ndb_context_mock(
                global_cache: datastore_services.RedisCache
        ) -> ContextManager[None]:
            """Mock the NDB context.

            Args:
                global_cache: RedisCache. Cache used by the NDB.

            Returns:
                ContextManager. Context manager that does nothing.
            """
            self.assertEqual(type(global_cache), datastore_services.RedisCache)
            return contextlib.nullcontext()

        get_ndb_context_swap = self.swap_with_checks(
            datastore_services,
            'get_ndb_context',
            get_ndb_context_mock
        )

        # Create middleware that wraps wsgi_app_mock.
        # The function 'wsgi_app_mock' is casted to be of type WSGIApplication
        # because we are passing it as a WSGIApplication not as a function.
        middleware = main.NdbWsgiMiddleware(
            cast(webapp2.WSGIApplication, wsgi_app_mock))
        test_response = webtest.TestResponse()

        # Verify that NdbWsgiMiddleware keeps the test_response the same.
        with get_ndb_context_swap:
            self.assertEqual(
                middleware({'key': 'value'}, test_response), test_response)
Ejemplo n.º 3
0
    def _do_httplib_request(self, req):
        "Convert WebOb Request to httplib request."
        headers = dict((name, val) for name, val in req.headers.items()
                       if name != 'Host')
        if req.scheme not in self.conn:
            self._load_conn(req.scheme)

        conn = self.conn[req.scheme]
        conn.request(req.method, req.path_qs, req.body, headers)

        webresp = conn.getresponse()
        res = webtest.TestResponse()
        res.status = '%s %s' % (webresp.status, webresp.reason)
        res.body = webresp.read()
        res.headerlist = webresp.getheaders()
        res.errors = ''
        return res
Ejemplo n.º 4
0
    def test_ndb_wsgi_middleware_properly_wraps_given_function(self) -> None:
        def wsgi_app_mock(
                environ: Dict[str, str],
                response: webtest.TestResponse) -> webtest.TestResponse:
            """Mock WSGI app.

            Args:
                environ: dict. Environment variables.
                response: webtest.TestResponse. Response to return.

            Returns:
                webtest.TestResponse. Response.
            """
            self.assertEqual(environ, {'key': 'value'})
            self.assertEqual(type(response), webtest.TestResponse)
            return response

        # TODO(13427): Replace Any with proper type after we can import types
        # from datastore_services.
        def get_ndb_context_mock(global_cache: Any) -> ContextManager[None]:
            """Mock the NDB context.

            Args:
                global_cache: RedisCache. Cache used by the NDB.

            Returns:
                ContextManager. Context manager that does nothing.
            """
            self.assertEqual(type(global_cache), datastore_services.RedisCache)
            return contextlib.nullcontext()

        get_ndb_context_swap = self.swap_with_checks(datastore_services,
                                                     'get_ndb_context',
                                                     get_ndb_context_mock)

        # Create middleware that wraps wsgi_app_mock.
        middleware = main.NdbWsgiMiddleware(wsgi_app_mock)
        test_response = webtest.TestResponse()

        # Verify that NdbWsgiMiddleware keeps the test_response the same.
        with get_ndb_context_swap:
            self.assertEqual(middleware({'key': 'value'}, test_response),
                             test_response)
Ejemplo n.º 5
0
    def _do_httplib_request(self, req):
        "Convert WebOb Request to httplib request."
        headers = dict((name, val) for name, val in req.headers.iteritems())
        if req.scheme not in self.conn:
            self._load_conn(req.scheme)

        conn = self.conn[req.scheme]
        conn.request(req.method, req.path_qs, req.body, headers)

        webresp = conn.getresponse()
        res = webtest.TestResponse()
        res.status = '%s %s' % (webresp.status, webresp.reason)
        res.body = webresp.read()
        response_headers = []
        for headername in dict(webresp.getheaders()).keys():
            for headervalue in webresp.msg.getheaders(headername):
                response_headers.append((headername, headervalue))
        res.headerlist = response_headers
        res.errors = ''
        return res