def test_consumes_validation_for_valid_mimetype_from_operation_definition(): """ Test that when `consumes` is defined in an operation definition, that the local value is used in place of any global `consumes` definition. """ request = RequestFactory(content_type='application/json') response = ResponseFactory(request=request) schema = SchemaFactory( consumes=['application/xml'], paths={ '/get': { 'get': { 'responses': { '200': { 'description': 'Success' } }, 'consumes': ['application/json'], } }, }, ) validators = construct_operation_validators( api_path='/get', path_definition=schema['paths']['/get'], operation_definition=schema['paths']['/get']['get'], context=schema, ) validate_operation(response.request, validators)
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_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_consumes_validation_for_invalid_mimetype_from_operation_definition(): """ Test the situation when the operation definition has overridden the global allowed mimetypes, that that the local value is used for validation. """ request = RequestFactory(content_type='application/xml') response = ResponseFactory(request=request) schema = SchemaFactory( consumes=['application/xml'], paths={ '/get': { 'get': { 'responses': { '200': { 'description': 'Success' } }, 'consumes': ['application/json'], } }, }, ) validators = construct_operation_validators( api_path='/get', path_definition=schema['paths']['/get'], operation_definition=schema['paths']['/get']['get'], context=schema, ) with pytest.raises(ValidationError): validate_operation(response.request, validators)
def test_query_data_for_multi_value_keys(): request = RequestFactory( url='http://www.example.com/api/?token=1234&token=5678&secret=abcd', ) assert request.query_data == { 'token': ['1234', '5678'], 'secret': ['abcd'] }
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_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_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_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_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_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_unsupported_content_type(): request = RequestFactory( body=json.dumps({'key': 'value'}), content_type='application/unsupported', ) with pytest.raises(NotImplementedError): request.data
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_parametrized_path_with_parameter_definition_as_reference(): context = SchemaFactory( paths={ '/get/{id}': { '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/12345') path = validate_path_to_api_path( path=request.path, context=context, **context ) assert path == '/get/{id}'
def test_consumes_validation_invalid_mimetype_from_global_definition(): """ Test that a request content_type that is in the global api consumes definitions is valid. """ request = RequestFactory(content_type='application/json') response = ResponseFactory(request=request) schema = SchemaFactory( consumes=['text/xml', 'application/xml'], paths={ '/get': { 'get': { 'responses': { '200': { 'description': 'Success' } } } }, }, ) validators = construct_operation_validators( api_path='/get', path_definition=schema['paths']['/get'], operation_definition=schema['paths']['/get']['get'], context=schema, ) with pytest.raises(ValidationError): validate_operation(response.request, validators)
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_index_with_requests(self): for _ in range(0, 10): RequestFactory() response = self.client.get('/sauron/requests/') self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'requests.html') self.assertContains(response, '<ul>')
def test_json_content_type_with_json_bytes_body(): body = json.dumps({'key': 'value', 'key2': 'value2', 'key[1]': 'subvalue1', 'key[2]': 'subvalue2'}).encode('utf-8') assert type(body) == bytes request = RequestFactory( body=body, content_type='application/json', ) assert request.data == {'key': 'value', 'key2': 'value2', 'key[1]': 'subvalue1', 'key[2]': 'subvalue2'}
def test_form_content_type_with_body(): request = RequestFactory( body="key=value&key2=value2&arr[1]=subvalue1&arr[2]=subvalue2", content_type='application/x-www-form-urlencoded', ) assert request.data == { 'key': 'value', 'key2': 'value2', 'arr[1]': 'subvalue1', 'arr[2]': 'subvalue2' }
def test_basic_request_path_validation(): context = SchemaFactory( paths={'/get': {}}, ) request = RequestFactory(url='http://www.example.com/get') path = validate_path_to_api_path( path=request.path, context=context, **context ) assert path == '/get'
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_py2_invalid_json(): body = '{"trailing comma not valid": [1,]}' request = RequestFactory( body=body, content_type='application/json', ) try: json.loads(body) except ValueError as e: expected_message = str(e) with pytest.raises(JSONDecodeError) as e: request.data assert str(e.value) == expected_message
def test_py3_invalid_json(): body = '{"trailing comma not valid": [1,]}' request = RequestFactory( body=body, content_type='application/json', ) try: json.loads(body) except JSONDecodeError as e: expected_exception = e with pytest.raises(JSONDecodeError) as e: request.data assert e.value.msg == expected_exception.msg
def test_json_content_type_with_json_body(): request = RequestFactory( body=json.dumps({ 'key': 'value', 'key2': 'value2', 'key[1]': 'subvalue1', 'key[2]': 'subvalue2' }), content_type='application/json', ) assert request.data == { 'key': 'value', 'key2': 'value2', 'key[1]': 'subvalue1', 'key[2]': 'subvalue2' }
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_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_parametrized_integer_path_validation(): context = SchemaFactory(paths={ '/get/{id}': { 'parameters': [ # One very plain id of type string. {'name': 'id', 'in': PATH, 'description': 'The id', 'type': INTEGER, 'required': True}, ], } }) request = RequestFactory(url='http://www.example.com/get/25') path = validate_path_to_api_path( path=request.path, context=context, **context ) assert path == '/get/{id}'
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_parametrized_path_with_multiple_prameters(): context = SchemaFactory(paths={ '/users/{username}/posts/{id}': { 'parameters': [ # One very plain id of type string. {'name': 'id', 'in': PATH, 'description': 'The id', 'type': INTEGER, 'required': True}, {'name': 'username', 'in': PATH, 'description': 'The username', 'type': STRING, 'required': True}, ], } }) request = RequestFactory(url='http://www.example.com/users/john-smith/posts/47') path = validate_path_to_api_path( path=request.path, context=context, **context ) assert path == '/users/{username}/posts/{id}'