Beispiel #1
0
    def test_get_pets_empty_value(self, spec):
        host_url = 'http://petstore.swagger.io/v1'
        path_pattern = '/v1/pets'
        query_params = {
            'limit': '',
        }

        request = MockRequest(
            host_url,
            'GET',
            '/pets',
            path_pattern=path_pattern,
            args=query_params,
        )

        with pytest.raises(EmptyParameterValue):
            validate_parameters(spec, request)
        body = validate_body(spec, request)

        assert body is None
    def test_get_pets_wrong_parameter_type(self, spec):
        host_url = 'http://petstore.swagger.io/v1'
        path_pattern = '/v1/pets'
        query_params = {
            'limit': 'twenty',
        }

        request = MockRequest(
            host_url,
            'GET',
            '/pets',
            path_pattern=path_pattern,
            args=query_params,
        )

        with pytest.raises(CastError):
            validate_parameters(spec, request)

        body = validate_body(spec, request)

        assert body is None
Beispiel #3
0
    def test_request_factory(self, mock_validate):
        spec = mock.sentinel.spec
        request = mock.sentinel.request
        parameters = mock.sentinel.parameters
        mock_validate.return_value = ResultMock(parameters=parameters)
        request_factory = FactoryClassMock

        result = validate_parameters(spec, request, request_factory)

        assert result == parameters
        mock_validate.assert_called_once_with(
            FactoryClassMock(request),
        )
    def test_get_pets_parameter_deserialization_error(self, spec):
        host_url = 'http://petstore.swagger.io/v1'
        path_pattern = '/v1/pets'
        query_params = {
            'limit': 1,
            'tags': 12,
        }

        request = MockRequest(
            host_url,
            'GET',
            '/pets',
            path_pattern=path_pattern,
            args=query_params,
        )

        with pytest.raises(DeserializeError):
            validate_parameters(spec, request)

        body = validate_body(spec, request)

        assert body is None
Beispiel #5
0
    def test_get_pets_invalid_response(self, spec, response_validator):
        host_url = 'http://petstore.swagger.io/v1'
        path_pattern = '/v1/pets'
        query_params = {
            'limit': '20',
        }

        request = MockRequest(
            host_url, 'GET', '/pets',
            path_pattern=path_pattern, args=query_params,
        )

        parameters = validate_parameters(spec, request)
        body = validate_body(spec, request)

        assert parameters == RequestParameters(
            query={
                'limit': 20,
                'page': 1,
                'search': '',
            }
        )
        assert body is None

        response_data_json = {
            'data': [
                {
                    'id': 1,
                    'name': {
                        'first_name': 'Cat',
                    },
                }
            ],
        }
        response_data = json.dumps(response_data_json)
        response = MockResponse(response_data)

        with pytest.raises(InvalidSchemaValue):
            validate_data(spec, request, response)

        response_result = response_validator.validate(request, response)

        schema_errors = response_result.errors[0].schema_errors
        assert response_result.errors == [
            InvalidSchemaValue(
                type='object',
                value=response_data_json,
                schema_errors=schema_errors,
            ),
        ]
        assert response_result.data is None
    def test_post_tags_created_invalid_type(self, spec, response_validator):
        host_url = 'http://petstore.swagger.io/v1'
        path_pattern = '/v1/tags'
        created = 'long time ago'
        pet_name = 'Dog'
        data_json = {
            'created': created,
            'name': pet_name,
        }
        data = json.dumps(data_json)

        request = MockRequest(
            host_url,
            'POST',
            '/tags',
            path_pattern=path_pattern,
            data=data,
        )

        parameters = validate_parameters(spec, request)
        with pytest.raises(InvalidSchemaValue):
            validate_body(spec, request)

        assert parameters == RequestParameters()

        code = 400
        message = 'Bad request'
        correlationId = UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')
        rootCause = 'Tag already exist'
        additionalinfo = 'Tag Dog already exist'
        data_json = {
            'code': code,
            'message': message,
            'correlationId': str(correlationId),
            'rootCause': rootCause,
            'additionalinfo': additionalinfo,
        }
        data = json.dumps(data_json)
        response = MockResponse(data, status_code=404)

        response_result = response_validator.validate(request, response)

        assert response_result.errors == []
        assert isinstance(response_result.data, BaseModel)
        assert response_result.data.code == code
        assert response_result.data.message == message
        assert response_result.data.correlationId == correlationId
        assert response_result.data.rootCause == rootCause
        assert response_result.data.additionalinfo == additionalinfo
Beispiel #7
0
    def test_delete_tags_no_requestbody(self, spec, response_validator):
        host_url = 'http://petstore.swagger.io/v1'
        path_pattern = '/v1/tags'
        request = MockRequest(
            host_url,
            'DELETE',
            '/tags',
            path_pattern=path_pattern,
        )

        parameters = validate_parameters(spec, request)
        body = validate_body(spec, request)

        assert parameters == RequestParameters()
        assert body is None
Beispiel #8
0
    def test_post_pets_missing_cookie(self, spec, spec_dict):
        host_url = 'http://petstore.swagger.io/v1'
        path_pattern = '/v1/pets'
        pet_name = 'Cat'
        pet_healthy = True
        data_json = {
            'name': pet_name,
            'ears': {
                'healthy': pet_healthy,
            }
        }
        data = json.dumps(data_json)
        headers = {
            'api_key': self.api_key_encoded,
        }

        request = MockRequest(
            host_url,
            'POST',
            '/pets',
            path_pattern=path_pattern,
            data=data,
            headers=headers,
        )

        with pytest.raises(MissingRequiredParameter):
            validate_parameters(spec, request)

        body = validate_body(spec, request)

        schemas = spec_dict['components']['schemas']
        pet_model = schemas['PetCreate']['x-model']
        assert body.__class__.__name__ == pet_model
        assert body.name == pet_name
        assert not hasattr(body, 'tag')
        assert not hasattr(body, 'address')
    def test_post_pets_missing_header(self, spec, spec_dict):
        host_url = 'https://staging.gigantic-server.com/v1'
        path_pattern = '/v1/pets'
        pet_name = 'Cat'
        pet_healthy = True
        data_json = {
            'name': pet_name,
            'ears': {
                'healthy': pet_healthy,
            }
        }
        data = json.dumps(data_json)
        cookies = {
            'user': '******',
        }

        request = MockRequest(
            host_url,
            'POST',
            '/pets',
            path_pattern=path_pattern,
            data=data,
            cookies=cookies,
        )

        with pytest.raises(MissingRequiredParameter):
            validate_parameters(spec, request)

        body = validate_body(spec, request)

        schemas = spec_dict['components']['schemas']
        pet_model = schemas['PetCreate']['x-model']
        assert body.__class__.__name__ == pet_model
        assert body.name == pet_name
        assert not hasattr(body, 'tag')
        assert not hasattr(body, 'address')
    def test_post_cats_only_required_body(self, spec, spec_dict):
        host_url = 'https://staging.gigantic-server.com/v1'
        path_pattern = '/v1/pets'
        pet_name = 'Cat'
        pet_healthy = True
        data_json = {
            'name': pet_name,
            'ears': {
                'healthy': pet_healthy,
            }
        }
        data = json.dumps(data_json)
        headers = {
            'api_key': self.api_key_encoded,
        }
        cookies = {
            'user': '******',
        }

        request = MockRequest(
            host_url,
            'POST',
            '/pets',
            path_pattern=path_pattern,
            data=data,
            headers=headers,
            cookies=cookies,
        )

        parameters = validate_parameters(spec, request)

        assert parameters == RequestParameters(
            header={
                'api_key': self.api_key,
            },
            cookie={
                'user': 123,
            },
        )

        body = validate_body(spec, request)

        schemas = spec_dict['components']['schemas']
        pet_model = schemas['PetCreate']['x-model']
        assert body.__class__.__name__ == pet_model
        assert body.name == pet_name
        assert not hasattr(body, 'tag')
        assert not hasattr(body, 'address')
    def test_post_tags_created_now(self, spec, response_validator):
        host_url = 'http://petstore.swagger.io/v1'
        path_pattern = '/v1/tags'
        created = 'now'
        pet_name = 'Dog'
        data_json = {
            'created': created,
            'name': pet_name,
        }
        data = json.dumps(data_json)

        request = MockRequest(
            host_url,
            'POST',
            '/tags',
            path_pattern=path_pattern,
            data=data,
        )

        parameters = validate_parameters(spec, request)
        body = validate_body(spec, request)

        assert parameters == RequestParameters()
        assert isinstance(body, BaseModel)
        assert body.created == created
        assert body.name == pet_name

        code = 400
        message = 'Bad request'
        rootCause = 'Tag already exist'
        additionalinfo = 'Tag Dog already exist'
        data_json = {
            'code': 400,
            'message': 'Bad request',
            'rootCause': 'Tag already exist',
            'additionalinfo': 'Tag Dog already exist',
        }
        data = json.dumps(data_json)
        response = MockResponse(data, status_code=404)

        response_result = response_validator.validate(request, response)

        assert response_result.errors == []
        assert isinstance(response_result.data, BaseModel)
        assert response_result.data.code == code
        assert response_result.data.message == message
        assert response_result.data.rootCause == rootCause
        assert response_result.data.additionalinfo == additionalinfo
Beispiel #12
0
    def test_get_pets_invalid_response(self, spec, response_validator):
        host_url = 'http://petstore.swagger.io/v1'
        path_pattern = '/v1/pets'
        query_params = {
            'limit': '20',
        }

        request = MockRequest(
            host_url,
            'GET',
            '/pets',
            path_pattern=path_pattern,
            args=query_params,
        )

        parameters = validate_parameters(spec, request)
        body = validate_body(spec, request)

        assert parameters == RequestParameters(query={
            'limit': 20,
            'page': 1,
            'search': '',
        })
        assert body is None

        data_json = {
            'data': [{
                'id': 1,
                'name': {
                    'first_name': 'Cat',
                },
            }],
        }
        data = json.dumps(data_json)
        response = MockResponse(data)

        response_result = response_validator.validate(request, response)

        original_exc = response_result.errors[0].original_exception
        assert response_result.errors == [
            InvalidMediaTypeValue(original_exception=InvalidSchemaValue(
                type=SchemaType.OBJECT,
                value=data_json,
                schema_errors=original_exc.schema_errors,
                schema_errors_iter=original_exc._schema_errors_iter,
            ), ),
        ]
        assert response_result.data is None
Beispiel #13
0
    def test_post_tags_empty_body(self, spec, spec_dict):
        host_url = 'http://petstore.swagger.io/v1'
        path_pattern = '/v1/tags'
        data_json = {}
        data = json.dumps(data_json)

        request = MockRequest(
            host_url, 'POST', '/tags',
            path_pattern=path_pattern, data=data,
        )

        parameters = validate_parameters(spec, request)

        assert parameters == RequestParameters()

        with pytest.raises(InvalidSchemaValue):
            validate_body(spec, request)
Beispiel #14
0
    def test_post_tags_wrong_property_type(self, spec):
        host_url = 'http://petstore.swagger.io/v1'
        path_pattern = '/v1/tags'
        tag_name = 123
        data = json.dumps(tag_name)

        request = MockRequest(
            host_url, 'POST', '/tags',
            path_pattern=path_pattern, data=data,
        )

        parameters = validate_parameters(spec, request)

        assert parameters == RequestParameters()

        with pytest.raises(InvalidSchemaValue):
            validate_body(spec, request)
    def test_get_pet(self, spec, response_validator):
        host_url = 'http://petstore.swagger.io/v1'
        path_pattern = '/v1/pets/{petId}'
        view_args = {
            'petId': '1',
        }
        request = MockRequest(
            host_url,
            'GET',
            '/pets/1',
            path_pattern=path_pattern,
            view_args=view_args,
        )

        parameters = validate_parameters(spec, request)

        assert parameters == RequestParameters(path={
            'petId': 1,
        })

        body = validate_body(spec, request)

        assert body is None

        data_id = 1
        data_name = 'test'
        data_json = {
            'data': {
                'id': data_id,
                'name': data_name,
                'ears': {
                    'healthy': True,
                },
            },
        }
        data = json.dumps(data_json)
        response = MockResponse(data)

        response_result = response_validator.validate(request, response)

        assert response_result.errors == []
        assert isinstance(response_result.data, BaseModel)
        assert isinstance(response_result.data.data, BaseModel)
        assert response_result.data.data.id == data_id
        assert response_result.data.data.name == data_name
Beispiel #16
0
    def test_get_pets_response(self, spec, response_validator):
        host_url = 'http://petstore.swagger.io/v1'
        path_pattern = '/v1/pets'
        query_params = {
            'limit': '20',
        }

        request = MockRequest(
            host_url, 'GET', '/pets',
            path_pattern=path_pattern, args=query_params,
        )

        parameters = validate_parameters(spec, request)
        body = validate_body(spec, request)

        assert parameters == RequestParameters(
            query={
                'limit': 20,
                'page': 1,
                'search': '',
            }
        )
        assert body is None

        data_json = {
            'data': [
                {
                    'id': 1,
                    'name': 'Cat',
                    'ears': {
                        'healthy': True,
                    },
                }
            ],
        }
        data = json.dumps(data_json)
        response = MockResponse(data)

        response_result = response_validator.validate(request, response)

        assert response_result.errors == []
        assert isinstance(response_result.data, BaseModel)
        assert len(response_result.data.data) == 1
        assert response_result.data.data[0].id == 1
        assert response_result.data.data[0].name == 'Cat'
Beispiel #17
0
        async def decorator(request: web.Request) -> web.StreamResponse:
            app = request.app
            config_dict = request.config_dict

            # Step 1. Ensure that OpenAPI schema exists as well as given
            # operation ID
            schema = get_openapi_schema(config_dict)
            operation = get_openapi_operation(schema, operation_id)

            # Step 2. Ensure that OpenAPI spec exists and convert aiohttp.web
            # request to openapi-core request
            spec = get_openapi_spec(config_dict)
            core_request = await to_openapi_core_request(request)

            # Step 3. Validate request parameters & body
            parameters = to_openapi_parameters(
                validate_parameters(spec, core_request))
            data = validate_body(spec, core_request)

            if isinstance(data, Model):
                data = types.MappingProxyType(vars(data))

            # Step 4. Validate security data if any
            security = validate_security(request, operation, oas=schema)

            # Step 5. Provide OpenAPI context for the handler
            request[OPENAPI_CONTEXT_REQUEST_KEY] = OpenAPIContext(
                request=request,
                app=app,
                config_dict=config_dict,
                operation=operation,
                parameters=parameters,
                data=data,
                security=security,
            )

            # Step 5. Validate response if needed
            response = await handler(request)
            if config_dict[OPENAPI_IS_VALIDATE_RESPONSE_APP_KEY]:
                validate_data(spec, core_request,
                              to_openapi_core_response(response))

            return response
    def test_get_pet_not_found(self, spec, response_validator):
        host_url = 'http://petstore.swagger.io/v1'
        path_pattern = '/v1/pets/{petId}'
        view_args = {
            'petId': '1',
        }
        request = MockRequest(
            host_url,
            'GET',
            '/pets/1',
            path_pattern=path_pattern,
            view_args=view_args,
        )

        parameters = validate_parameters(spec, request)

        assert parameters == RequestParameters(path={
            'petId': 1,
        })

        body = validate_body(spec, request)

        assert body is None

        code = 404
        message = 'Not found'
        rootCause = 'Pet not found'
        data_json = {
            'code': 404,
            'message': message,
            'rootCause': rootCause,
        }
        data = json.dumps(data_json)
        response = MockResponse(data, status_code=404)

        response_result = response_validator.validate(request, response)

        assert response_result.errors == []
        assert isinstance(response_result.data, BaseModel)
        assert response_result.data.code == code
        assert response_result.data.message == message
        assert response_result.data.rootCause == rootCause
    def test_post_no_one_of_schema(self, spec, spec_dict):
        host_url = 'https://staging.gigantic-server.com/v1'
        path_pattern = '/v1/pets'
        pet_name = 'Cat'
        alias = 'kitty'
        data_json = {
            'name': pet_name,
            'alias': alias,
        }
        data = json.dumps(data_json)
        headers = {
            'api_key': self.api_key_encoded,
        }
        cookies = {
            'user': '******',
        }

        request = MockRequest(
            host_url,
            'POST',
            '/pets',
            path_pattern=path_pattern,
            data=data,
            headers=headers,
            cookies=cookies,
        )

        parameters = validate_parameters(spec, request)

        assert parameters == RequestParameters(
            header={
                'api_key': self.api_key,
            },
            cookie={
                'user': 123,
            },
        )

        with pytest.raises(InvalidSchemaValue):
            validate_body(spec, request)
Beispiel #20
0
    def test_delete_tags_with_requestbody(self, spec, response_validator):
        host_url = 'http://petstore.swagger.io/v1'
        path_pattern = '/v1/tags'
        ids = [1, 2, 3]
        data_json = {
            'ids': ids,
        }
        data = json.dumps(data_json)
        request = MockRequest(
            host_url,
            'DELETE',
            '/tags',
            path_pattern=path_pattern,
            data=data,
        )

        parameters = validate_parameters(spec, request)
        body = validate_body(spec, request)

        assert parameters == RequestParameters()
        assert isinstance(body, BaseModel)
        assert body.ids == ids
Beispiel #21
0
    def test_post_tags_extra_body_properties(self, spec, spec_dict):
        host_url = 'http://petstore.swagger.io/v1'
        path_pattern = '/v1/tags'
        pet_name = 'Dog'
        alias = 'kitty'
        data_json = {
            'name': pet_name,
            'alias': alias,
        }
        data = json.dumps(data_json)

        request = MockRequest(
            host_url, 'POST', '/tags',
            path_pattern=path_pattern, data=data,
        )

        parameters = validate_parameters(spec, request)

        assert parameters == RequestParameters()

        with pytest.raises(InvalidSchemaValue):
            validate_body(spec, request)
    def test_post_pets_raises_invalid_mimetype(self, spec):
        host_url = 'https://staging.gigantic-server.com/v1'
        path_pattern = '/v1/pets'
        data_json = {
            'name': 'Cat',
            'tag': 'cats',
        }
        data = json.dumps(data_json)
        headers = {
            'api_key': self.api_key_encoded,
        }
        cookies = {
            'user': '******',
        }

        request = MockRequest(
            host_url,
            'POST',
            '/pets',
            path_pattern=path_pattern,
            data=data,
            mimetype='text/html',
            headers=headers,
            cookies=cookies,
        )

        parameters = validate_parameters(spec, request)

        assert parameters == RequestParameters(
            header={
                'api_key': self.api_key,
            },
            cookie={
                'user': 123,
            },
        )

        with pytest.raises(InvalidContentType):
            validate_body(spec, request)
    def test_get_pets_tags_param(self, spec, response_validator):
        host_url = 'http://petstore.swagger.io/v1'
        path_pattern = '/v1/pets'
        query_params = [
            ('limit', '20'),
            ('tags', 'cats,dogs'),
        ]

        request = MockRequest(
            host_url,
            'GET',
            '/pets',
            path_pattern=path_pattern,
            args=query_params,
        )

        parameters = validate_parameters(spec, request)
        body = validate_body(spec, request)

        assert parameters == RequestParameters(query={
            'limit': 20,
            'page': 1,
            'search': '',
            'tags': ['cats', 'dogs'],
        })
        assert body is None

        data_json = {
            'data': [],
        }
        data = json.dumps(data_json)
        response = MockResponse(data)

        response_result = response_validator.validate(request, response)

        assert response_result.errors == []
        assert isinstance(response_result.data, BaseModel)
        assert response_result.data.data == []
Beispiel #24
0
    def test_get_tags(self, spec, response_validator):
        host_url = 'http://petstore.swagger.io/v1'
        path_pattern = '/v1/tags'

        request = MockRequest(
            host_url, 'GET', '/tags',
            path_pattern=path_pattern,
        )

        parameters = validate_parameters(spec, request)
        body = validate_body(spec, request)

        assert parameters == RequestParameters()
        assert body is None

        data_json = ['cats', 'birds']
        data = json.dumps(data_json)
        response = MockResponse(data)

        response_result = response_validator.validate(request, response)

        assert response_result.errors == []
        assert response_result.data == data_json
    def test_post_cats_boolean_string(self, spec, spec_dict):
        host_url = 'https://staging.gigantic-server.com/v1'
        path_pattern = '/v1/pets'
        pet_name = 'Cat'
        pet_tag = 'cats'
        pet_street = 'Piekna'
        pet_city = 'Warsaw'
        pet_healthy = False
        data_json = {
            'name': pet_name,
            'tag': pet_tag,
            'position': 2,
            'address': {
                'street': pet_street,
                'city': pet_city,
            },
            'healthy': pet_healthy,
            'ears': {
                'healthy': pet_healthy,
            }
        }
        data = json.dumps(data_json)
        headers = {
            'api_key': self.api_key_encoded,
        }
        cookies = {
            'user': '******',
        }

        request = MockRequest(
            host_url,
            'POST',
            '/pets',
            path_pattern=path_pattern,
            data=data,
            headers=headers,
            cookies=cookies,
        )

        parameters = validate_parameters(spec, request)

        assert parameters == RequestParameters(
            header={
                'api_key': self.api_key,
            },
            cookie={
                'user': 123,
            },
        )

        body = validate_body(spec, request)

        schemas = spec_dict['components']['schemas']
        pet_model = schemas['PetCreate']['x-model']
        address_model = schemas['Address']['x-model']
        assert body.__class__.__name__ == pet_model
        assert body.name == pet_name
        assert body.tag == pet_tag
        assert body.position == 2
        assert body.address.__class__.__name__ == address_model
        assert body.address.street == pet_street
        assert body.address.city == pet_city
        assert body.healthy is False
async def validate_parameters(spec: OpenApiSpec, request: web.Request):
    req = await AiohttpOpenAPIRequest.create(request)
    return shortcuts.validate_parameters(spec, req)