Ejemplo n.º 1
0
def test_performs_validation(empty_swagger_spec, response_spec):
    empty_swagger_spec.config['validate_responses'] = True
    response = Mock(spec=IncomingResponse,
                    status_code=200,
                    json=Mock(return_value='Monday'))

    with patch('bravado_core.response.validate_schema_object') as val_schem:
        with patch('bravado_core.response.get_response_spec') as get_resp:
            get_resp.return_value = response_spec
            op = Mock(swagger_spec=empty_swagger_spec)
            unmarshal_response(response, op)
            assert val_schem.call_count == 1
def test_performs_validation(empty_swagger_spec, response_spec):
    empty_swagger_spec.config['validate_responses'] = True
    response = Mock(
        spec=ResponseLike,
        status_code=200,
        json=Mock(return_value='Monday'))

    with patch('bravado_core.response.validate_schema_object') as val_schem:
        with patch('bravado_core.response.get_response_spec') as get_resp:
            get_resp.return_value = response_spec
            op = Mock(swagger_spec=empty_swagger_spec)
            unmarshal_response(response, op)
            assert val_schem.call_count == 1
Ejemplo n.º 3
0
def test_skips_validation(empty_swagger_spec, response_spec):
    empty_swagger_spec.config['validate_responses'] = False
    response = Mock(spec=IncomingResponse,
                    status_code=200,
                    headers={'content-type': APP_JSON},
                    json=Mock(return_value='Monday'))

    with patch('bravado_core.response.validate_schema_object') as val_schem:
        with patch('bravado_core.response.get_response_spec') as get_resp:
            get_resp.return_value = response_spec
            op = Mock(swagger_spec=empty_swagger_spec)
            unmarshal_response(response, op)
            assert val_schem.call_count == 0
def test_skips_validation(empty_swagger_spec, response_spec):
    empty_swagger_spec.config['validate_responses'] = False
    response = Mock(
        spec=IncomingResponse,
        status_code=200,
        headers={'content-type': APP_JSON},
        json=Mock(return_value='Monday'))

    with patch('bravado_core.response.validate_schema_object') as val_schem:
        with patch('bravado_core.response.get_response_spec') as get_resp:
            get_resp.return_value = response_spec
            op = Mock(swagger_spec=empty_swagger_spec)
            unmarshal_response(response, op)
            assert val_schem.call_count == 0
Ejemplo n.º 5
0
def test_ensure_polymorphic_objects_are_correctly_build_in_case_of_fully_dereferenced_specs(
    polymorphic_dict, validate_responses, use_models, internally_dereference_refs,
):
    raw_response = [{'name': 'name', 'type': 'Dog', 'birth_date': '2017-11-02'}]

    spec = Spec.from_dict(
        spec_dict=polymorphic_dict,
        config={
            'validate_responses': validate_responses,
            'use_models': use_models,
            'internally_dereference_refs': internally_dereference_refs,
        },
        origin_url='',
    )

    response = Mock(
        spec=IncomingResponse,
        status_code=200,
        headers={'content-type': APP_JSON},
        json=Mock(return_value=raw_response),
    )

    unmarshaled_response = unmarshal_response(response, spec.resources['pets'].get_pets)
    if use_models:
        assert repr(unmarshaled_response) == "[Dog(birth_date=datetime.date(2017, 11, 2), name='name', type='Dog')]"
    else:
        assert unmarshaled_response == raw_response
Ejemplo n.º 6
0
def response_callback(incoming_response, operation):
    """
    So the http_client is finished with its part of processing the response.
    This hands the response over to bravado_core for validation and
    unmarshalling.

    :type incoming_response: :class:`bravado_core.response.IncomingResponse`
    :type operation: :class:`bravado_core.operation.Operation`
    :return: Response spec's return value.
    :raises: HTTPError
        - On 5XX status code, the HTTPError has minimal information.
        - On non-2XX status code with no matching response, the HTTPError
            contains a detailed error message.
        - On non-2XX status code with a matching response, the HTTPError
            contains the return value.
    """
    raise_on_unexpected(incoming_response)

    try:
        swagger_return_value = unmarshal_response(incoming_response, operation)
    except MatchingResponseNotFound as e:
        six.reraise(HTTPError,
                    HTTPError(response=incoming_response, message=str(e)),
                    sys.exc_info()[2])

    raise_on_expected(incoming_response, swagger_return_value)
    return swagger_return_value
Ejemplo n.º 7
0
def response_callback(incoming_response, operation):
    """
    So the http_client is finished with its part of processing the response.
    This hands the response over to bravado_core for validation and
    unmarshalling. On success, the swagger_result is available as
    `incoming_response.swagger_result`.

    :type incoming_response: :class:`bravado_core.response.IncomingResponse`
    :type operation: :class:`bravado_core.operation.Operation`
    :raises: HTTPError
        - On 5XX status code, the HTTPError has minimal information.
        - On non-2XX status code with no matching response, the HTTPError
            contains a detailed error message.
        - On non-2XX status code with a matching response, the HTTPError
            contains the return value.
    """
    raise_on_unexpected(incoming_response)

    try:
        incoming_response.swagger_result = unmarshal_response(
            incoming_response,
            operation)
    except MatchingResponseNotFound as e:
        six.reraise(
            HTTPError,
            HTTPError(response=incoming_response, message=str(e)),
            sys.exc_info()[2])

    raise_on_expected(incoming_response)
Ejemplo n.º 8
0
def test_ensure_polymorphic_objects_are_correctly_build_in_case_of_fully_dereferenced_specs(
    polymorphic_dict, validate_responses, use_models, internally_dereference_refs,
):
    raw_response = [{'name': 'name', 'type': 'Dog', 'birth_date': '2017-11-02'}]

    spec = Spec.from_dict(
        spec_dict=polymorphic_dict,
        config={
            'validate_responses': validate_responses,
            'use_models': use_models,
            'internally_dereference_refs': internally_dereference_refs,
        },
        origin_url='',
    )

    response = Mock(
        spec=IncomingResponse,
        status_code=200,
        headers={'content-type': APP_JSON},
        json=Mock(return_value=raw_response),
    )

    unmarshaled_response = unmarshal_response(response, spec.resources['pets'].get_pets)
    if use_models:
        assert repr(unmarshaled_response) == "[Dog(birth_date=datetime.date(2017, 11, 2), name='name', type='Dog')]"
    else:
        assert unmarshaled_response == raw_response
def test_unmarshal_model_polymorphic_specs(polymorphic_spec):
    pet_list_dicts = [
        {
            'name': 'a dog name',
            'type': 'Dog',
            'birth_date': '2017-03-09',
        },
        {
            'name': 'a cat name',
            'type': 'Cat',
            'color': 'white',
        },
    ]
    pet_list_models = unmarshal_response(
        response=Mock(
            spec=IncomingResponse,
            status_code=200,
            headers={'content-type': APP_JSON},
            json=Mock(return_value=pet_list_dicts),
        ),
        op=polymorphic_spec.resources['pets'].operations['get_pets'],
    )

    assert len(pet_list_dicts) == len(pet_list_models)

    for list_item_model, list_item_dict in zip(pet_list_models,
                                               pet_list_dicts):
        assert isinstance(list_item_model,
                          polymorphic_spec.definitions['GenericPet'])
        assert isinstance(list_item_model,
                          polymorphic_spec.definitions[list_item_dict['type']])
        assert list_item_model._marshal() == list_item_dict
Ejemplo n.º 10
0
def test_json_content(empty_swagger_spec, response_spec):
    response = Mock(spec=IncomingResponse,
                    status_code=200,
                    json=Mock(return_value='Monday'))

    with patch('bravado_core.response.get_response_spec') as m:
        m.return_value = response_spec
        op = Mock(swagger_spec=empty_swagger_spec)
        assert 'Monday' == unmarshal_response(response, op)
Ejemplo n.º 11
0
def test_text_content(empty_swagger_spec, response_spec):
    response = Mock(spec=IncomingResponse,
                    status_code=200,
                    headers={'content-type': 'text/plain'},
                    text='Monday')

    with patch('bravado_core.response.get_response_spec') as m:
        m.return_value = response_spec
        op = Mock(swagger_spec=empty_swagger_spec)
        assert 'Monday' == unmarshal_response(response, op)
Ejemplo n.º 12
0
def test_json_content(empty_swagger_spec, response_spec):
    response = Mock(
        spec=ResponseLike,
        status_code=200,
        json=Mock(return_value='Monday'))

    with patch('bravado_core.response.get_response_spec') as m:
        m.return_value = response_spec
        op = Mock(swagger_spec=empty_swagger_spec)
        assert 'Monday' == unmarshal_response(response, op)
def test_no_content(empty_swagger_spec):
    response_spec = {
        'description': "I don't have a 'schema' key so I return nothing",
    }
    response = Mock(spec=IncomingResponse, status_code=200)

    with patch('bravado_core.response.get_response_spec') as m:
        m.return_value = response_spec
        op = Mock(swagger_spec=empty_swagger_spec)
        result = unmarshal_response(response, op)
        assert result is None
def test_unmarshal_model_polymorphic_specs_with_invalid_discriminator(
        polymorphic_spec):
    pet_list_dicts = [
        {
            'name': 'a dog name',
            'type': 'a-random-value',
            'birth_date': '2017-03-09',
        },
    ]
    with pytest.raises(ValidationError):
        # Expecting validation error as "a-random-value" is not a valid type
        unmarshal_response(
            response=Mock(
                spec=IncomingResponse,
                status_code=200,
                headers={'content-type': APP_JSON},
                json=Mock(return_value=pet_list_dicts),
            ),
            op=polymorphic_spec.resources['pets'].operations['get_pets'],
        )
def test_text_content(empty_swagger_spec, response_spec):
    response = Mock(
        spec=IncomingResponse,
        status_code=200,
        headers={'content-type': 'text/plain'},
        text='Monday')

    with patch('bravado_core.response.get_response_spec') as m:
        m.return_value = response_spec
        op = Mock(swagger_spec=empty_swagger_spec)
        assert 'Monday' == unmarshal_response(response, op)
def test_no_content(empty_swagger_spec):
    response_spec = {
        'description': "I don't have a 'schema' key so I return nothing",
    }
    response = Mock(spec=IncomingResponse, status_code=200)

    with patch('bravado_core.response.get_response_spec') as m:
        m.return_value = response_spec
        op = Mock(swagger_spec=empty_swagger_spec)
        result = unmarshal_response(response, op)
        assert result is None
Ejemplo n.º 17
0
def test_msgpack_content(empty_swagger_spec, response_spec):
    message = 'Monday'
    response = Mock(spec=IncomingResponse,
                    status_code=200,
                    headers={'content-type': APP_MSGPACK},
                    raw_bytes=msgpack.dumps(message, use_bin_type=True))

    with patch(
            'bravado_core.response.get_response_spec',
            return_value=response_spec,
    ):
        op = Mock(swagger_spec=empty_swagger_spec)
        assert message == unmarshal_response(response, op)
Ejemplo n.º 18
0
 def _unmarshal(self, response):
     # Now transform the request's Response object into an instance of a
     # swagger model
     try:
         result = unmarshal_response(response, self.operation)
     except jsonschema.exceptions.ValidationError as e:
         log.warn("Failed to unmarshal response: %s" % e)
         k = ValidationError("Failed to unmarshal response because: %s" % str(e))
         c = self.error_callback
         if hasattr(c, '__func__'):
             c = c.__func__
         return c(k)
     return result
def test_msgpack_content(empty_swagger_spec, response_spec):
    message = 'Monday'
    response = Mock(
        spec=IncomingResponse,
        status_code=200,
        headers={'content-type': APP_MSGPACK},
        raw_bytes=msgpack.dumps(message, use_bin_type=True))

    with patch(
        'bravado_core.response.get_response_spec',
        return_value=response_spec,
    ):
        op = Mock(swagger_spec=empty_swagger_spec)
        assert message == unmarshal_response(response, op)
Ejemplo n.º 20
0
def test_ensure_polymorphic_objects_are_correctly_build_in_case_of_fully_dereferenced_specs(
    polymorphic_dict,
    validate_responses,
    use_models,
    internally_dereference_refs,
):
    raw_response = {
        'number_of_pets': 1,
        'list': [{
            'name': 'name',
            'type': 'Dog',
            'birth_date': '2017-11-02'
        }],
    }
    spec = Spec.from_dict(
        spec_dict=polymorphic_dict,
        config={
            'validate_responses': validate_responses,
            'use_models': use_models,
            'internally_dereference_refs': internally_dereference_refs,
        },
        origin_url='',
    )

    response = Mock(
        spec=IncomingResponse,
        status_code=200,
        headers={'content-type': APP_JSON},
        json=Mock(return_value=raw_response),
    )
    unmarshaled_response = unmarshal_response(response,
                                              spec.resources['pets'].get_pets)

    pet_list_model_type = spec.definitions['PetList'] if use_models else dict
    dog_model_type = spec.definitions['Dog'] if use_models else dict
    expected_response = pet_list_model_type(
        number_of_pets=1,
        list=[
            dog_model_type(birth_date=datetime.date(2017, 11, 2),
                           name='name',
                           type='Dog'),
        ],
    )
    assert expected_response == unmarshaled_response
def test_unmarshal_model_polymorphic_specs_with_xnullable_field(
        polymorphic_dict):
    # Test case to ensure no further regressions on issue #359
    polymorphic_dict['definitions']['GenericPet']['x-nullable'] = True
    polymorphic_spec = Spec.from_dict(polymorphic_dict)
    PetList = polymorphic_spec.definitions['PetList']

    response = unmarshal_response(
        response=Mock(
            spec=IncomingResponse,
            status_code=200,
            headers={'content-type': APP_JSON},
            json=Mock(return_value={
                'number_of_pets': 1,
                'list': [None],
            }, ),
        ),
        op=polymorphic_spec.resources['pets'].operations['get_pets'],
    )

    assert response == PetList(number_of_pets=1, list=[None])
Ejemplo n.º 22
0
 def response_callback(response_adapter):
     return unmarshal_response(response_adapter, self)