Exemple #1
0
    def test_format_request_relationship_bad_format(self):
        """Ensures exception is raised when an inappropriate relation format is presented"""
        class RelatedResource(ResourceBase):
            pks = (
                'id',
                'pk',
            )

        rel_dict = {'resource': dict(data=dict(type='related_resource'))}
        req = RequestContainer(body_args=dict(
            data=dict(attributes=dict(id=1), relationships=rel_dict)))
        self.assertRaises(JSONAPIFormatException,
                          JSONAPIAdapter.format_request, req)

        rel_dict = {'resource': dict(data=dict(id='1/2'))}
        req = RequestContainer(body_args=dict(
            data=dict(attributes=dict(id=1), relationships=rel_dict)))
        self.assertRaises(JSONAPIFormatException,
                          JSONAPIAdapter.format_request, req)

        rel_dict = {'resource': dict(id='1/2', type='related_resource')}
        req = RequestContainer(body_args=dict(
            data=dict(attributes=dict(id=1), relationships=rel_dict)))
        self.assertRaises(JSONAPIFormatException,
                          JSONAPIAdapter.format_request, req)
Exemple #2
0
    def test_create_resource(self):
        resource = create_resource(MyModel, self.session_handler)
        req = RequestContainer(body_args=dict(value='blah'))
        resp = resource.create(req)
        self.assertEqual(resp.properties['value'], 'blah')
        id_ = resp.properties['id']
        session = self.session_handler.get_session()
        resp = session.query(MyModel).get(id_)
        self.assertIsNotNone(resp)
        self.assertEqual(resp.value, 'blah')

        retrieved = resource.retrieve(
            RequestContainer(url_params=dict(id=id_)))
        self.assertEqual(retrieved.properties['value'], 'blah')

        retrieved_list = resource.retrieve_list(RequestContainer())
        self.assertEqual(len(retrieved_list.related_resources), 1)
        relatec = retrieved_list.related_resources[0].resource
        self.assertEqual(len(relatec), 1)

        updated = resource.update(
            RequestContainer(url_params=dict(id=id_),
                             body_args=dict(value='new')))
        self.assertEqual(updated.properties['value'], 'new')
        session = self.session_handler.get_session()
        model = session.query(MyModel).get(id_)
        self.assertEqual(model.value, 'new')

        deleted = resource.delete(RequestContainer(url_params=dict(id=id_)))
        session = self.session_handler.get_session()
        model = session.query(MyModel).get(id_)
        self.assertIsNone(model)
Exemple #3
0
    def test_paginate(self):
        all_models = self.create_resources(count=10)
        req = RequestContainer()
        resource = self.resource_class.retrieve_list(req)
        next_link = None
        for r in resource.linked_resources:
            if r.name == 'next':
                next_link = r
                break
        else:
            assert False
        self.assertEqual(next_link.name, 'next')
        next_resource = next_link.resource
        self.assertIsInstance(next_resource, self.resource_class)

        self.assertIn(self.manager.pagination_count_query_arg, next_resource.get_query_arg_dict())
        self.assertIn(self.manager.pagination_pk_query_arg, next_resource.get_query_arg_dict())

        req = RequestContainer(query_args=next_resource.get_query_arg_dict())
        resource = self.resource_class.retrieve_list(req)
        prev_link = None
        for r in resource.linked_resources:
            if r.name == 'previous':
                prev_link = r
                break
        else:
            assert False
        self.assertEqual(prev_link.name, 'previous')
        prev_resource = prev_link.resource
        self.assertIsInstance(prev_resource, self.resource_class)

        self.assertIn(self.manager.pagination_count_query_arg, prev_resource.get_query_arg_dict())
        self.assertIn(self.manager.pagination_pk_query_arg, prev_resource.get_query_arg_dict())
Exemple #4
0
 def test_format_request_improper_request(self):
     """
     Ensures that the appropriate exception is raised when
     the request is improperly formatted
     """
     req = RequestContainer(body_args=dict(id=1))
     self.assertRaises(JSONAPIFormatException,
                       JSONAPIAdapter.format_request, req)
     req = RequestContainer(body_args=dict(data=dict(id=1)))
     self.assertRaises(JSONAPIFormatException,
                       JSONAPIAdapter.format_request, req)
Exemple #5
0
 def test_required(self):
     field = BaseField('field', required=True)
     req = RequestContainer()
     self.assertRaises(ValidationException,
                       translate_fields,
                       req,
                       fields=[field],
                       validate=True)
     test_body = dict(nothere='this')
     req = RequestContainer(body_args=test_body)
     url, query, body = translate_fields(req,
                                         fields=[field],
                                         validate=True,
                                         skip_required=True)
     self.assertEqual(body, test_body)
Exemple #6
0
    def test_retrieve_list(self):
        all_models = self.create_resources(count=3)
        req = RequestContainer()
        resource = self.resource_class.retrieve_list(req)

        for res in resource.properties[resource.resource_name]:
            self.assertIn(res, self.manager.objects.values())
Exemple #7
0
 def test_retrieve(self):
     id_ = uuid.uuid4()
     model = dict(id=id_, first=1, second=2)
     self.manager.objects[model['id']] = model
     req = RequestContainer(url_params=dict(id=id_))
     resource = self.resource_class.retrieve(req)
     self.assertDictEqual(resource.properties, model)
    def test_all_options(self):
        """
        Tests calling the all_options route
        and constructing all of the links.
        """
        class Fake(ResourceBase):
            pks = ('id', )

            @apimethod()
            def fake(cls, request):
                return cls()

            @apimethod(no_pks=True)
            def fake2(cls, request):
                return cls()

        class MyResource(AllOptionsResource):
            linked_resource_classes = (Fake, )

        options = MyResource.all_options(RequestContainer())
        self.assertEqual(len(options.linked_resources), 2)
        found_fake = False
        found_fake_list = False
        for l in options.linked_resources:
            rel = l.resource
            if l.name == 'fake':
                self.assertEqual(rel.url, '/fake/<id>')
                found_fake = True
            if l.name == 'fake_list':
                self.assertEqual(rel.url, '/fake')
                found_fake_list = True
        self.assertTrue(found_fake)
        self.assertTrue(found_fake_list)
Exemple #9
0
 def test_delete(self):
     id_ = uuid.uuid4()
     model = dict(id=id_, first=1, second=2)
     self.manager.objects[id_] = model
     req = RequestContainer(url_params=dict(id=id_), body_args=dict(first=2))
     resource = self.resource_class.delete(req)
     self.assertDictEqual(resource.properties, {})
     self.assertNotIn(id_, self.manager.objects)
 def test_next_pagination(self):
     """
     Tests basic forward pagination end on
     a multiple of the paginate_by
     """
     self.create_models(count=100)
     req = RequestContainer()
     resource = self.resource.retrieve_list(req)
     self.assertEqual(len(resource.properties['my_resource']), 10)
     count = 1
     while self.get_linked_resource(resource, 'next'):
         next_link = self.get_linked_resource(resource, 'next')
         req = RequestContainer(query_args=next_link.get_query_arg_dict())
         resource = self.resource.retrieve_list(req)
         self.assertEqual(len(resource.properties['my_resource']), 10)
         count += 1
     self.assertEqual(10, count)
 def test_empty(self):
     """
     Tests for when no models have been created
     """
     req = RequestContainer()
     resource = self.resource.retrieve_list(req)
     self.assertEqual(len(resource.linked_resources), 0)
     self.assertEqual(len(resource.properties['my_resource']), 0)
 def test_prev_pagination_uneven_total(self):
     """
     Tests previous pagination with the total count
     of models not as a multiple of the paginate_by.
     """
     self.create_models(count=101)
     req = RequestContainer(query_args=dict(page=11))
     resource = self.resource.retrieve_list(req)
     self.assertEqual(len(resource.properties['my_resource']), 1)
     count = 1
     while self.get_linked_resource(resource, 'previous'):
         previous = self.get_linked_resource(resource, 'previous')
         req = RequestContainer(query_args=previous.get_query_arg_dict())
         resource = self.resource.retrieve_list(req)
         self.assertEqual(len(resource.properties['my_resource']), 10)
         count += 1
     self.assertEqual(11, count)
 def test_next_pagination_partial_end(self):
     """
     Tests forward pagination that ends with a
     partial page (i.e. less than the paginate_by)
     """
     self.create_models(count=101)
     req = RequestContainer()
     resource = self.resource.retrieve_list(req)
     count = 1
     while self.get_linked_resource(resource, 'next'):
         self.assertEqual(len(resource.properties['my_resource']), 10)
         next_link = self.get_linked_resource(resource, 'next')
         req = RequestContainer(query_args=next_link.get_query_arg_dict())
         resource = self.resource.retrieve_list(req)
         count += 1
     self.assertEqual(len(resource.properties['my_resource']), 1)
     self.assertEqual(11, count)
Exemple #14
0
 def test_create_link(self):
     body = dict(first=1, second=2)
     req = RequestContainer(body_args=body)
     resource = self.resource_class.create(req)
     self.assertEqual(len(resource.linked_resources), 1)
     created = resource.linked_resources[0]
     self.assertEqual(created.name, 'created')
     self.assertIsInstance(created.resource, self.resource_class)
     self.assertEqual(created.resource.properties, resource.properties)
Exemple #15
0
 def test_create(self):
     body = dict(first=1, second=2)
     req = RequestContainer(body_args=body)
     resource = self.resource_class.create(req)
     self.assertIsInstance(resource, restmixins.Create)
     resource_id = resource.properties.get('id')
     body.update(dict(id=resource_id))
     self.assertDictEqual(body, resource.properties)
     actual_obj = self.manager.objects[resource_id]
     self.assertDictEqual(actual_obj, resource.properties)
 def test_not_enough_for_pagination(self):
     """
     Tests that no pagination links are available when
     there are less than or equal the paginate_by count
     of records.
     """
     self.create_models(count=10)
     req = RequestContainer()
     resource = self.resource.retrieve_list(req)
     self.assertEqual(len(resource.linked_resources), 0)
     self.assertEqual(len(resource.properties['my_resource']), 10)
Exemple #17
0
 def test_update(self):
     id_ = uuid.uuid4()
     model = dict(id=id_, first=1, second=2)
     self.manager.objects[model['id']] = model
     req = RequestContainer(url_params=dict(id=id_), body_args=dict(first=2))
     resource = self.resource_class.update(req)
     for k, v in resource.properties.items():
         if k is not 'first':
             self.assertEqual(v, model[k])
         else:
             self.assertEqual(v, 2)
Exemple #18
0
    def test_input_category_types(self):
        cat = input_categories.URL_PARAMS
        test_input = dict(field='something')

        # URL_PARAMS
        field = BaseField('field',
                          required=True,
                          arg_type=input_categories.URL_PARAMS)
        req = RequestContainer(url_params=test_input)
        url, query, body = translate_fields(req, fields=[field], validate=True)
        self.assertEqual(url, test_input)
        req = RequestContainer(query_args=test_input, body_args=test_input)
        self.assertRaises(ValidationException,
                          translate_fields,
                          req,
                          fields=[field],
                          validate=True)

        # QUERY_ARGS
        field = BaseField('field',
                          required=True,
                          arg_type=input_categories.QUERY_ARGS)
        req = RequestContainer(query_args=test_input)
        url, query, body = translate_fields(req, fields=[field], validate=True)
        self.assertEqual(query, test_input)
        req = RequestContainer(url_params=test_input, body_args=test_input)
        self.assertRaises(ValidationException,
                          translate_fields,
                          req,
                          fields=[field],
                          validate=True)

        # BODY_ARGS
        field = BaseField('field',
                          required=True,
                          arg_type=input_categories.BODY_ARGS)
        req = RequestContainer(body_args=test_input)
        url, query, body = translate_fields(req, fields=[field], validate=True)
        self.assertEqual(body, test_input)
        req = RequestContainer(query_args=test_input, url_params=test_input)
        self.assertRaises(ValidationException,
                          translate_fields,
                          req,
                          fields=[field],
                          validate=True)

        # Non-existent input type
        field = BaseField('field', required=True, arg_type='fake')
        req = RequestContainer(query_args=test_input,
                               url_params=test_input,
                               body_args=test_input)
        self.assertRaises(RestException,
                          translate_fields,
                          req,
                          fields=[field],
                          validate=True)
Exemple #19
0
    def test_retrieve_list(self):
        all_models = self.create_resources(count=3)
        req = RequestContainer()
        resource = self.resource_class.retrieve_list(req)

        sub_resources = None
        for r in resource.related_resources:
            if r.name == self.resource_class.resource_name:
                sub_resources = r
                break
        else:
            assert False
        self.assertEqual(sub_resources.name, self.resource_class.resource_name)
        sub_resources = sub_resources.resource

        for res in sub_resources:
            self.assertIn(res.properties, self.manager.objects.values())
            self.assertIsInstance(res, self.resource_class)
Exemple #20
0
    def test_format_request_relationships(self):
        """
        Tests that relationships are appropriately reformatted
        to the ripozo style.
        """
        class RelatedResource(ResourceBase):
            pks = (
                'id',
                'pk',
            )

        rel_dict = {
            'resource': dict(data=dict(id='1/2', type='related_resource'))
        }
        req = RequestContainer(body_args=dict(
            data=dict(attributes=dict(id=1), relationships=rel_dict)))
        resp = JSONAPIAdapter.format_request(req)
        self.assertDictEqual(resp.body_args, {
            'id': 1,
            'resource.id': '1',
            'resource.pk': '2'
        })
Exemple #21
0
    def setUp(self):
        logging.disable('DEBUG')

        class MyManager(InMemoryManager):
            _fields = (
                'id',
                'first',
                'second',
            )
            _field_validators = {
                'first': fields.IntegerField('first', required=True),
                'second': fields.IntegerField('second', required=True)
            }

        class MyClass(CRUDL):
            resource_name = 'myresource'
            manager = MyManager()

        self.resource_class = MyClass
        self.manager = MyClass.manager
        for i in six.moves.range(100):
            self.manager.objects[i] = dict(id=i, first=1, second=2)
        self.resource = MyClass.retrieve_list(RequestContainer())
Exemple #22
0
 def test_delete(self):
     ids = six.moves.range(self.runs)
     req = RequestContainer(body_args=dict(first='1', second='2'))
     for i in ids:
         self.manager.objects[i] = dict(id=i, first=1, second=2)
     self.actually_delete(ids)
Exemple #23
0
 def actually_delete(self, ids):
     req = RequestContainer()
     for id_ in ids:
         req._url_params['id'] = id_
         self.resource_class.delete(req)
Exemple #24
0
 def test_create(self):
     req = RequestContainer(body_args=dict(first='1', second='2'))
     for i in six.moves.range(self.runs):
         self.resource_class.create(req)
Exemple #25
0
 def test_update(self):
     self.manager.objects['1'] = dict(id='1', first=1, second=2)
     req = RequestContainer(url_params=dict(id='1'))
     for i in six.moves.range(self.runs):
         req._body_args['first'] = i
         self.resource_class.update(req)
Exemple #26
0
 def test_retrieve(self):
     self.manager.objects['1'] = dict(id='1', first=1, second=2)
     request = RequestContainer(url_params=dict(id='1'))
     for i in six.moves.range(self.runs):
         self.resource_class.retrieve(request)
Exemple #27
0
 def test_retrieve_list(self):
     for i in six.moves.range(100):
         self.manager.objects[i] = dict(id=i, first=1, second=2)
     req = RequestContainer()
     for i in six.moves.range(self.runs):
         self.resource_class.retrieve_list(req)
Exemple #28
0
from helloworld import HelloResource
from ripozo import RequestContainer

res = HelloResource.hello_world(RequestContainer())
    def say_hello(cls, request):
        return cls(properties=request.body_args)


class RelatedResource(ResourceBase):
    _namespace = '/api'
    _resource_name = 'related'
    _pks = ['id']


if __name__ == '__main__':
    from ripozo import RequestContainer

    request = RequestContainer(body_args={
        'say': 'hello',
        'related': {
            'id': 1
        }
    })
    resource = MyResource.say_hello(request)

    # prints {'say': 'hello'}
    print(resource.properties)

    resource_tuple = resource.related_resources[0]

    # prints 'related'
    print(resource_tuple.name)

    # prints '/api/related/1'
    print(resource_tuple.resource.url)
Exemple #30
0
 def test_update(self):
     self.manager.objects['1'] = dict(id='1', first=1, second=2)
     req = RequestContainer(url_params=dict(id='1'))
     for i in six.moves.range(self.runs):
         req._body_args['first'] = i
         self.resource_class.update(req)
Exemple #31
0
 def actually_delete(self, ids):
     req = RequestContainer()
     for id_ in ids:
         req._url_params['id'] = id_
         self.resource_class.delete(req)
Exemple #32
0
 def test_format_request(self):
     """Expected case"""
     req = RequestContainer(body_args=dict(data=dict(attributes=dict(
         id=1))))
     resp = JSONAPIAdapter.format_request(req)
     self.assertDictEqual(resp.body_args, dict(id=1))