def test_request_content_type_validation_ignores_parameters():
    schema = SchemaFactory(
        consumes=['application/json'],
        paths={
            '/get': {
                'get': {
                    'responses': {
                        '200': {
                            'description': 'Success'
                        }
                    },
                }
            },
        },
    )

    request = RequestFactory(
        url='http://www.example.com/get',
        content_type='application/json; charset=utf-8',
    )

    validate_request(
        request=request,
        schema=schema,
    )
def test_request_content_type_validation_when_no_content_type_specified():
    schema = SchemaFactory(
        consumes=['application/json'],
        paths={
            '/get': {
                'get': {
                    'responses': {
                        '200': {
                            'description': 'Success'
                        }
                    },
                }
            },
        },
    )

    request = RequestFactory(
        url='http://www.example.com/get',
        content_type=None,
    )

    # this is considered valid currently, but may change
    validate_request(
        request=request,
        schema=schema,
    )
def test_request_parameter_array_extraction(format_, value):
    schema = SchemaFactory(
        paths={
            '/get/': {
                'get': {
                    'responses': {'200': {'description': "Success"}},
                    'parameters': [
                        {
                            'name': 'id',
                            'in': QUERY,
                            'type': ARRAY,
                            'collectionFormat': format_,
                            'minItems': 3,
                            'maxItems': 3,
                            'items': {
                                'type': INTEGER,
                                'minimum': 1,
                                'maximum': 3,
                            },
                        },
                    ],
                },
            },
        },
    )

    request = RequestFactory(url='http://www.example.com/get/?id={}'.format(value))

    validate_request(
        request=request,
        schema=schema,
    )
def test_request_validation_with_parametrized_path_with_invalid_value():
    """
    Test that request validation finds and validates parametrized paths.
    Ensure that it does validation on the values.
    """
    schema = SchemaFactory(
        paths={
            '/get/{id}': {
                'get': {'responses': {'200': {'description': 'Success'}}},
                'parameters': [
                    {
                        'name': 'id',
                        'in': PATH,
                        'description': 'The Primary Key',
                        'type': INTEGER,
                        'required': True,
                    }
                ]
            },
        }
    )

    request = RequestFactory(url='http://www.example.com/get/abcd')

    with pytest.raises(ValidationError) as err:
        validate_request(
            request=request,
            schema=schema,
        )

    assert_message_in_errors(
        MESSAGES['type']['invalid'],
        err.value.detail,
        'path.id.type',
    )
Exemple #5
0
def test_request_validation_with_invalid_operation_on_path():
    schema = SchemaFactory(
        consumes=['application/json'],
        paths={
            '/get': {
                'get': {
                    'responses': {
                        '200': {
                            'description': 'Success'
                        }
                    },
                }
            },
        },
    )

    request = RequestFactory(
        url='http://www.example.com/get',
        content_type=None,
    )

    validate_request(
        request=request,
        schema=schema,
    )
def test_request_validation_with_valid_path_and_base_path():
    """
    Test that request validation is able to match api paths that also have a
    base api path.
    """
    schema = SchemaFactory(
        basePath='/api/v1',
        paths={
            '/get': {
                'get': {
                    'responses': {
                        200: {
                            'description': "Success"
                        }
                    },
                },
            },
        },
    )

    request = RequestFactory(url='http://www.example.com/api/v1/get')

    validate_request(
        request=request,
        schema=schema,
    )
def test_request_query_parameter_validation_with_no_declared_parameters():
    """
    Ensure that when a query parameter is present with no definition within the
    schema that it is ignored.  We need to have at least one parameter at play
    to trigger parameter validation to happen for this endpoint.
    """
    schema = SchemaFactory(
        parameters = {
            'id': {
                'name': 'id',
                'in': PATH,
                'description': 'id',
                'required': True,
                'type': INTEGER,
            },
        },
        paths={
            '/get/{id}/': {
                'parameters': [
                    {'$ref': '#/parameters/id'},
                ],
                'get': {
                    'responses': {200: {'description': "Success"}},
                },
            },
        },
    )

    request = RequestFactory(url='http://www.example.com/get/3/?page=3')

    validate_request(
        request=request,
        schema=schema,
    )
def test_request_validation_with_parametrized_path():
    """
    Test that request validation finds and validates parametrized paths.
    """
    schema = SchemaFactory(
        paths={
            '/get/{id}': {
                'get': {'responses': {'200': {'description': 'Success'}}},
                'parameters': [
                    {
                        'name': 'id',
                        'in': PATH,
                        'description': 'The Primary Key',
                        'type': INTEGER,
                        'required': True,
                    }
                ]
            },
        }
    )

    request = RequestFactory(url='http://www.example.com/get/1234')

    validate_request(
        request=request,
        schema=schema,
    )
def test_request_validation_with_parametrized_path():
    """
    Test that request validation finds and validates parametrized paths.
    """
    schema = SchemaFactory(
        paths={
            '/get/{id}': {
                'get': {
                    'responses': {
                        200: {
                            'description': 'Success'
                        }
                    }
                },
                'parameters': [{
                    'name': 'id',
                    'in': PATH,
                    'description': 'The Primary Key',
                    'type': INTEGER,
                    'required': True,
                }]
            },
        })

    request = RequestFactory(url='http://www.example.com/get/1234')

    validate_request(
        request=request,
        schema=schema,
    )
def test_request_parameter_validation_with_base_path():
    """
    Test that path parameter validation works even when there is a base path in
    the api.
    """
    schema = SchemaFactory(
        basePath='/api/v1',
        paths={
            '/get/{id}/': {
                'parameters': [
                    {
                        'name': 'id',
                        'in': PATH,
                        'description': 'id',
                        'required': True,
                        'type': STRING,
                    },
                ],
                'get': {
                    'responses': {
                        200: {
                            'description': "Success"
                        }
                    },
                },
            },
        },
    )

    request = RequestFactory(url='http://www.example.com/api/v1/get/32/')

    validate_request(
        request=request,
        schema=schema,
    )
def test_request_validation_with_invalid_operation_on_path():
    """
    Test that request validation detects request paths that are not declared
    in the schema.
    """
    from django.core.exceptions import ValidationError

    schema = SchemaFactory(
        paths={
            '/post': {
                'post': None,
            },
        },
    )

    request = RequestFactory(url='http://www.example.com/post')

    with pytest.raises(ValidationError) as err:
        validate_request(
            request,
            paths=schema['paths'],
            base_path=schema.get('base_path', ''),
            context=schema,
            inner=True,
        )

    assert 'method' in err.value.messages[0]
    assert_error_message_equal(
        err.value.messages[0]['method'][0],
        MESSAGES['request']['invalid_method'],
    )
def test_request_parameter_validation_typecasting(type_, value):
    """
    Test that request validation does parameter validation for all parameters that require
    typecasting since query params are generally treated as strings.
    """
    schema = SchemaFactory(paths={
        '/get/': {
            'parameters': [{
                'name': 'id',
                'in': QUERY,
                'type': type_,
            }],
            'get': {
                'responses': {
                    "200": {
                        'description': "Success"
                    }
                },
            },
        },
    }, )

    request = RequestFactory(
        url='http://www.example.com/get/?id={}'.format(value))

    validate_request(
        request=request,
        schema=schema,
    )
Exemple #13
0
def test_request_body_parameter_validation_with_invalid_value(
        user_post_schema):
    """
    Test validating the request body with a valid post.
    """
    request = RequestFactory(
        url='http://www.example.com/post/',
        content_type='application/json',
        body=json.dumps({
            'username': '******',
            'email': 'test'
        }),
        method=POST,
    )

    with pytest.raises(ValidationError) as err:
        validate_request(
            request=request,
            schema=user_post_schema,
        )

    assert_message_in_errors(
        MESSAGES['format']['invalid_email'],
        err.value.detail,
    )
Exemple #14
0
def test_request_header_validation():
    schema = SchemaFactory(paths={
        '/get/': {
            'get': {
                'responses': {
                    200: {
                        'description': "Success"
                    }
                },
                'parameters': [{
                    'name': 'Authorization',
                    'in': HEADER,
                    'type': INTEGER,
                }]
            },
        },
    }, )

    request = RequestFactory(
        url='http://www.example.com/get/',
        headers={'Authorization': 'abc'},
    )

    with pytest.raises(ValidationError) as err:
        validate_request(
            request=request,
            schema=schema,
        )

    assert_message_in_errors(
        MESSAGES['type']['invalid'],
        err.value.detail,
        'method.parameters.headers.Authorization.type',
    )
def test_request_validation_with_parameter_as_reference():
    """
    Test that request validation finds and validates parametrized paths when
    the parameter is a reference.
    """
    schema = SchemaFactory(
        paths={
            '/get/{id}': {
                'get': {'responses': {200: {'description': 'Success'}}},
                'parameters': [
                    {'$ref': '#/parameters/id'},
                ]
            },
        },
        parameters={
            'id': {
                'name': 'id',
                'in': PATH,
                'description': 'The Primary Key',
                'type': INTEGER,
                'required': True,
            }
        },
    )

    request = RequestFactory(url='http://www.example.com/get/1234')

    validate_request(
        request=request,
        schema=schema,
    )
def test_request_header_validation():
    schema = SchemaFactory(
        paths={
            '/get/': {
                'get': {
                    'responses': {200: {'description': "Success"}},
                    'parameters': [
                        {
                            'name': 'Authorization',
                            'in': HEADER,
                            'type': INTEGER,
                        }
                    ]
                },
            },
        },
    )

    request = RequestFactory(
        url='http://www.example.com/get/',
        headers={'Authorization': 'abc'},
    )

    with pytest.raises(ValidationError) as err:
        validate_request(
            request=request,
            schema=schema,
        )

    assert_message_in_errors(
        MESSAGES['type']['invalid'],
        err.value.detail,
        'method.parameters.headers.Authorization.type',
    )
def test_request_parameter_array_extraction(format_, value):
    schema = SchemaFactory(paths={
        '/get/': {
            'get': {
                'responses': {
                    '200': {
                        'description': "Success"
                    }
                },
                'parameters': [
                    {
                        'name': 'id',
                        'in': QUERY,
                        'type': ARRAY,
                        'collectionFormat': format_,
                        'minItems': 3,
                        'maxItems': 3,
                        'items': {
                            'type': INTEGER,
                            'minimum': 1,
                            'maximum': 3,
                        },
                    },
                ],
            },
        },
    }, )

    request = RequestFactory(
        url='http://www.example.com/get/?id={}'.format(value))

    validate_request(
        request=request,
        schema=schema,
    )
def test_request_parameter_validation():
    """
    Test that request validation does parameter validation.  This is largely a
    smoke test to ensure that parameter validation is wired into request
    validation correctly.
    """
    schema = SchemaFactory(
        paths={
            "/get/{id}/": {
                "parameters": [
                    {"name": "id", "in": PATH, "description": "id", "required": True, "type": STRING, "format": "uuid"},
                    {"name": "page", "in": QUERY, "type": INTEGER},
                ],
                "get": {"responses": {200: {"description": "Success"}}},
            }
        }
    )

    request = RequestFactory(url="http://www.example.com/get/32/?page=abcd")

    with pytest.raises(ValidationError) as err:
        validate_request(request=request, schema=schema)

    assert_message_in_errors(MESSAGES["format"]["invalid_uuid"], err.value.detail, "method.parameters.path.id.format")

    assert_message_in_errors(MESSAGES["type"]["invalid"], err.value.detail, "query.page.type")
def test_request_header_array_extraction(format_, value):
    schema = SchemaFactory(
        paths={
            '/get/': {
                'get': {
                    'responses': {200: {'description': "Success"}},
                    'parameters': [
                        {
                            'name': 'Authorization',
                            'in': HEADER,
                            'type': ARRAY,
                            'collectionFormat': format_,
                            'minItems': 3,
                            'maxItems': 3,
                            'items': {
                                'type': INTEGER,
                                'minimum': 1,
                                'maximum': 3,
                            },
                        },
                    ],
                },
            },
        },
    )

    request = RequestFactory(
        url='http://www.example.com/get/',
        headers={'Authorization': value},
    )

    validate_request(
        request=request,
        schema=schema,
    )
Exemple #20
0
def validate_api_call(schema, raw_request, raw_response):
    """
    Validate the request/response cycle of an api call against a swagger
    schema.  Request/Response objects from the `requests` and `urllib` library
    are supported.
    """
    request = normalize_request(raw_request)
    response = normalize_response(raw_response)

    with ErrorCollection() as errors:
        try:
            validate_request(
                request=request,
                schema=schema,
            )
        except ValidationError as err:
            errors['request'].add_error(err.messages or getattr(err, 'detail'))
            return

        try:
            validate_response(
                response=response,
                request_method=request.method,
                schema=schema,
            )
        except ValidationError as err:
            errors['response'].add_error(err.messages
                                         or getattr(err, 'detail'))
Exemple #21
0
def validate_api_call(schema, raw_request, raw_response):
    """
    Validate the request/response cycle of an api call against a swagger
    schema.  Request/Response objects from the `requests` and `urllib` library
    are supported.
    """
    request = normalize_request(raw_request)
    response = normalize_response(raw_response)

    with ErrorCollection() as errors:
        try:
            validate_request(
                request=request,
                schema=schema,
            )
        except ValidationError as err:
            errors['request'].add_error(err.messages or getattr(err, 'detail'))
            return

        try:
            validate_response(
                response=response,
                request_method=request.method,
                schema=schema,
            )
        except ValidationError as err:
            errors['response'].add_error(err.messages or getattr(err, 'detail'))
Exemple #22
0
def test_request_validation_with_invalid_operation_on_path():
    """
    Test that request validation detects request paths that are not declared
    in the schema.
    """
    schema = SchemaFactory(
        paths={
            '/post': {
                'post': {},
            },
        },
    )

    request = RequestFactory(url='http://www.example.com/post')

    with pytest.raises(ValidationError) as err:
        validate_request(
            request=request,
            schema=schema,
        )

    assert_message_in_errors(
        MESSAGES['request']['invalid_method'],
        err.value.detail,
        'method',
    )
def test_request_parameter_validation_typecasting(type_, value):
    """
    Test that request validation does parameter validation for all parameters that require
    typecasting since query params are generally treated as strings.
    """
    schema = SchemaFactory(
        paths={
            '/get/': {
                'parameters': [
                    {
                        'name': 'id',
                        'in': QUERY,
                        'type': type_,
                    }
                ],
                'get': {
                    'responses': {"200": {'description': "Success"}},
                },
            },
        },
    )

    request = RequestFactory(url='http://www.example.com/get/?id={}'.format(value))

    validate_request(
        request=request,
        schema=schema,
    )
def test_request_parameter_validation_with_base_path():
    """
    Test that path parameter validation works even when there is a base path in
    the api.
    """
    schema = SchemaFactory(
        basePath='/api/v1',
        paths={
            '/get/{id}/': {
                'parameters': [
                    {
                        'name': 'id',
                        'in': PATH,
                        'description': 'id',
                        'required': True,
                        'type': STRING,
                    },
                ],
                'get': {
                    'responses': {200: {'description': "Success"}},
                },
            },
        },
    )

    request = RequestFactory(url='http://www.example.com/api/v1/get/32/')

    validate_request(
        request=request,
        schema=schema,
    )
def test_request_parameter_validation():
    """
    Test that request validation does parameter validation.  This is largely a
    smoke test to ensure that parameter validation is wired into request
    validation correctly.
    """
    schema = SchemaFactory(paths={
        '/get/{id}/': {
            'parameters': [
                {
                    'name': 'id',
                    'in': PATH,
                    'description': 'id',
                    'required': True,
                    'type': STRING,
                    'format': 'uuid',
                },
                {
                    'name': 'page',
                    'in': QUERY,
                    'type': INTEGER,
                },
            ],
            'get': {
                'responses': {
                    200: {
                        'description': "Success"
                    }
                },
            },
        },
    }, )

    request = RequestFactory(url='http://www.example.com/get/32/?page=abcd')

    with pytest.raises(ValidationError) as err:
        validate_request(
            request=request,
            schema=schema,
        )

    assert_message_in_errors(
        MESSAGES['format']['invalid_uuid'],
        err.value.detail,
        'method.parameters.path.id.format',
    )

    assert_message_in_errors(
        MESSAGES['type']['invalid'],
        err.value.detail,
        'query.page.type',
    )
def test_request_parameter_validation():
    """
    Test that request validation does parameter validation.  This is largely a
    smoke test to ensure that parameter validation is wired into request
    validation correctly.
    """
    schema = SchemaFactory(
        paths={
            '/get/{id}/': {
                'parameters': [
                    {
                        'name': 'id',
                        'in': PATH,
                        'description': 'id',
                        'required': True,
                        'type': STRING,
                        'format': 'uuid',
                    },
                    {
                        'name': 'page',
                        'in': QUERY,
                        'type': INTEGER,
                    },
                ],
                'get': {
                    'responses': {200: {'description': "Success"}},
                },
            },
        },
    )

    request = RequestFactory(url='http://www.example.com/get/32/?page=abcd')

    with pytest.raises(ValidationError) as err:
        validate_request(
            request=request,
            schema=schema,
        )

    assert_message_in_errors(
        MESSAGES['format']['invalid_uuid'],
        err.value.detail,
        'method.parameters.path.id.format',
    )

    assert_message_in_errors(
        MESSAGES['type']['invalid'],
        err.value.detail,
        'query.page.type',
    )
def test_request_body_parameter_validation_with_nullable_field(user_post_schema):
    """
    Test validating the request body with a valid post.
    """
    request = RequestFactory(
        url='http://www.example.com/post/',
        content_type='application/json',
        body=json.dumps({'username': '******', 'email': '*****@*****.**', 'age': None}),
        method=POST,
    )

    validate_request(
        request=request,
        schema=user_post_schema,
    )
Exemple #28
0
def test_request_query_parameter_validation_with_array_by_multi():
    """
    Ensure that when a query parameter is present with no definition within the
    schema that it is ignored.  We need to have at least one parameter at play
    to trigger parameter validation to happen for this endpoint.
    """
    schema = SchemaFactory(
        parameters={
            'status': {
                'name': 'status',
                'in': QUERY,
                'description': 'status',
                'required': True,
                'type': ARRAY,
                "items": {
                    "type": "string",
                    "enum": ["available", "pending", "sold"],
                    "default": "available"
                },
                "collectionFormat": "multi"
            },
        },
        paths={
            '/get': {
                'parameters': [
                    {
                        '$ref': '#/parameters/status'
                    },
                ],
                'get': {
                    'responses': {
                        200: {
                            'description': "Success"
                        }
                    },
                },
            },
        },
    )

    request = RequestFactory(url='http://www.example.com/get?status=sold')

    validate_request(
        request=request,
        schema=schema,
    )
Exemple #29
0
def test_request_validation_with_parameter_as_reference_for_invalid_value():
    """
    Test that request validation finds and validates parametrized paths when
    the parameter is a reference.  Ensure that it detects invalid types.
    """
    schema = SchemaFactory(
        paths={
            '/get/{id}': {
                'get': {
                    'responses': {
                        '200': {
                            'description': 'Success'
                        }
                    }
                },
                'parameters': [
                    {
                        '$ref': '#/parameters/id'
                    },
                ]
            },
        },
        parameters={
            'id': {
                'name': 'id',
                'in': PATH,
                'description': 'The Primary Key',
                'type': INTEGER,
                'required': True,
            }
        },
    )

    request = RequestFactory(url='http://www.example.com/get/abc')

    with pytest.raises(ValidationError) as err:
        validate_request(
            request=request,
            schema=schema,
        )

    assert_message_in_errors(
        MESSAGES['path']['no_matching_paths_found'],
        err.value.detail,
        'path',
    )
def test_request_parameter_validation_with_base_path():
    """
    Test that path parameter validation works even when there is a base path in
    the api.
    """
    schema = SchemaFactory(
        basePath="/api/v1",
        paths={
            "/get/{id}/": {
                "parameters": [{"name": "id", "in": PATH, "description": "id", "required": True, "type": STRING}],
                "get": {"responses": {200: {"description": "Success"}}},
            }
        },
    )

    request = RequestFactory(url="http://www.example.com/api/v1/get/32/")

    validate_request(request=request, schema=schema)
Exemple #31
0
def test_request_body_parameter_validation_with_valid_value(user_post_schema):
    """
    Test validating the request body with a valid post.
    """
    request = RequestFactory(
        url='http://www.example.com/post/',
        content_type='application/json',
        body=json.dumps({
            'username': '******',
            'email': '*****@*****.**'
        }),
        method=POST,
    )

    validate_request(
        request=request,
        schema=user_post_schema,
    )
def test_request_validation_with_valid_path():
    """
    Test that request validation is able to match api paths.
    """
    schema = SchemaFactory(
        paths={
            '/get': {
                'get': {'responses': {'200': {'description': 'Success'}}},
            },
        },
    )

    request = RequestFactory(url='http://www.example.com/get')

    validate_request(
        request=request,
        schema=schema,
    )
def test_request_query_parameter_validation_with_array_by_multi():
    """
    Ensure that when a query parameter is present with no definition within the
    schema that it is ignored.  We need to have at least one parameter at play
    to trigger parameter validation to happen for this endpoint.
    """
    schema = SchemaFactory(
        parameters = {
            'status': {
                'name': 'status',
                'in': QUERY,
                'description': 'status',
                'required': True,
                'type': ARRAY,
                "items": {
                    "type": "string",
                    "enum": [
                        "available",
                        "pending",
                        "sold"
                    ],
                    "default": "available"
                },
                "collectionFormat": "multi"
            },
        },
        paths={
            '/get': {
                'parameters': [
                    {'$ref': '#/parameters/status'},
                ],
                'get': {
                    'responses': {200: {'description': "Success"}},
                },
            },
        },
    )

    request = RequestFactory(url='http://www.example.com/get?status=sold')

    validate_request(
        request=request,
        schema=schema,
    )
def test_request_body_parameter_validation_with_invalid_value(user_post_schema):
    """
    Test validating the request body with a valid post.
    """
    request = RequestFactory(
        url='http://www.example.com/post/',
        content_type='application/json',
        body=json.dumps({'username': '******', 'email': 'test'}),
        method=POST,
    )

    with pytest.raises(ValidationError) as err:
        validate_request(
            request=request,
            schema=user_post_schema,
        )

    assert_message_in_errors(
        MESSAGES['format']['invalid_email'],
        err.value.detail,
    )
def test_request_validation_with_invalid_request_path():
    """
    Test that request validation detects request paths that are not declared
    in the schema.
    """
    schema = SchemaFactory()
    assert not schema['paths']

    request = RequestFactory(url='http://www.example.com/not-an-api-path')

    with pytest.raises(ValidationError) as err:
        validate_request(
            request=request,
            schema=schema,
        )

    assert_message_in_errors(
        MESSAGES['path']['no_matching_paths_found'],
        err.value.detail,
        'path',
    )
def test_request_validation_with_invalid_request_path():
    """
    Test that request validation detects request paths that are not declared
    in the schema.
    """
    schema = SchemaFactory()
    assert not schema['paths']

    request = RequestFactory(url='http://www.example.com/not-an-api-path')

    with pytest.raises(ValidationError) as err:
        validate_request(
            request=request,
            schema=schema,
        )

    assert_message_in_errors(
        MESSAGES['path']['no_matching_paths_found'],
        err.value.detail,
        'path',
    )
def test_request_validation_with_invalid_operation_on_path():
    schema = SchemaFactory(
        consumes=['application/json'],
        paths={
            '/get': {
                'get': {
                    'responses': {'200': {'description': 'Success'}},
                }
            },
        },
    )

    request = RequestFactory(
        url='http://www.example.com/get',
        content_type=None,
    )

    validate_request(
        request=request,
        schema=schema,
    )
def test_request_content_type_validation_ignores_parameters():
    schema = SchemaFactory(
        consumes=['application/json'],
        paths={
            '/get': {
                'get': {
                    'responses': {'200': {'description': 'Success'}},
                }
            },
        },
    )

    request = RequestFactory(
        url='http://www.example.com/get',
        content_type='application/json; charset=utf-8',
    )

    validate_request(
        request=request,
        schema=schema,
    )
Exemple #39
0
def test_request_query_parameter_validation_with_no_declared_parameters():
    """
    Ensure that when a query parameter is present with no definition within the
    schema that it is ignored.  We need to have at least one parameter at play
    to trigger parameter validation to happen for this endpoint.
    """
    schema = SchemaFactory(
        parameters={
            'id': {
                'name': 'id',
                'in': PATH,
                'description': 'id',
                'required': True,
                'type': INTEGER,
            },
        },
        paths={
            '/get/{id}/': {
                'parameters': [
                    {
                        '$ref': '#/parameters/id'
                    },
                ],
                'get': {
                    'responses': {
                        200: {
                            'description': "Success"
                        }
                    },
                },
            },
        },
    )

    request = RequestFactory(url='http://www.example.com/get/3/?page=3')

    validate_request(
        request=request,
        schema=schema,
    )
Exemple #40
0
def test_request_validation_with_parameter_as_reference():
    """
    Test that request validation finds and validates parametrized paths when
    the parameter is a reference.
    """
    schema = SchemaFactory(
        paths={
            '/get/{id}': {
                'get': {
                    'responses': {
                        '200': {
                            'description': 'Success'
                        }
                    }
                },
                'parameters': [
                    {
                        '$ref': '#/parameters/id'
                    },
                ]
            },
        },
        parameters={
            'id': {
                'name': 'id',
                'in': PATH,
                'description': 'The Primary Key',
                'type': INTEGER,
                'required': True,
            }
        },
    )

    request = RequestFactory(url='http://www.example.com/get/1234')

    validate_request(
        request=request,
        schema=schema,
    )
def test_request_validation_with_valid_path():
    """
    Test that request validation is able to match api paths.
    """
    schema = SchemaFactory(paths={
        '/get': {
            'get': {
                'responses': {
                    200: {
                        'description': 'Success'
                    }
                }
            },
        },
    }, )

    request = RequestFactory(url='http://www.example.com/get')

    validate_request(
        request=request,
        schema=schema,
    )
def test_request_content_type_validation_when_no_content_type_specified():
    schema = SchemaFactory(
        consumes=['application/json'],
        paths={
            '/get': {
                'get': {
                    'responses': {'200': {'description': 'Success'}},
                }
            },
        },
    )

    request = RequestFactory(
        url='http://www.example.com/get',
        content_type=None,
    )

    # this is considered valid currently, but may change
    validate_request(
        request=request,
        schema=schema,
    )
def test_request_validation_with_valid_path_and_base_path():
    """
    Test that request validation is able to match api paths that also have a
    base api path.
    """
    schema = SchemaFactory(
        basePath='/api/v1',
        paths={
            '/get': {
                'get': {
                    'responses': {'200': {'description': "Success"}},
                },
            },
        },
    )

    request = RequestFactory(url='http://www.example.com/api/v1/get')

    validate_request(
        request=request,
        schema=schema,
    )
def test_request_validation_with_parameter_as_reference_for_invalid_value():
    """
    Test that request validation finds and validates parametrized paths when
    the parameter is a reference.  Ensure that it detects invalid types.
    """
    schema = SchemaFactory(
        paths={
            '/get/{id}': {
                'get': {'responses': {'200': {'description': 'Success'}}},
                'parameters': [
                    {'$ref': '#/parameters/id'},
                ]
            },
        },
        parameters={
            'id': {
                'name': 'id',
                'in': PATH,
                'description': 'The Primary Key',
                'type': INTEGER,
                'required': True,
            }
        },
    )

    request = RequestFactory(url='http://www.example.com/get/abc')

    with pytest.raises(ValidationError) as err:
        validate_request(
            request=request,
            schema=schema,
        )

    assert_message_in_errors(
        MESSAGES['path']['no_matching_paths_found'],
        err.value.detail,
        'path',
    )
def test_request_validation_with_parametrized_path_with_invalid_value():
    """
    Test that request validation finds and validates parametrized paths.
    Ensure that it does validation on the values.
    """
    schema = SchemaFactory(
        paths={
            '/get/{id}': {
                'get': {
                    'responses': {
                        200: {
                            'description': 'Success'
                        }
                    }
                },
                'parameters': [{
                    'name': 'id',
                    'in': PATH,
                    'description': 'The Primary Key',
                    'type': INTEGER,
                    'required': True,
                }]
            },
        })

    request = RequestFactory(url='http://www.example.com/get/abcd')

    with pytest.raises(ValidationError) as err:
        validate_request(
            request=request,
            schema=schema,
        )

    assert_message_in_errors(
        MESSAGES['type']['invalid'],
        err.value.detail,
        'path.id.type',
    )
Exemple #46
0
def test_request_header_array_extraction(format_, value):
    schema = SchemaFactory(paths={
        '/get/': {
            'get': {
                'responses': {
                    200: {
                        'description': "Success"
                    }
                },
                'parameters': [
                    {
                        'name': 'Authorization',
                        'in': HEADER,
                        'type': ARRAY,
                        'collectionFormat': format_,
                        'minItems': 3,
                        'maxItems': 3,
                        'items': {
                            'type': INTEGER,
                            'minimum': 1,
                            'maximum': 3,
                        },
                    },
                ],
            },
        },
    }, )

    request = RequestFactory(
        url='http://www.example.com/get/',
        headers={'Authorization': value},
    )

    validate_request(
        request=request,
        schema=schema,
    )
def test_request_parameter_validation():
    """
    Test that request validation does parameter validation.  This is largely a
    smoke test to ensure that parameter validation is wired into request
    validation correctly.
    """
    from django.core.exceptions import ValidationError

    schema = SchemaFactory(
        paths={
            '/get/{id}/': {
                'parameters': [
                    {
                        'name': 'id',
                        'in': PATH,
                        'description': 'id',
                        'required': True,
                        'type': STRING,
                        'format': 'uuid',
                    },
                    {
                        'name': 'page',
                        'in': QUERY,
                        'type': INTEGER,
                    },
                ],
                'get': {
                    'responses': {200: {'description': "Success"}},
                },
            },
        },
    )

    request = RequestFactory(url='http://www.example.com/get/32/?page=abcd')

    with pytest.raises(ValidationError) as err:
        validate_request(
            request,
            paths=schema['paths'],
            base_path=schema.get('base_path', ''),
            context=schema,
            inner=True,
        )

    assert 'method' in err.value.messages[0]
    assert 'parameters' in err.value.messages[0]['method'][0][0]
    assert 'path' in err.value.messages[0]['method'][0][0]['parameters'][0]
    assert 'id' in err.value.messages[0]['method'][0][0]['parameters'][0]['path'][0]
    assert 'format' in err.value.messages[0]['method'][0][0]['parameters'][0]['path'][0]['id'][0]
    assert_error_message_equal(
        err.value.messages[0]['method'][0][0]['parameters'][0]['path'][0]['id'][0]['format'][0],
        MESSAGES['format']['invalid_uuid'],
    )

    assert 'query' in err.value.messages[0]['method'][0][0]['parameters'][0]
    assert 'page' in err.value.messages[0]['method'][0][0]['parameters'][0]['query'][0]
    assert 'type' in err.value.messages[0]['method'][0][0]['parameters'][0]['query'][0]['page'][0]
    assert_error_message_equal(
        err.value.messages[0]['method'][0][0]['parameters'][0]['query'][0]['page'][0]['type'][0],
        MESSAGES['type']['invalid'],
    )
Exemple #48
0
def validate_api_request(schema, raw_request):
    request = normalize_request(raw_request)

    with ErrorDict():
        validate_request(request=request, schema=schema)