def test_missing_object_spec_defaulting_on(petstore_dict): """When default_type_to_object config option is set to True, then missing types default to object """ petstore_spec = Spec.from_dict(petstore_dict, config={'use_models': False, 'default_type_to_object': True}) category_spec = copy.deepcopy( petstore_spec.spec_dict['definitions']['Category'] ) # now a missing type will default to object type category_spec['properties']['id'].pop('type') result = unmarshal_schema_object( petstore_spec, category_spec, {'id': {'foo': 'bar'}, 'name': 'short-hair'}) assert result == {'id': {'foo': 'bar'}, 'name': 'short-hair'} # so a different type will fail with pytest.raises(SwaggerMappingError): result = unmarshal_schema_object( petstore_spec, category_spec, {'id': 'blahblah', 'name': 'short-hair'})
def test_missing_object_spec_defaulting_on(petstore_dict): """When default_type_to_object config option is set to True, then missing types default to object """ category_spec = petstore_dict['definitions']['Category'] # now a missing type will default to object type category_spec['properties']['id'].pop('type') petstore_spec = Spec.from_dict(petstore_dict, config={'use_models': False, 'default_type_to_object': True}) result = unmarshal_schema_object( petstore_spec, category_spec, {'id': {'foo': 'bar'}, 'name': 'short-hair'}, ) assert result == {'id': {'foo': 'bar'}, 'name': 'short-hair'} # so a different type will fail with pytest.raises(SwaggerMappingError): unmarshal_schema_object( petstore_spec, category_spec, {'id': 'blahblah', 'name': 'short-hair'}, )
def test_unmarshal_with_primitive_fail(empty_swagger_spec): """Test scenarios in which validation should fail: (2)""" content_spec = { 'type': 'string', 'x-nullable': False, } value = None with pytest.raises(ValidationError) as excinfo: validate_schema_object(empty_swagger_spec, content_spec, value) unmarshal_schema_object(empty_swagger_spec, content_spec, value) assert excinfo.value.message == "None is not of type 'string'"
def test_unmarshal_with_object_req_no_value(empty_swagger_spec, nullable): """When the value is required but not set at all, validation should fail: (4), (10) """ content_spec = content_spec_factory(True, nullable) value = {} with pytest.raises(ValidationError) as excinfo: validate_schema_object(empty_swagger_spec, content_spec, value) unmarshal_schema_object(empty_swagger_spec, content_spec, value) assert excinfo.value.message == "'x' is a required property"
def test_unmarshal_with_object_no_null_value_none(empty_swagger_spec, required): """When nullable is `False` and the value is set to `None`, validation should fail: (3), (6) """ content_spec = content_spec_factory(required, False) value = {'x': None} with pytest.raises(ValidationError) as excinfo: validate_schema_object(empty_swagger_spec, content_spec, value) unmarshal_schema_object(empty_swagger_spec, content_spec, value) assert excinfo.value.message == "None is not of type 'string'"
def test_bad_object_spec(petstore_dict): petstore_spec = Spec.from_dict(petstore_dict, config={'use_models': False}) category_spec = copy.deepcopy( petstore_spec.spec_dict['definitions']['Category']) # Type is a required field for objects. category_spec['properties']['id'].pop('type') with pytest.raises(SwaggerMappingError): unmarshal_schema_object(petstore_spec, category_spec, { 'id': 200, 'name': 'short-hair' })
def test_invalid_type(petstore_dict): petstore_spec = Spec.from_dict(petstore_dict, config={'use_models': False}) category_spec = copy.deepcopy( petstore_spec.spec_dict['definitions']['Category']) category_spec['properties']['id']['type'] = 'notAValidType' with pytest.raises(SwaggerMappingError): unmarshal_schema_object(petstore_spec, category_spec, { 'id': 200, 'name': 'short-hair' })
def test_invalid_type(petstore_dict): petstore_spec = Spec.from_dict(petstore_dict, config={'use_models': False}) category_spec = copy.deepcopy( petstore_spec.spec_dict['definitions']['Category'] ) category_spec['properties']['id']['type'] = 'notAValidType' with pytest.raises(SwaggerMappingError): unmarshal_schema_object( petstore_spec, category_spec, {'id': 200, 'name': 'short-hair'})
def test_bad_object_spec(petstore_dict): petstore_spec = Spec.from_dict(petstore_dict, config={'use_models': False}) category_spec = copy.deepcopy( petstore_spec.spec_dict['definitions']['Category'] ) # Type is a required field for objects. category_spec['properties']['id'].pop('type') with pytest.raises(SwaggerMappingError): unmarshal_schema_object( petstore_spec, category_spec, {'id': 200, 'name': 'short-hair'})
def unmarshal_param(param, request): """Unmarshal the given parameter from the passed in request like object. :type param: :class:`bravado_core.param.Param` :type request: :class:`bravado_core.request.IncomingRequest` :return: value of parameter """ swagger_spec = param.swagger_spec deref = swagger_spec.deref param_spec = deref(get_param_type_spec(param)) location = param.location param_type = deref(param_spec.get('type')) cast_param = partial(cast_request_param, param_type, param.name) default_value = schema.get_default(swagger_spec, param_spec) if location == 'path': raw_value = cast_param(request.path.get(param.name, None)) elif location == 'query': raw_value = cast_param(request.query.get(param.name, default_value)) elif location == 'header': raw_value = cast_param(request.headers.get(param.name, default_value)) elif location == 'formData': if param_type == 'file': raw_value = request.files.get(param.name, None) else: raw_value = cast_param(request.form.get(param.name, default_value)) elif location == 'body': try: # TODO: verify content-type header raw_value = request.json() except ValueError as json_error: # If the body parameter is required then we should make sure that an exception # is thrown, instead if the body parameter is optional is OK-ish to assume that # raw_value is the default_value if param.required: raise SwaggerMappingError( "Error reading request body JSON: {0}".format(str(json_error)), ) else: raw_value = default_value else: raise SwaggerMappingError( "Don't know how to unmarshal_param with location {0}".format(location), ) if raw_value is None and not param.required: return None if param_type == 'array' and location != 'body': raw_value = unmarshal_collection_format( swagger_spec, param_spec, raw_value, ) if swagger_spec.config['validate_requests']: validate_schema_object(swagger_spec, param_spec, raw_value) value = unmarshal_schema_object(swagger_spec, param_spec, raw_value) return value
def unmarshal_response(response, op): """Unmarshal incoming http response into a value based on the response specification. :type response: :class:`bravado_core.response.IncomingResponse` :type op: :class:`bravado_core.operation.Operation` :returns: value where type(value) matches response_spec['schema']['type'] if it exists, None otherwise. """ deref = op.swagger_spec.deref response_spec = get_response_spec(response.status_code, op) if 'schema' not in response_spec: # If response spec does not define schema return None content_type = response.headers.get('content-type', '').lower() if content_type.startswith(APP_JSON) or content_type.startswith( APP_MSGPACK): content_spec = deref(response_spec['schema']) if content_type.startswith(APP_JSON): content_value = response.json() else: content_value = msgpack.loads(response.raw_bytes, raw=False) if op.swagger_spec.config['validate_responses']: validate_schema_object(op.swagger_spec, content_spec, content_value) return unmarshal_schema_object(op.swagger_spec, content_spec, content_value) # TODO: Non-json response contents return response.text
def unmarshal_response(response, op): """Unmarshal incoming http response into a value based on the response specification. :type response: :class:`bravado_core.response.IncomingResponse` :type op: :class:`bravado_core.operation.Operation` :returns: value where type(value) matches response_spec['schema']['type'] if it exists, None otherwise. """ response_spec = get_response_spec(response.status_code, op) def has_content(response_spec): return 'schema' in response_spec if not has_content(response_spec): return None # TODO: Non-json response contents content_spec = response_spec['schema'] content_value = response.json() if op.swagger_spec.config['validate_responses']: validate_schema_object(op.swagger_spec, content_spec, content_value) return unmarshal_schema_object(op.swagger_spec, content_spec, content_value)
def unmarshal_response(response, op): """Unmarshal incoming http response into a value based on the response specification. :type response: :class:`bravado_core.response.IncomingResponse` :type op: :class:`bravado_core.operation.Operation` :returns: value where type(value) matches response_spec['schema']['type'] if it exists, None otherwise. """ deref = op.swagger_spec.deref response_spec = get_response_spec(response.status_code, op) def has_content(response_spec): return "schema" in response_spec if not has_content(response_spec): return None # TODO: Non-json response contents content_spec = deref(response_spec["schema"]) content_value = response.json() if op.swagger_spec.config["validate_responses"]: validate_schema_object(op.swagger_spec, content_spec, content_value) return unmarshal_schema_object(op.swagger_spec, content_spec, content_value)
def test_use_models_false(petstore_dict): petstore_spec = Spec.from_dict(petstore_dict, config={"use_models": False}) category_spec = petstore_spec.spec_dict["definitions"]["Category"] result = unmarshal_schema_object(petstore_spec, category_spec, {"id": 200, "name": "short-hair"}) assert isinstance(result, dict)
def unmarshal_response_inner(response, op): """ Unmarshal incoming http response into a value based on the response specification. :type response: :class:`bravado_core.response.IncomingResponse` :type op: :class:`bravado_core.operation.Operation` :returns: value where type(value) matches response_spec['schema']['type'] if it exists, None otherwise. """ deref = op.swagger_spec.deref response_spec = get_response_spec(status_code=response.status_code, op=op) if 'schema' not in response_spec: return None content_type = response.headers.get('content-type', '').lower() if content_type.startswith(APP_JSON) or content_type.startswith(APP_MSGPACK): content_spec = deref(response_spec['schema']) if content_type.startswith(APP_JSON): content_value = response.json() else: content_value = unpackb(response.raw_bytes, encoding='utf-8') if op.swagger_spec.config.get('validate_responses', False): validate_schema_object(op.swagger_spec, content_spec, content_value) return unmarshal_schema_object( swagger_spec=op.swagger_spec, schema_object_spec=content_spec, value=content_value, ) # TODO: Non-json response contents return response.text
def test_unmarshal_with_object_default(empty_swagger_spec, nullable, required): """With a value set, validation should always pass: (2), (5), (8), (11)""" content_spec = content_spec_factory(required, nullable) value = {'x': 'y'} validate_schema_object(empty_swagger_spec, content_spec, value) result = unmarshal_schema_object(empty_swagger_spec, content_spec, value) assert result == value
def _unmarshal(cls, val): """Unmarshal a dict into an instance of the model. :type val: dict :rtype: .Model """ from bravado_core.unmarshal import unmarshal_schema_object return unmarshal_schema_object(cls._swagger_spec, cls._model_spec, val)
def test_unmarshal_with_primitive_pass(empty_swagger_spec, value, nullable): """Test scenarios in which validation should pass: (1), (3), (4)""" content_spec = { 'type': 'string', 'x-nullable': nullable, } validate_schema_object(empty_swagger_spec, content_spec, value) result = unmarshal_schema_object(empty_swagger_spec, content_spec, value) assert result == value
def test_use_models_false(petstore_dict): petstore_spec = Spec.from_dict(petstore_dict, config={'use_models': False}) category_spec = petstore_spec.spec_dict['definitions']['Category'] result = unmarshal_schema_object(petstore_spec, category_spec, { 'id': 200, 'name': 'short-hair' }) assert isinstance(result, dict)
def test_use_models_false(petstore_dict): petstore_spec = Spec.from_dict(petstore_dict, config={'use_models': False}) category_spec = petstore_spec.spec_dict['definitions']['Category'] result = unmarshal_schema_object( petstore_spec, category_spec, {'id': 200, 'name': 'short-hair'}) assert isinstance(result, dict)
def test_unmarshal_with_object_no_req_no_value(empty_swagger_spec, nullable): """When the value is not required and not set at all, validation should pass: (1), (7) """ content_spec = content_spec_factory(False, nullable=nullable) value = {} validate_schema_object(empty_swagger_spec, content_spec, value) result = unmarshal_schema_object(empty_swagger_spec, content_spec, value) assert result == {'x': None} # Missing parameters are re-introduced
def test_unmarshal_with_object_null_value_none(empty_swagger_spec, required): """When nullable is `True` and the value is set to `None`, validation should pass: (9), (12) """ content_spec = content_spec_factory(required, True) value = {'x': None} validate_schema_object(empty_swagger_spec, content_spec, value) result = unmarshal_schema_object(empty_swagger_spec, content_spec, value) assert result == {'x': None}
def unmarshal_response_inner( response, # type: IncomingResponse op, # type: Operation ): # type: (...) -> typing.Optional[T] """ Unmarshal incoming http response into a value based on the response specification. :type response: :class:`bravado_core.response.IncomingResponse` :type op: :class:`bravado_core.operation.Operation` :returns: value where type(value) matches response_spec['schema']['type'] if it exists, None otherwise. """ content_type = response.headers.get('content-type', '').lower() if content_type.startswith(APP_JSON) or content_type.startswith(APP_MSGPACK): use_models = op.swagger_spec.config.get('use_models', True) if content_type.startswith(APP_JSON): content_value = response.json() else: content_value = unpackb(response.raw_bytes) try: response_spec = get_response_spec( status_code=response.status_code, op=op) except MatchingResponseNotFound: if not use_models: return content_value six.reraise(*sys.exc_info()) if 'schema' not in response_spec: if not use_models: return content_value return None content_spec = op.swagger_spec.deref(response_spec['schema']) if op.swagger_spec.config.get('validate_responses', False): validate_schema_object(op.swagger_spec, content_spec, content_value) return unmarshal_schema_object( swagger_spec=op.swagger_spec, schema_object_spec=content_spec, value=content_value, ) if content_type.startswith('application'): return response.raw_bytes # TODO: Non-json response contents return response.text
def unmarshal_param(param, request): """Unmarshal the given parameter from the passed in request like object. :type param: :class:`bravado_core.param.Param` :type request: :class:`bravado_core.request.IncomingRequest` :return: value of parameter """ swagger_spec = param.swagger_spec deref = swagger_spec.deref param_spec = deref(get_param_type_spec(param)) location = param.location param_type = deref(param_spec.get('type')) cast_param = partial(cast_request_param, param_type, param.name) default_value = schema.get_default(swagger_spec, param_spec) if location == 'path': raw_value = cast_param(request.path.get(param.name, None)) elif location == 'query': raw_value = cast_param(request.query.get(param.name, default_value)) elif location == 'header': raw_value = cast_param(request.headers.get(param.name, default_value)) elif location == 'formData': if param_type == 'file': raw_value = request.files.get(param.name, None) else: raw_value = cast_param(request.form.get(param.name, default_value)) elif location == 'body': # TODO: verify content-type header try: raw_value = request.json() except ValueError as json_error: raise SwaggerMappingError("Error reading request body JSON: {0}". format(str(json_error))) else: raise SwaggerMappingError( "Don't know how to unmarshal_param with location {0}". format(location)) if raw_value is None and not schema.is_required(swagger_spec, param_spec): return None if param_type == 'array' and location != 'body': raw_value = unmarshal_collection_format(swagger_spec, param_spec, raw_value) if swagger_spec.config['validate_requests']: validate_schema_object(swagger_spec, param_spec, raw_value) value = unmarshal_schema_object(swagger_spec, param_spec, raw_value) return value
async def unmarshal_param(param, request): """Unmarshal the given parameter from the passed in request like object. :type param: :class:`bravado_core.param.Param` :type request: :class:`bravado_core.request.IncomingRequest` :return: value of parameter """ swagger_spec = param.swagger_spec deref = swagger_spec.deref param_spec = deref(get_param_type_spec(param)) location = param.location param_type = deref(param_spec.get('type')) cast_param = partial(cast_request_param, param_type, param.name) default_value = schema.get_default(swagger_spec, param_spec) if location == Location.path: raw_value = cast_param(request.match_info.get(param.name, None)) elif location == Location.query: raw_value = cast_param(request.query.get(param.name, default_value)) elif location == Location.header: raw_value = cast_param(request.headers.get(param.name, default_value)) elif location == Location.form_data: if param_type == 'file': raw_value = request.files.get(param.name, None) else: raw_value = cast_param(request.form.get(param.name, default_value)) elif location == Location.body: # TODO: verify content-type header try: raw_value = request.json() except ValueError as json_error: raise SwaggerMappingError( "Error reading request body JSON: {0}".format(str(json_error))) else: raise SwaggerMappingError( "Don't know how to unmarshal_param with location {0}".format( location)) if raw_value is None and not schema.is_required(swagger_spec, param_spec): return None if param_type == 'array' and location != Location.body: raw_value = unmarshal_collection_format(swagger_spec, param_spec, raw_value) if swagger_spec.config['validate_requests']: validate_schema_object(swagger_spec, param_spec, raw_value) value = unmarshal_schema_object(swagger_spec, param_spec, raw_value) return value
def test_missing_object_spec(petstore_dict): petstore_spec = Spec.from_dict(petstore_dict, config={'use_models': False}) category_spec = copy.deepcopy( petstore_spec.spec_dict['definitions']['Category'] ) # without a type, do no validation category_spec['properties']['id'].pop('type') # so id can be a string... result = unmarshal_schema_object( petstore_spec, category_spec, {'id': 'blahblah', 'name': 'short-hair'}) assert result == {'id': 'blahblah', 'name': 'short-hair'} # ...or anything else result = unmarshal_schema_object( petstore_spec, category_spec, {'id': {'foo': 'bar'}, 'name': 'short-hair'}) assert result == {'id': {'foo': 'bar'}, 'name': 'short-hair'}
def test_missing_object_spec(petstore_dict): # without a type, do no validation category_spec = petstore_dict['definitions']['Category'] category_spec['properties']['id'] = {} petstore_spec = Spec.from_dict(petstore_dict, config={'use_models': False}) # so id can be a string... result = unmarshal_schema_object( petstore_spec, category_spec, {'id': 'blahblah', 'name': 'short-hair'}, ) assert result == {'id': 'blahblah', 'name': 'short-hair'} # ...or anything else result = unmarshal_schema_object( petstore_spec, category_spec, {'id': {'foo': 'bar'}, 'name': 'short-hair'}, ) assert result == {'id': {'foo': 'bar'}, 'name': 'short-hair'}
def test_missing_object_spec_defaulting_off(petstore_dict, value): """When default_type_to_object config option is set to True, then missing types default to object """ category_spec = petstore_dict['definitions']['Category'] category_spec['properties']['id'].pop('type') petstore_spec = Spec.from_dict(petstore_dict, config={'use_models': False, 'default_type_to_object': False}) # In case of missing type the unmarshaling is equivalent no a no-op assert value == unmarshal_schema_object( petstore_spec, category_spec, value, )
def test_unmarshal_schema_object_allOf(composition_dict, composition_abspath): composition_spec = Spec.from_dict(composition_dict, origin_url=get_url(composition_abspath)) pongClone_spec = composition_spec.spec_dict['definitions']['pongClone'] pongClone = composition_spec.definitions['pongClone'] result = unmarshal_schema_object( composition_spec, pongClone_spec, { 'additionalFeature': 'Badges', 'gameSystem': 'NES', 'pang': 'value', 'releaseDate': 'October', }, ) assert isinstance(result, pongClone)
def unmarshal_param(param, request): """Unmarshal the given parameter from the passed in request like object. :type param: :class:`bravado_core.param.Param` :type request: :class:`bravado_core.request.IncomingRequest` :return: value of parameter """ swagger_spec = param.swagger_spec deref = swagger_spec.deref param_spec = deref(get_param_type_spec(param)) location = param.location param_type = deref(param_spec.get('type')) cast_param = partial(cast_request_param, param_type, param.name) default_value = schema.get_default(swagger_spec, param_spec) if location == 'path': raw_value = cast_param(request.path.get(param.name, None)) elif location == 'query': raw_value = cast_param(request.query.get(param.name, default_value)) elif location == 'header': raw_value = cast_param(request.headers.get(param.name, default_value)) elif location == 'formData': if param_type == 'file': raw_value = request.files.get(param.name, None) else: raw_value = cast_param(request.form.get(param.name, default_value)) elif location == 'body': # TODO: verify content-type header raw_value = request.json() else: raise SwaggerMappingError( "Don't know how to unmarshal_param with location {0}".format( location)) if param_type == 'array' and location != 'body': raw_value = unmarshal_collection_format(swagger_spec, param_spec, raw_value) if swagger_spec.config['validate_requests']: validate_schema_object(swagger_spec, param_spec, raw_value) value = unmarshal_schema_object(swagger_spec, param_spec, raw_value) return value
def unmarshal_response_inner( response, # type: IncomingResponse op, # type: Operation ): # type: (...) -> typing.Optional[T] """ Unmarshal incoming http response into a value based on the response specification. :type response: :class:`bravado_core.response.IncomingResponse` :type op: :class:`bravado_core.operation.Operation` :returns: value where type(value) matches response_spec['schema']['type'] if it exists, None otherwise. """ deref = op.swagger_spec.deref response_spec = get_response_spec(status_code=response.status_code, op=op) if 'schema' not in response_spec: return None content_type = response.headers.get('content-type', '').lower() if content_type.startswith(APP_JSON) or content_type.startswith( APP_MSGPACK): content_spec = deref(response_spec['schema']) if content_type.startswith(APP_JSON): content_value = response.json() else: content_value = unpackb(response.raw_bytes, encoding='utf-8') if op.swagger_spec.config.get('validate_responses', False): validate_schema_object(op.swagger_spec, content_spec, content_value) return unmarshal_schema_object( swagger_spec=op.swagger_spec, schema_object_spec=content_spec, value=content_value, ) # TODO: Non-json response contents return response.text
def unmarshal_param(param, request): """Unmarshal the given parameter from the passed in request like object. :type param: :class:`bravado_core.param.Param` :type request: :class:`bravado_core.request.IncomingRequest` """ param_spec = get_param_type_spec(param) location = param.location cast_param = partial(cast_request_param, param_spec['type'], param.name) default_value = schema.get_default(param_spec) if location == 'path': raw_value = cast_param(request.path.get(param.name, None)) elif location == 'query': raw_value = cast_param(request.query.get(param.name, default_value)) elif location == 'header': raw_value = cast_param(request.headers.get(param.name, default_value)) elif location == 'formData': if param_spec['type'] == 'file': raw_value = request.files.get(param.name, None) else: raw_value = cast_param(request.form.get(param.name, default_value)) elif location == 'body': # TODO: verify content-type header raw_value = request.json() else: raise SwaggerMappingError( "Don't know how to unmarshal_param with location {0}". format(location)) if param_spec['type'] == 'array' and location != 'body': raw_value = unmarshal_collection_format(param_spec, raw_value) if param.swagger_spec.config['validate_requests']: validate_schema_object(param.swagger_spec, param_spec, raw_value) value = unmarshal_schema_object(param.swagger_spec, param_spec, raw_value) return value
def benchmark(self): persons_obj = unmarshal_schema_object(self.spec, self.persons, self.data) print(persons_obj)
def unmarshal(self): obj = unmarshal_schema_object(self.spec, self.obj, self.data)
def benchmark(self): school_obj = unmarshal_schema_object(self.spec, self.school, self.data)
def benchmark(self): unmarshal_schema_object(self.spec, self.animal, self.data)