コード例 #1
0
    def test_application_exception(self) -> None:
        """Tests application(), exception catching case."""
        environ = {"PATH_INFO": "/"}

        def start_response(status: str,
                           response_headers: List[Tuple[str, str]]) -> None:
            self.assertTrue(status.startswith("500"))
            header_dict = dict(response_headers)
            self.assertEqual(header_dict["Content-type"],
                             "text/html; charset=utf-8")

        def mock_application(
                environ: Dict[str, Any],
                start_response: 'StartResponse') -> Iterable[bytes]:
            int("a")
            # Never reached.
            return wsgi.our_application(environ, start_response)

        with unittest.mock.patch('wsgi.our_application', mock_application):
            callback = cast('StartResponse', start_response)
            output_iterable = wsgi.application(environ, callback)
            output_list = cast(List[bytes], output_iterable)
            self.assertTrue(output_list)
            output = output_list[0].decode('utf-8')
            self.assertIn("ValueError", output)
コード例 #2
0
ファイル: test_wsgi.py プロジェクト: tamas-marton/osm-gimmisn
    def get_dom_for_path(self,
                         path: str,
                         absolute: bool = False,
                         expected_status: str = "") -> ET.Element:
        """Generates an XML DOM for a given wsgi path."""
        if not expected_status:
            expected_status = "200 OK"

        def start_response(status: str,
                           response_headers: List[Tuple[str, str]]) -> None:
            # Make sure the built-in exception catcher is not kicking in.
            self.assertEqual(status, expected_status)
            header_dict = dict(response_headers)
            self.assertEqual(header_dict["Content-type"],
                             "text/html; charset=utf-8")

        prefix = config.Config.get_uri_prefix()
        if not absolute:
            path = prefix + path
        environ = {"PATH_INFO": path}
        if self.gzip_compress:
            environ["HTTP_ACCEPT_ENCODING"] = "gzip, deflate"
        callback = cast('StartResponse', start_response)
        output_iterable = wsgi.application(environ, callback)
        output_list = cast(List[bytes], output_iterable)
        self.assertTrue(output_list)
        if self.gzip_compress:
            output_bytes = xmlrpc.client.gzip_decode(output_list[0])
        else:
            output_bytes = output_list[0]
        output = output_bytes.decode('utf-8')
        stream = io.StringIO(output)
        tree = ET.parse(stream)
        root = tree.getroot()
        return root
コード例 #3
0
ファイル: test.py プロジェクト: HackerDom/ructfe-2014
def run_with_cgi(application, method, url, _in, _length, query):
    environ = dict()
    environ['wsgi.input'] = _in
    environ['CONTENT_LENGTH'] = _length
    environ['wsgi.errors'] = sys.stderr
    environ['wsgi.version'] = (1, 0)
    environ['wsgi.multithread'] = False
    environ['wsgi.multiprocess'] = True
    environ['wsgi.run_once'] = True
    environ['wsgi.url_scheme'] = 'http'
    environ['PATH_INFO'] = url
    environ['REQUEST_METHOD'] = method.upper()
    environ['QUERY_STRING'] = query

    _status = None
    _response_headers = None

    def start_response(status, response_headers):
        nonlocal _status, _response_headers
        _status = status
        _response_headers = response_headers

    result = application(environ, start_response)
    output = [data for data in result]
    return _status, _response_headers, output
コード例 #4
0
ファイル: request.py プロジェクト: samalba/image-spider
def request(method, resource, query_string='', post_data=''):

    """
    HTTP request stub.

    Arguments:
        method: string HTTP method.
        resource: string REST resource.
        query_string: optional string HTTP query string.
        post_data: optional string HTTP post data.

    Returns: dict having:
        http_status: string HTTP response status code and description.
        other_headers: list of tuples, each a name-value pair of HTTP response
                       headers other than the status.
        content: string HTTP response content.
    """

    result = {}

    def store_headers(http_status, other_headers):
        result['http_status'] = http_status
        result['other_headers'] = other_headers

    env = {'REQUEST_METHOD': method.upper(),
           'PATH_INFO': resource,
           'QUERY_STRING': query_string,
           'wsgi.input': WsgiInputStub(post_data)}

    if 'POST' == method:
        env['CONTENT_LENGTH'] = len(post_data)

    result['content'] = wsgi.application(env, store_headers)

    return result
コード例 #5
0
def run_with_cgi(application, method, url, _in, _length, query):
    environ = dict()
    environ['wsgi.input'] = _in
    environ['CONTENT_LENGTH'] = _length
    environ['wsgi.errors'] = sys.stderr
    environ['wsgi.version'] = (1, 0)
    environ['wsgi.multithread'] = False
    environ['wsgi.multiprocess'] = True
    environ['wsgi.run_once'] = True
    environ['wsgi.url_scheme'] = 'http'
    environ['PATH_INFO'] = url
    environ['REQUEST_METHOD'] = method.upper()
    environ['QUERY_STRING'] = query

    _status = None
    _response_headers = None

    def start_response(status, response_headers):
        nonlocal _status, _response_headers
        _status = status
        _response_headers = response_headers

    result = application(environ, start_response)
    output = [data for data in result]
    return _status, _response_headers, output
コード例 #6
0
    def get_dom_for_path(self, path: str) -> ET.Element:
        """Generates an XML DOM for a given wsgi path."""
        def start_response(status: str,
                           response_headers: List[Tuple[str, str]]) -> None:
            # Make sure the built-in exception catcher is not kicking in.
            self.assertEqual(status, "200 OK")
            header_dict = {key: value for (key, value) in response_headers}
            self.assertEqual(header_dict["Content-type"],
                             "text/html; charset=utf-8")

        def get_abspath(path: str) -> str:
            if os.path.isabs(path):
                return path
            return os.path.join(os.path.dirname(__file__), path)

        with unittest.mock.patch('util.get_abspath', get_abspath):
            environ = {"PATH_INFO": path}
            callback = cast('StartResponse',
                            start_response)  # type: StartResponse
            output_iterable = wsgi.application(environ, callback)
            output_list = cast(List[bytes], output_iterable)
            self.assertTrue(output_list)
            output = output_list[0].decode('utf-8')
            stream = io.StringIO(output)
            tree = ET.parse(stream)
            root = tree.getroot()
            return root
コード例 #7
0
ファイル: app.py プロジェクト: flyiniggle/hitched
def mount(conf):
    def CORS():
        cherrypy.response.headers["Access-Control-Allow-Origin"] = os.environ['OPENSHIFT_APP_DNS']

    cherrypy.config.update({"tools.staticdir.root": files.get_root()})
    cherrypy.config.update(conf)
    cherrypy.tools.CORS = cherrypy.Tool('before_handler', CORS)
    cherrypy.tree.mount(wsgi.application(), "/", conf)
コード例 #8
0
ファイル: test_wsgi.py プロジェクト: meskobalazs/osm-gimmisn
    def get_css_for_path(self, path: str) -> str:
        """Generates a string for a given wsgi path."""
        def start_response(status: str,
                           response_headers: List[Tuple[str, str]]) -> None:
            # Make sure the built-in exception catcher is not kicking in.
            self.assertEqual(status, "200 OK")
            header_dict = dict(response_headers)
            self.assertEqual(header_dict["Content-type"],
                             "text/css; charset=utf-8")

        prefix = config.Config.get_uri_prefix()
        environ = {"PATH_INFO": prefix + path}
        callback = cast('StartResponse', start_response)
        output_iterable = wsgi.application(environ, callback)
        output_list = cast(List[bytes], output_iterable)
        self.assertTrue(output_list)
        output = output_list[0].decode('utf-8')
        return output
コード例 #9
0
    def get_js_for_path(self, path: str) -> str:
        """Generates a string for a given wsgi path."""
        def start_response(status: str,
                           response_headers: List[Tuple[str, str]]) -> None:
            # Make sure the built-in exception catcher is not kicking in.
            self.assertEqual(status, "200 OK")
            header_dict = dict(response_headers)
            self.assertEqual(header_dict["Content-type"],
                             "application/x-javascript; charset=utf-8")

        with unittest.mock.patch('util.get_abspath', get_abspath):
            environ = {"PATH_INFO": path}
            callback = cast('StartResponse', start_response)
            output_iterable = wsgi.application(environ, callback)
            output_list = cast(List[bytes], output_iterable)
            self.assertTrue(output_list)
            output = output_list[0].decode('utf-8')
            return output
コード例 #10
0
    def get_json_for_path(self, ctx: context.Context,
                          path: str) -> Dict[str, Any]:
        """Generates an json dict for a given wsgi path."""
        def start_response(status: str,
                           response_headers: List[Tuple[str, str]]) -> None:
            # Make sure the built-in exception catcher is not kicking in.
            self.assertEqual(status, "200 OK")
            header_dict = dict(response_headers)
            self.assertEqual(header_dict["Content-type"],
                             "application/json; charset=utf-8")

        prefix = ctx.get_ini().get_uri_prefix()
        environ = {"PATH_INFO": prefix + path}
        callback = cast('StartResponse', start_response)
        output_iterable = wsgi.application(environ, callback, ctx)
        output_list = cast(List[str], output_iterable)
        self.assertTrue(output_list)
        output = output_list[0]
        return cast(Dict[str, Any], json.loads(output))
コード例 #11
0
ファイル: test_wsgi.py プロジェクト: urbalazs/osm-gimmisn
    def test_application_exception(self) -> None:
        """Tests application(), exception catching case."""
        ctx = test_context.make_test_context()
        ctx.set_unit(test_context.TestUnit())
        environ = {
            "PATH_INFO": "/"
        }

        def start_response(status: str, response_headers: List[Tuple[str, str]]) -> None:
            self.assertTrue(status.startswith("500"))
            header_dict = dict(response_headers)
            self.assertEqual(header_dict["Content-type"], "text/html; charset=utf-8")

        callback = cast('StartResponse', start_response)

        output_iterable = wsgi.application(environ, callback, ctx)

        output_list = cast(List[bytes], output_iterable)
        self.assertTrue(output_list)
        output = output_list[0].decode('utf-8')
        self.assertIn("TestError", output)
コード例 #12
0
    def get_dom_for_path(self, path: str) -> ET.Element:
        """Generates an XML DOM for a given wsgi path."""
        def start_response(status: str,
                           response_headers: List[Tuple[str, str]]) -> None:
            # Make sure the built-in exception catcher is not kicking in.
            self.assertEqual(status, "200 OK")
            header_dict = dict(response_headers)
            self.assertEqual(header_dict["Content-type"],
                             "text/html; charset=utf-8")

        with unittest.mock.patch('config.get_abspath', get_abspath):
            prefix = config.Config.get_uri_prefix()
            environ = {"PATH_INFO": prefix + path}
            callback = cast('StartResponse', start_response)
            output_iterable = wsgi.application(environ, callback)
            output_list = cast(List[bytes], output_iterable)
            self.assertTrue(output_list)
            output = output_list[0].decode('utf-8')
            stream = io.StringIO(output)
            tree = ET.parse(stream)
            root = tree.getroot()
            return root
コード例 #13
0
def request(method, resource, query_string='', post_data=''):
    """
    HTTP request stub.

    Arguments:
        method: string HTTP method.
        resource: string REST resource.
        query_string: optional string HTTP query string.
        post_data: optional string HTTP post data.

    Returns: dict having:
        http_status: string HTTP response status code and description.
        other_headers: list of tuples, each a name-value pair of HTTP response
                       headers other than the status.
        content: string HTTP response content.
    """

    result = {}

    def store_headers(http_status, other_headers):
        result['http_status'] = http_status
        result['other_headers'] = other_headers

    env = {
        'REQUEST_METHOD': method.upper(),
        'PATH_INFO': resource,
        'QUERY_STRING': query_string,
        'wsgi.input': WsgiInputStub(post_data)
    }

    if 'POST' == method:
        env['CONTENT_LENGTH'] = len(post_data)

    result['content'] = wsgi.application(env, store_headers)

    return result
コード例 #14
0
 def app(environ: Dict[str, Any],
         start_response: 'StartResponse') -> Iterable[bytes]:
     return wsgi.application(environ, start_response, ctx)
コード例 #15
0
def test_application():
    '''Verify application returns our hello world'''
    assert_equals(['Hello world'], application('', lambda x, y: (x, y)))
コード例 #16
0
def test_application():
    """Verify application returns our hello world"""
    assert_equals(["Hello world"], application("", lambda x, y: (x, y)))