def test_require_representation_application_json(): resource = TestResource() # simple application/json content type env = create_environ( body=json.dumps({ 'one': 'foo', 'two': 'foo' }), headers={'Content-Type': 'application/json'}, ) representation = resource.require_representation(Request(env)) assert isinstance(representation, dict) # application/json content type with charset param env = create_environ( body=json.dumps({ 'one': 'foo', 'two': 'foo' }), headers={'Content-Type': 'application/json; charset=UTF-8'}, ) representation = resource.require_representation(Request(env)) assert isinstance(representation, dict)
def test_require_representation_unsupported_media_type(): resource = TestResource() # invalid content type format env = create_environ( body=json.dumps({ 'one': 'foo', 'two': 'foo' }), headers={'Content-Type': 'foo bar'}, ) with pytest.raises(falcon.HTTPUnsupportedMediaType): resource.require_representation(Request(env)) # valid format but surely unsupported (RFC-1437) env = create_environ( body=json.dumps({ 'one': 'foo', 'two': 'foo' }), headers={'Content-Type': 'matter-transport/sentient-life-form'}, ) with pytest.raises(falcon.HTTPUnsupportedMediaType): resource.require_representation(Request(env))
def test_on_put_error_result(self): """ Test if we will receive correct response """ resource = CollectionResource(objects_class=FakeObjectClass) env = create_environ(path='/') req = Request(env) req.context = { 'doc': { 'id': 1, } } def clean(data): if 'name' not in data: return {}, {'name': ['Test Error Message']} resource.clean = clean resp = Response() resource.on_put(req=req, resp=resp) self.assertEqual(resp.body, {'errors': { 'name': ['Test Error Message'] }})
def test_whole_serializer_validation_as_hhtp_bad_request(req): class TestSerializer(BaseSerializer): one = StringField("one different than two") two = StringField("two different than one") def validate(self, object_dict, partial=False): super().validate(object_dict, partial) # possible use case: kind of uniqueness relationship if object_dict['one'] == object_dict['two']: raise ValidationError("one must be different than two") class TestResource(Resource): serializer = TestSerializer() resource = TestResource() env = create_environ( body=json.dumps({ 'one': 'foo', 'two': 'foo' }), headers={'Content-Type': 'application/json'}, ) with pytest.raises(errors.HTTPBadRequest): resource.require_validated(Request(env))
def test_options(resp): """ Test that options is a json serialized output of resource.describe() Args: req (falcon.Request): request instance object provided by ``req`` pytest fixture resp (falcon.Response): responce instance provided by ``resp`` pytest fixture """ # note: creating request is optional here since we bypass whole falcon # routing and dispatching procedure env = create_environ(method="OPTIONS") req = Request(env) # noqa resource = Resource() resource.on_options(req, resp) assert all([ 'OPTIONS' in _retrieve_header(resp, 'allow'), 'GET' in _retrieve_header(resp, 'allow'), ]) assert resp.status == falcon.HTTP_200 assert json.loads(resp.body) # assert this is obviously the same assert resource.describe(req, resp) == json.loads(resp.body)
def test_oauth_middleware_request_auth_invalid(headers): auth_middleware = JwtMiddleware() auth_middleware._verification_key = RSA_2048_PUB_KEY with pytest.raises(falcon.HTTPUnauthorized): auth_middleware.process_resource( Request(create_environ(headers=headers)), None, None, None)
def test_slots_request(self): env = testing.create_environ() req = Request(env) try: req.doesnt = 'exist' except AttributeError: pytest.fail('Unable to add additional variables dynamically')
def test_parameter_with_many_and_required(): class SomeResource(Resource): foo = IntParam(details="give me foo", required=True, many=True) env = create_environ(query_string="foo=1&foo=2") resource = SomeResource() params = resource.require_params(Request(env)) assert isinstance(params['foo'], Iterable) assert set(params['foo']) == {1, 2}
def create_request(method, path, subdomain=None, query_string=None, content_type='application/json'): environ = environ_factory(method, path, server_name) options = RequestOptions() # return create_req(options=options, **environ) req = Request(environ, options) return req
def test_oauth_middleware_request_auth_valid(): auth_middleware = JwtMiddleware() auth_middleware._verification_key = RSA_2048_PUB_KEY test_req = Request( create_environ(headers={'Authorization': TEST_AUTH_HEADER})) test_resp = Response() auth_middleware.process_resource(test_req, test_resp, None, None) auth_middleware.process_request(test_req, test_resp) auth_middleware.process_response(test_req, test_resp, None)
def test_on_put_success_result(self): """ Test if we will receive correct response """ resource = CollectionResource(objects_class=FakeObjectClass) env = create_environ(path='/') req = Request(env) req.context = {'doc': {'id': 1, 'name': 'Opentopic'}} resp = Response() resource.on_put(req=req, resp=resp) self.assertEqual(resp.body, {'id': 1, 'name': 'Opentopic'})
def test_parameter_with_validation_raises_bad_request(query_string): class SomeResource(Resource): number = IntParam(details="number with min/max bounds", validators=[min_validator(10), max_validator(20)]) env = create_environ(query_string=query_string) resource = SomeResource() with pytest.raises(errors.HTTPBadRequest): resource.require_params(Request(env))
def test_parameter_with_validation_enabled_passes(query_string): class SomeResource(Resource): number = IntParam(details="number with min/max bounds", validators=[min_validator(10), max_validator(20)]) env = create_environ(query_string=query_string) resource = SomeResource() params = resource.require_params(Request(env)) assert isinstance(params['number'], int)
def create_request(method, path, subdomain=None, query_string=None, content_type='application/json'): environ = environ_factory(method, path, server_name) options = RequestOptions() # return create_req(options=options, **environ) req = Request(environ, options) resource, method_map, params, req.uri_template = router.find(path, req) return req
def test_render_response_result(self): """ check if result is available request context """ env = create_environ(path='/') req = Request(env) resp = Response() result = 'Cognitive Digital Marketing :)' BaseResource.render_response( result=result, req=req, resp=resp ) self.assertEqual(resp.body, 'Cognitive Digital Marketing :)')
def test_update_withtout_pk(self): """ test how update function will handle when we are not going to pass pk value """ resource = SingleResource(objects_class=None) env = create_environ(path='/') req = Request(env) req.context = {'doc': {}} resp = Response() with self.assertRaises(Exception): resource.on_patch(req, resp)
def test_render_response_status_200(self): """ need to check if status of the response is set for 200 and """ env = create_environ(path='/') req = Request(env) resp = Response() result = None BaseResource.render_response( result=result, req=req, resp=resp ) self.assertTrue(resp.status, 200)
def test_update_get_object(self): """ Test `get_object` func """ resource = SingleResource(objects_class=None) env = create_environ(path='/') req = Request(env) req.context = {'doc': {'pk': 1}} resp = Response() resource.objects_class = FakeObjectList() obj = resource.get_object(req=req, resp=resp, path_params={}) self.assertEqual(obj.pk, 1)
def test_parameter_with_many_and_custom_container_method(): class StringSetParam(StringParam): # container is custom method call ("bound" to param instance) def container(self, values): return set(values) class SomeResource(Resource): foo = StringSetParam(details="give me foo", many=True) env = create_environ(query_string="foo=bar&foo=baz") resource = SomeResource() params = resource.require_params(Request(env)) assert isinstance(params['foo'], set) assert 'bar' in params['foo'] and 'baz' in params['foo']
def test_parameter_with_many_and_custom_container_type_object(): class StringSetParam(StringParam): # container is simply a type object (it is not a descriptor) # so does not receive self as a parameter container = set class SomeResource(Resource): foo = StringSetParam(details="give me foo", many=True) env = create_environ(query_string="foo=bar&foo=baz") resource = SomeResource() params = resource.require_params(Request(env)) assert isinstance(params['foo'], set) assert 'bar' in params['foo'] and 'baz' in params['foo']
def test_parameter_with_many_and_default(req): class SomeResource(Resource): foo = StringParam(details="give me foo", default='baz', many=True) resource = SomeResource() params = resource.require_params(req) assert isinstance(params['foo'], Iterable) assert params['foo'] == ['baz'] env = create_environ(query_string="foo=bar") params = resource.require_params(Request(env)) assert isinstance(params['foo'], Iterable) assert params['foo'] == ['bar']
def test_options_with_additional_args(req, resp): """ Test that requesting OPTIONS will succeed even if not expected additional kwargs are passed. Note: this is a case when OPTIONS are requested on resource that is routed with URL template. """ # note: creating request is optional here since we bypass whole falcon # routing and dispatching procedure env = create_environ(method="OPTIONS") req = Request(env) # noqa resource = Resource() resource.on_options(req, resp, additionnal_kwarg="foo")
def test_on_head(self): """ need to check if status of the response is set for 200 and """ env = create_environ(path='/') req = Request(env) req.context = {'doc': {}} req.params[mongoengine.CollectionResource.PARAM_TOTAL_COUNT] = '1' resp = Response() resource = mongoengine.CollectionResource( objects_class=Mock(return_value=[1, 2, 3]), max_limit=2) resource.get_object_list = Mock(return_value=[1, 2]) resource.get_total_objects = Mock(return_value={'total_count': 3}) resource.on_head(req=req, resp=resp) self.assertIsNot(resp.body, [1, 2, 3]) self.assertEqual(resp.get_header('x-api-total'), '3') self.assertEqual(resp.get_header('x-api-returned'), '2')
def test_basic_documentation_output_type_accept(): """Ensure API documentation works with selectable output types""" accept_output = hug.output_format.accept( { "application/json": hug.output_format.json, "application/pretty-json": hug.output_format.pretty_json, }, default=hug.output_format.json, ) with mock.patch.object(api.http, "_output_format", accept_output, create=True): handler = api.http.documentation_404() response = StartResponseMock() handler(Request(create_environ(path="v1/doc")), response) documentation = json.loads(response.data.decode("utf8"))["documentation"] assert "handlers" in documentation and "overview" in documentation
def test_on_options(self): """ need to check if status of the response is set for 200 and """ env = create_environ(path='/') req = Request(env) req.context = {'doc': {}} resp = Response() resource = mongoengine.CollectionResource(objects_class=FakeObjectList, max_limit=2) resource.on_options(req=req, resp=resp) self.assertEqual(resp.get_header('Allow'), 'GET, HEAD, OPTIONS, POST, PUT') self.assertEqual( resp.body, { 'name': 'FakeObjectList', 'description': 'Extend list to match interface of List resource', })
def test_basic_documentation_output_type_accept(): """Ensure API documentation works with selectable output types""" accept_output = hug.output_format.accept( { 'application/json': hug.output_format.json, 'application/pretty-json': hug.output_format.pretty_json }, default=hug.output_format.json) with mock.patch.object(api.http, '_output_format', accept_output, create=True): handler = api.http.documentation_404() response = StartResponseMock() handler(Request(create_environ(path='v1/doc')), response) documentation = json.loads(response.data.decode('utf8'))['documentation'] assert 'handlers' in documentation and 'overview' in documentation
def test_clean_check_error_raising(self): """ Check if clean function returns errors dict when `clean_param_name` raise `ParamException` """ resource = CollectionResource(objects_class=None) env = create_environ(path='/') req = Request(env) req.context = {'doc': {'id': 1, 'name': 'Opentopic'}} Response() def clean_name_test(self): raise ParamException('Test Error Message') resource.clean_name = clean_name_test data, errors = resource.clean(req.context['doc']) self.assertEqual(data, { 'id': 1, }) self.assertEqual(errors, {'name': ['Test Error Message']})
def test_auth_middleware_basic(): middleware = AuthenticateMiddleware() req = Request({ 'wsgi.errors': '', 'wsgi.input': '', 'REQUEST_METHOD': 'GET', 'SCRIPT_NAME': '', 'PATH_INFO': '', 'SERVER_PROTOCOL': 'HTTP/1.1', 'HTTP_AUTHORIZATION': 'Basic {}'.format(basic_token) }) resp = Response() middleware.process_request(req, resp) assert 'user' in req.context assert 'dataset' in req.context['user'] assert 'sub' in req.context['user'] assert req.context['user']['dataset'] == 'ds002404' assert req.context['user']['sub'] == 'fd44f5c5-b21b-420b-9555-af856efc9452'
def test_update_params(self): """ Test if param is updated and returned """ resource = SingleResource(objects_class=None) env = create_environ(path='/') req = Request(env) req.context = { 'doc': { 'pk': 1, 'name': 'TestNewName' }, } resp = Response() resource.objects_class = FakeObjectList() resource.serialize = fake_serialize resource.on_patch(req, resp) self.assertEqual({ 'pk': 1, 'name': 'TestNewName', '_saved': True }, resp.body)
def test_update_password(self, api, user1, user2, authenticated_user): # Given response = StartResponseMock() request = Request(create_environ(headers={'AUTHORIZATION': 'XXXX'})) # When result = api.update_password(user1.user_id, "newpassword", request, response, authenticated_user) # Then user = TESTSESSION.query(User).filter_by(user_id=user1.user_id).one() assert check_password(user, "newpassword") is True # When result = api.update_password(-1, "newpassword", request, response, authenticated_user) # Then assert response.status == HTTP_404 assert result is None # When result = api.update_password(user2.user_id, "newpassword", request, response, authenticated_user) # Then assert response.status == HTTP_401 assert result == ("Authenticated user isn't allowed to update the" " password for requested user")