Пример #1
0
def test_with_timeouts(mock_marshal_param, minimal_swagger_spec, getPetById_spec, request_dict, timeout_kv):
    request_dict["url"] = "/pet/{petId}"
    op = CallableOperation(Operation.from_spec(minimal_swagger_spec, "/pet/{petId}", "get", getPetById_spec))
    k, v = timeout_kv
    request = construct_request(op, request_options={k: v}, petId=34)
    assert request[k] == v
    assert mock_marshal_param.call_count == 1
Пример #2
0
    def __call__(self, _token=None, **op_kwargs):
        """Invoke the actual HTTP request and return a future.

        :rtype: :class:`bravado.http_future.HTTPFuture`
        """
        warn_for_deprecated_op(self.operation)

        # Apply request_options defaults
        request_options = op_kwargs.pop('_request_options', {})
        request_config = RequestConfig(request_options,
                                       also_return_response_default=True)

        request_params = construct_request(
            self.operation, request_options, **op_kwargs)

        # config = self.operation.swagger_spec.config
        http_client = self.operation.swagger_spec.http_client

        # Per-request config overrides client wide config
        # also_return_response = request_options.get(
        #     'also_return_response',
        #     config['also_return_response'])

        # Check if we need an authorization token and if so set it up
        if self.require_authorization and _token is None:
            raise ESIAuthorizationError('Missing required authorization token')

        return http_client.request(
            request_params,
            operation=self.operation,
            request_config=request_config,
            authorization_token=_token)
Пример #3
0
def invoke(op, *args, **kwargs):
    if op.http_method != 'get':
        clickclick.action('Invoking..')
    request = construct_request(op, {}, **kwargs)
    c = RequestsClient()
    future = c.request(request)
    future.result()
    clickclick.ok()
Пример #4
0
def test_with_not_string_headers(
    minimal_swagger_dict,
    getPetById_spec,
    request_dict,
    swagger_type,
    swagger_format,
    header_name,
    header_value,
):
    url = '/pet/{petId}'
    parameter = {
        'name': header_name,
        'in': 'header',
        'required': False,
        'type': swagger_type,
    }
    if swagger_format:
        parameter['format'] = swagger_format
    minimal_swagger_dict['paths'][url]['get']['parameters'].append(parameter)

    minimal_swagger_spec = build_swagger_spec(minimal_swagger_dict)
    request_dict['url'] = url

    operation = Operation.from_spec(
        swagger_spec=minimal_swagger_spec,
        path_name='/pet/{petId}',
        http_method='get',
        op_spec=getPetById_spec,
    )

    petId = 34
    api_key = 'foo'
    request = construct_request(
        operation=operation,
        request_options={'headers': {
            header_name: header_value
        }},
        petId=petId,
        api_key=api_key,
    )

    # To unmarshall a request bravado-core needs the request to be wrapped
    # by an object with a specific list of attributes
    request_object = type(
        'IncomingRequest', (IncomingRequest, ), {
            'path': {
                'petId': petId
            },
            'query': {},
            'form': {},
            'headers': request['headers'],
            'files': mock.Mock(),
        })

    assert request['headers'][header_name] == str(header_value)
    unmarshalled_request = unmarshal_request(request_object, operation)
    assert unmarshalled_request[header_name] == header_value
Пример #5
0
def test_with_timeouts(mock_marshal_param, minimal_swagger_spec,
                       getPetById_spec, request_dict, timeout_kv):
    request_dict['url'] = '/pet/{petId}'
    op = CallableOperation(Operation.from_spec(
        minimal_swagger_spec, '/pet/{petId}', 'get', getPetById_spec))
    k, v = timeout_kv
    request = construct_request(op, request_options={k: v}, petId=34, api_key='foo')
    assert request[k] == v
    assert mock_marshal_param.call_count == 2
Пример #6
0
def test_with_timeouts(
    mock_marshal_param, minimal_swagger_spec,
    getPetById_spec, request_dict, timeout_kv,
):
    request_dict['url'] = '/pet/{petId}'
    op = CallableOperation(Operation.from_spec(
        minimal_swagger_spec, '/pet/{petId}', 'get', getPetById_spec))
    k, v = timeout_kv
    request = construct_request(op, request_options={k: v}, petId=34, api_key='foo')
    assert request[k] == v
    assert mock_marshal_param.call_count == 2
Пример #7
0
def test_with_not_string_headers(
    minimal_swagger_dict, getPetById_spec, request_dict,
    swagger_type, swagger_format, header_name, header_value,
):
    url = '/pet/{petId}'
    parameter = {
        'name': header_name,
        'in': 'header',
        'required': False,
        'type': swagger_type,
    }
    if swagger_format:
        parameter['format'] = swagger_format
    minimal_swagger_dict['paths'][url]['get']['parameters'].append(parameter)

    minimal_swagger_spec = build_swagger_spec(minimal_swagger_dict)
    request_dict['url'] = url

    operation = Operation.from_spec(
        swagger_spec=minimal_swagger_spec,
        path_name='/pet/{petId}',
        http_method='get',
        op_spec=getPetById_spec,
    )

    petId = 34
    api_key = 'foo'
    request = construct_request(
        operation=operation,
        request_options={'headers': {header_name: header_value}},
        petId=petId,
        api_key=api_key,
    )

    # To unmarshall a request bravado-core needs the request to be wrapped
    # by an object with a specific list of attributes
    request_object = type('IncomingRequest', (IncomingRequest,), {
        'path': {'petId': petId},
        'query': {},
        'form': {},
        'headers': request['headers'],
        'files': mock.Mock(),
    })

    expected_header_value = str(header_value)
    # we need to handle a backwards-incompatible change in bravado-core 5.0.5
    if swagger_type == 'boolean':
        assert request['headers'][header_name] in (expected_header_value, expected_header_value.lower())
    else:
        assert request['headers'][header_name] == expected_header_value

    unmarshalled_request = unmarshal_request(request_object, operation)
    assert unmarshalled_request[header_name] == header_value
Пример #8
0
def test_use_msgpack(
    minimal_swagger_spec,
    getPetById_spec,
):
    op = CallableOperation(
        Operation.from_spec(minimal_swagger_spec, '/pet/{petId}', 'get',
                            getPetById_spec))
    request = construct_request(
        op,
        request_options={
            'use_msgpack': True,
        },
        petId=1,
    )
    assert request['headers']['Accept'] == 'application/msgpack'
Пример #9
0
def test_use_msgpack(
    minimal_swagger_spec,
    getPetById_spec,
):
    op = CallableOperation(
        Operation.from_spec(
            minimal_swagger_spec,
            '/pet/{petId}',
            'get',
            getPetById_spec
        )
    )
    request = construct_request(
        op,
        request_options={
            'use_msgpack': True,
        },
        petId=1,
    )
    assert request['headers']['Accept'] == 'application/msgpack'
Пример #10
0
def test_use_msgpack(
    minimal_swagger_spec,
    getPetById_spec,
):
    op = CallableOperation(
        Operation.from_spec(minimal_swagger_spec, '/pet/{petId}', 'get',
                            getPetById_spec))
    request_options = {
        'use_msgpack': True,
        'headers': {
            'Some-Header': 'header-value'
        }
    }  # type: Dict[str, Any]
    request = construct_request(
        op,
        request_options=request_options,
        petId=1,
    )
    assert request['headers']['Accept'] == 'application/msgpack'
    assert request['headers']['Some-Header'] == 'header-value', \
        "Requested header should be present"
    assert 'Accept' not in request_options['headers'], \
        "Original request options should not be modified"
Пример #11
0
    def _bravado_construct_request(self):
        """
        An example request dict from swagger's pet store application looks like:

        {'url': u'http://petstore.swagger.io/v2/pet/42',
         'headers': {},
         'params': {},
         'method': 'DELETE'}

        Or also like:

        {'url': u'http://petstore.swagger.io/v2/pet/42',
         'headers': {u'api_key': 'FrAmE30.'},
         'params': {},
         'method': 'DELETE'}

        :return: The dict
        """
        parameters = self._get_filled_parameters()

        return construct_request(self.operation,
                                 request_options={},
                                 **parameters)
Пример #12
0
def ro_opInvokeCapture(roOp, ):
    ####+END:

    pp = pprint.PrettyPrinter(indent=4)

    #icm.TM_here("svcSpec={svcSpec} -- perfSap={perfSap}".format(svcSpec=roOp.svcSpec, perfSap=roOp.perfSap))

    loadedSvcSpec, origin_url = loadSvcSpec(roOp.svcSpec, roOp.perfSap)

    if roOp.perfSap:
        #origin_url = "http://localhost:8080"
        origin_url = roOp.perfSap

    #
    # NOTYET LOG level changes here
    #
    #icm.TM_here("{}".format(pp.pformat(loadedSvcSpec)))

    opBravadoObj = getOperationWithResourceAndOpName(
        loadedSvcSpec,
        origin_url,
        roOp.resource,
        roOp.opName,
    )

    if not opBravadoObj:
        icm.EH_problem_usageError(
            """getOperationWithResourceAndOpName Failed: resource={resource} opName={opName}"""
            .format(
                resource=roOp.resource,
                opName=roOp.opName,
            ))
        return None

    requestOptions = dict()

    params = roOp.roParams

    headerParams = params.headerParams
    if headerParams:
        requestOptions["headers"] = headerParams

    urlParams = params.urlParams
    if urlParams == None:
        urlParams = dict()

    bodyParams = params.bodyParams
    icm.TM_here("{}".format(pp.pformat(bodyParams)))
    if bodyParams:
        #
        # With ** we achieve kwargs
        #
        #  func(**{'type':'Event'}) is equivalent to func(type='Event')
        #
        request = construct_request(opBravadoObj,
                                    requestOptions,
                                    body=bodyParams,
                                    **urlParams)
    else:
        request = construct_request(opBravadoObj, requestOptions, **urlParams)

    icm.LOG_here("request={request}".format(request=pp.pformat(request)))

    c = RequestsClient()

    #
    # This is where the invoke request goes out
    #
    future = c.request(request)

    #
    # This where the invoke response comes in
    #

    opResults = {}
    try:
        result = future.result()
    except Exception as e:
        #icm.EH_critical_exception(e)
        opResults = None

        roResults = ro.Ro_Results(
            httpResultCode=500,  # type=int
            httpResultText="Internal Server Error",  # type=str
            opResults=opResults,
            opResultHeaders=None,
        )

    if opResults != None:

        #
        # result
        #
        # 2018-10-01 -- https://github.com/Yelp/bravado/blob/master/bravado/requests_client.py
        # class RequestsResponseAdapter(IncomingResponse):
        #
        # type(result._delegate.text) = unicode
        # type(result._delegate.content) = str
        #

        opResults = None

        if result._delegate.content:
            try:
                opResults = result.json()
            except Exception as e:
                icm.EH_critical_exception(e)
                opResults = None

        roResults = ro.Ro_Results(
            httpResultCode=result._delegate.status_code,  # type=int
            httpResultText=result._delegate.reason,  # type=str
            opResults=opResults,
            opResultHeaders=result._delegate.headers,
        )

        icm.LOG_here(
            "RESPONSE: status_code={status_code} -- reason={reason} -- text={text}"
            .format(
                status_code=result._delegate.status_code,
                reason=result._delegate.reason,
                text=result._delegate.text,
            ))

        icm.LOG_here("RESPONSE: responseHeaders: {headers}".format(
            headers=pp.pformat(result._delegate.headers)))

    roOp.roResults = roResults

    return roOp
Пример #13
0
def opInvoke(headers, op, *args, **kwargs):
    ####+END:
    """ NOTYET, Important, opInvoke should be layered on  top of opInvokeCapture """

    pp = pprint.PrettyPrinter(indent=4)

    headerLines = list()
    if headers:
        with open(headers, 'rb') as file:
            headerLines = file.readlines()

    # else:
    #     print("Has No Headers")

    headerLinesAsDict = dict()
    for each in headerLines:
        headerLineAsList = each.split(":")
        headerLineAsListLen = len(headerLineAsList)

        if headerLineAsListLen == 2:
            headerLineTag = headerLineAsList[0]
            headerLineValue = headerLineAsList[1]
        else:
            icm.EH_problem_usageError(
                "Expected 2: {}".format(headerLineAsListLen))
            continue

        headerLinesAsDict[headerLineTag] = headerLineValue.lstrip(' ').rstrip()

    requestOptions = dict()

    if headerLinesAsDict:
        requestOptions["headers"] = headerLinesAsDict

    def bodyArgToDict(
        bodyAny,
        bodyFile,
        bodyStr,
        bodyFunc,
    ):
        """ Returns None if all Args were None, and returns "" if one of the args was "", Otherwize a dict or {}."""
        def bodyStrAsDict(bodyStr):
            return ast.literal_eval(bodyStr)

        def bodyFileAsDict(bodyFile):
            with open(bodyFile, 'r') as myfile:
                data = myfile.read().replace('\n', '')
            return ast.literal_eval(data)

        def bodyFuncAsDict(bodyFunc):
            resDict = eval(bodyFunc)
            # NOTYET, verify that we have a dict
            return resDict

        if bodyAny != None:
            icm.TM_here("bodyAny={}".format(pp.pformat(bodyAny)))

            if bodyAny == "":
                return ""

            # Be it file, function or string
            if os.path.isfile(bodyAny):
                return bodyFileAsDict(bodyAny)
            elif bodyAny == "NOTYET-valid func":
                return bodyFuncAsDict(bodyAny)
            else:
                # We then take bodyAny to be a string
                return bodyStrAsDict(bodyAny)

        elif bodyFile != None:
            icm.TM_here("bodyFile={}".format(pp.pformat(bodyFile)))

            if bodyFile == "":
                return ""

            if os.path.isfile(bodyAny):
                return bodyFileAsDict(bodyFile)
            else:
                return {}

        elif bodyFunc != None:
            icm.TM_here("bodyFunc={}".format(pp.pformat(bodyFunc)))

            if bodyFunc == "":
                return ""

            if bodyFunc == "NOTYET-valid func":
                return bodyFuncAsDict(bodyFunc)
            else:
                return {}

        elif bodyStr != None:
            icm.TM_here("bodyStr={}".format(pp.pformat(bodyStr)))

            if bodyStr == "":
                return ""

            bodyValue = bodyStrAsDict(bodyStr)
            return bodyValue

        else:
            # So they were all None, meaning that no form of "body" was specified.
            return None

    # icm.TM_here("Args: {}".format(args))
    # for key in kwargs:
    #      icm.TM_here("another keyword arg: %s: %s" % (key, kwargs[key]))

    bodyAny = kwargs.pop('body', None)
    bodyFile = kwargs.pop('bodyFile', None)
    bodyStr = kwargs.pop('bodyStr', None)
    bodyFunc = kwargs.pop('bodyFunc', None)

    bodyValue = bodyArgToDict(bodyAny, bodyFile, bodyStr, bodyFunc)

    icm.TM_here(pp.pformat(requestOptions))

    if bodyValue == None:
        request = construct_request(op, requestOptions, **kwargs)
    elif bodyValue == "":
        # Causes An Exception That Describes Expected Dictionary
        request = construct_request(op, requestOptions, body=None, **kwargs)
    else:
        request = construct_request(op,
                                    requestOptions,
                                    body=bodyValue,
                                    **kwargs)

    icm.LOG_here("request={request}".format(request=pp.pformat(request)))

    c = RequestsClient()

    future = c.request(request)

    try:
        result = future.result()
    except Exception as e:
        #icm.EH_critical_exception(e)
        result = None

    if result:
        icm.LOG_here("responseHeaders: {headers}".format(
            headers=pp.pformat(result._delegate.headers)))

        icm.ANN_write("Operation Status: {result}".format(result=result))

        icm.ANN_write("Operation Result: {result}".format(
            result=pp.pformat(result.json())))