Esempio n. 1
0
 def __call__(self, value):
     if type(value) in (str, bytes):
         try:
             return json_converter.loads(value)
         except Exception:
             raise ValueError('Incorrectly formatted JSON provided')
     if type(value) is list:
         # If Falcon is set to comma-separate entries, this segment joins them again.
         try:
             fixed_value = ",".join(value)
             return json_converter.loads(fixed_value)
         except Exception:
             raise ValueError('Incorrectly formatted JSON provided')
     else:
         return value
Esempio n. 2
0
File: types.py Progetto: zxy-zxy/hug
 def __call__(self, value):
     if type(value) in (str, bytes):
         try:
             return json_converter.loads(value)
         except Exception:
             raise ValueError('Incorrectly formatted JSON provided')
     if type(value) is list:
         # If Falcon is set to comma-separate entries, this segment joins them again.
         try:
             fixed_value = ",".join(value)
             return json_converter.loads(fixed_value)
         except Exception:
             raise ValueError('Incorrectly formatted JSON provided')
     else:
         return value
Esempio n. 3
0
File: test.py Progetto: zxy-zxy/hug
def call(method, api_or_module, url, body='', headers=None, params=None, query_string='', scheme='http', **kwargs):
    """Simulates a round-trip call against the given API / URL"""
    api = API(api_or_module).http.server()
    response = StartResponseMock()
    headers = {} if headers is None else headers
    if not isinstance(body, str) and 'json' in headers.get('content-type', 'application/json'):
        body = output_format.json(body)
        headers.setdefault('content-type', 'application/json')

    params = params if params else {}
    params.update(kwargs)
    if params:
        query_string = '{}{}{}'.format(query_string, '&' if query_string else '', urlencode(params, True))
    result = api(create_environ(path=url, method=method, headers=headers, query_string=query_string,
                                body=body, scheme=scheme), response)
    if result:
        try:
            response.data = result[0].decode('utf8')
        except TypeError:
            data = BytesIO()
            for chunk in result:
                data.write(chunk)
            data = data.getvalue()
            try:
                response.data = data.decode('utf8')
            except UnicodeDecodeError:   # pragma: no cover
                response.data = data
        except (UnicodeDecodeError, AttributeError):
            response.data = result[0]
        response.content_type = response.headers_dict['content-type']
        if 'application/json' in response.content_type:
            response.data = json.loads(response.data)

    return response
Esempio n. 4
0
 def __call__(self, value):
     if type(value) in (str, bytes):
         try:
             return json_converter.loads(value)
         except Exception:
             raise ValueError('Incorrectly formatted JSON provided')
     else:
         return value
Esempio n. 5
0
def call(method,
         api_or_module,
         url,
         body='',
         headers=None,
         params=None,
         query_string='',
         scheme='http',
         **kwargs):
    """Simulates a round-trip call against the given API / URL"""
    api = API(api_or_module).http.server()
    response = StartResponseMock()
    headers = {} if headers is None else headers
    if not isinstance(body, str) and 'json' in headers.get(
            'content-type', 'application/json'):
        body = output_format.json(body)
        headers.setdefault('content-type', 'application/json')

    params = params if params else {}
    params.update(kwargs)
    if params:
        query_string = '{}{}{}'.format(query_string,
                                       '&' if query_string else '',
                                       urlencode(params, True))
    result = api(
        create_environ(path=url,
                       method=method,
                       headers=headers,
                       query_string=query_string,
                       body=body,
                       scheme=scheme), response)
    if result:
        try:
            response.data = result[0].decode('utf8')
        except TypeError:
            data = BytesIO()
            for chunk in result:
                data.write(chunk)
            data = data.getvalue()
            try:
                response.data = data.decode('utf8')
            except UnicodeDecodeError:  # pragma: no cover
                response.data = data
        except (UnicodeDecodeError, AttributeError):
            response.data = result[0]
        response.content_type = response.headers_dict['content-type']
        if 'application/json' in response.content_type:
            response.data = json.loads(response.data)

    return response
Esempio n. 6
0
File: test.py Progetto: byo-ai/hug
def cli(method, *args, api=None, module=None, **arguments):
    """Simulates testing a hug cli method from the command line"""
    collect_output = arguments.pop('collect_output', True)
    if api and module:
        raise ValueError(
            "Please specify an API OR a Module that contains the API, not both"
        )
    elif api or module:
        method = API(api or module).cli.commands[method].interface._function

    command_args = [method.__name__] + list(args)
    for name, values in arguments.items():
        if not isinstance(values, (tuple, list)):
            values = (values, )
        for value in values:
            command_args.append('--{0}'.format(name))
            if not value in (True, False):
                command_args.append('{0}'.format(value))

    old_sys_argv = sys.argv
    sys.argv = [str(part) for part in command_args]

    old_outputs = method.interface.cli.outputs
    if collect_output:
        method.interface.cli.outputs = lambda data: to_return.append(
            old_outputs(data))
    to_return = []

    try:
        method.interface.cli()
    except Exception as e:
        to_return = (e, )

    method.interface.cli.outputs = old_outputs
    sys.argv = old_sys_argv
    if to_return:
        result = _internal_result(to_return)
        try:
            result = json.loads(result)
        except Exception:
            try:
                result = ast.literal_eval(result)
            except Exception:
                pass
        return result
Esempio n. 7
0
def call(method,
         api_or_module,
         url,
         body="",
         headers=None,
         params=None,
         query_string="",
         scheme="http",
         host=DEFAULT_HOST,
         **kwargs):
    """Simulates a round-trip call against the given API / URL"""
    api = API(api_or_module).http.server()
    response = StartResponseMock()
    headers = {} if headers is None else headers
    if not isinstance(body, str) and "json" in headers.get(
            "content-type", "application/json"):
        body = output_format.json(body)
        headers.setdefault("content-type", "application/json")

    params = params if params else {}
    params.update(kwargs)
    if params:
        query_string = "{}{}{}".format(query_string,
                                       "&" if query_string else "",
                                       urlencode(params, True))
    result = api(
        create_environ(
            path=url,
            method=method,
            headers=headers,
            query_string=query_string,
            body=body,
            scheme=scheme,
            host=host,
        ),
        response,
    )
    if result:
        response.data = _internal_result(result)
        response.content_type = response.headers_dict["content-type"]
        if "application/json" in response.content_type:
            response.data = json.loads(response.data)
    return response
Esempio n. 8
0
def call(method,
         api_or_module,
         url,
         body='',
         headers=None,
         params=None,
         query_string='',
         scheme='http',
         **kwargs):
    """Simulates a round-trip call against the given API / URL"""
    api = API(api_or_module).http.server()
    response = StartResponseMock()
    headers = {} if headers is None else headers
    if not isinstance(body, str) and 'json' in headers.get(
            'content-type', 'application/json'):
        body = output_format.json(body)
        headers.setdefault('content-type', 'application/json')

    params = params if params else {}
    params.update(kwargs)
    if params:
        query_string = '{}{}{}'.format(query_string,
                                       '&' if query_string else '',
                                       urlencode(params, True))
    result = api(
        create_environ(path=url,
                       method=method,
                       headers=headers,
                       query_string=query_string,
                       body=body,
                       scheme=scheme), response)
    if result:
        response.data = _internal_result(result)
        response.content_type = response.headers_dict['content-type']
        if 'application/json' in response.content_type:
            response.data = json.loads(response.data)
    return response
Esempio n. 9
0
def json(body, charset='utf-8', **kwargs):
    """Takes JSON formatted data, converting it into native Python objects"""
    return json_converter.loads(text(body, charset=charset))
Esempio n. 10
0
def json(body, charset='utf-8', **kwargs):
    """Takes JSON formatted data, converting it into native Python objects"""
    return json_converter.loads(text(body, charset=charset))