Пример #1
0
    def test_create_update(self):
        from papyrus.protocol import Protocol
        from pyramid.request import Request
        from geojson import Feature, FeatureCollection
        from shapely.geometry import Point

        MappedClass = self._get_mapped_class()

        # a mock session specific to this test
        class MockSession(object):
            def query(self, mapped_class):
                return {'a': mapped_class(Feature(id='a')),
                        'b': mapped_class(Feature(id='b'))}
            def flush(self):
                pass

        proto = Protocol(MockSession, MappedClass, 'geom')

        # we need an actual Request object here, for body to do its job
        request = Request({})
        request.method = 'POST'
        request.body = '{"type": "FeatureCollection", "features": [{"type": "Feature", "id": "a", "properties": {"text": "foo"}, "geometry": {"type": "Point", "coordinates": [45, 5]}}, {"type": "Feature", "id": "b", "properties": {"text": "bar"}, "geometry": {"type": "Point", "coordinates": [46, 6]}}]}'
        features = proto.create(request)

        self.assertTrue(isinstance(features, FeatureCollection))
        self.assertEqual(len(features.features), 2)
        self.assertEqual(features.features[0].id, 'a')
        self.assertEqual(features.features[0].text, 'foo')
        self.assertTrue(features.features[0].geom.shape.equals(Point(45, 5)))
        self.assertEqual(features.features[1].id, 'b')
        self.assertEqual(features.features[1].text, 'bar')
        self.assertTrue(features.features[1].geom.shape.equals(Point(46, 6)))
Пример #2
0
    def test_items_delete(self):
        """
        Test deleting an item.
        """
        # first create an item
        self._create_item_status()
        payload = {
            "name": "Macbook Air",
            "type": "TRADE",
            "quantity": "1",
            "price": "",
            "description": "Lightweight lappy.",
            "reason": "",
            "is_draft": "y",
            "uuid": str(uuid.uuid4())
        }

        request = Request({}, method='POST', body=json.dumps(payload))
        request.registry = self.config.registry

        response = items(request)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(DBSession.query(Item).count(), 1)

        # try retrieving the newly added item
        item = DBSession.query(Item).first()

        # now send a delete request
        request.method = 'DELETE'
        request.matchdict = {'id': item.id}
        request.body = None
        items(request)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(DBSession.query(Item).count(), 0)
Пример #3
0
    def test_items_delete(self):
        """
        Test deleting an item.
        """
        # first create an item
        self._create_item_status()
        payload = {"name": "Macbook Air", "type": "TRADE", "quantity": "1",
                   "price": "", "description": "Lightweight lappy.",
                   "reason": "", "is_draft": "y", "uuid": str(uuid.uuid4())}

        request = Request({}, method='POST', body=json.dumps(payload))
        request.registry = self.config.registry

        response = items(request)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(DBSession.query(Item).count(), 1)

        # try retrieving the newly added item
        item = DBSession.query(Item).first()

        # now send a delete request
        request.method = 'DELETE'
        request.matchdict = {'id': item.id}
        request.body = None
        items(request)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(DBSession.query(Item).count(), 0)
Пример #4
0
def test_request_properties():
    root_request = Request({}, headers={"X-Some-Special-Header": "foobar"})
    # this is a slightly baroque mechanism to make sure that the request is
    # internally consistent for all test environments
    root_request.body = '{"myKey": 42}'.encode()
    assert '{"myKey": 42}' == root_request.text
    request = PyramidSwaggerRequest(root_request, {})
    assert {"myKey": 42} == request.body
    assert "foobar" == request.headers["X-Some-Special-Header"]
Пример #5
0
def test_request_properties():
    root_request = Request({}, headers={"X-Some-Special-Header": "foobar"})
    # this is a slightly baroque mechanism to make sure that the request is
    # internally consistent for all test environments
    root_request.body = '{"myKey": 42}'.encode()
    assert '{"myKey": 42}' == root_request.text
    request = PyramidSwaggerRequest(root_request, {})
    assert {"myKey": 42} == request.body
    assert "foobar" == request.headers["X-Some-Special-Header"]
Пример #6
0
def _extract_json_body(request: Request) -> object:
    json_body = {}
    if request.body == "":
        request.body = "{}"
    try:
        json_body = request.json_body
    except (ValueError, TypeError) as err:
        error = error_entry("body", None, "Invalid JSON request body".format(err))
        request.errors.append(error)
    return json_body
Пример #7
0
def _extract_json_body(request: Request) -> object:
    json_body = {}
    if request.body == '':
        request.body = '{}'
    try:
        json_body = request.json_body
    except (ValueError, TypeError) as err:
        error = error_entry('body', None,
                            'Invalid JSON request body'.format(err))
        request.errors.append(error)
    return json_body
Пример #8
0
def _extract_json_body(request: Request) -> object:
    json_body = {}
    if request.body == '':
        request.body = '{}'
    try:
        json_body = request.json_body
    except (ValueError, TypeError) as err:
        error = error_entry('body', None,
                            'Invalid JSON request body'.format(err))
        request.errors.append(error)
    return json_body
Пример #9
0
    def test_items_put(self):
        """
        Test updating an item.
        """
        self._create_item_status()

        payload = {
            "name": "Macbook Air",
            "type": "TRADE",
            "quantity": "1",
            "price": "",
            "description": "Lightweight lappy.",
            "reason": "",
            "is_draft": "y",
            "uuid": str(uuid.uuid4())
        }

        request = Request({}, method='POST', body=json.dumps(payload))
        request.registry = self.config.registry

        # make the request
        items(request)

        # try retrieving the newly added item
        item = DBSession.query(Item).first()
        self.failUnless(item)

        payload = {
            "name": "Macbook Pro",
            "type": "SALE",
            "quantity": "5",
            "price": "200.00",
            "description": "Lightweight lappy.",
            "reason": "",
            "is_draft": "n",
            "id": item.id
        }

        request.matchdict = {'id': item.id}
        request.method = 'PUT'
        request.body = json.dumps(payload)

        # make the request again
        response = items(request)
        self.assertEqual(response.status_code, 200)

        # reload item
        item = DBSession.query(Item).filter_by(id=item.id).first()
        self.assertEqual(item.name, payload['name'])
        self.assertEqual(item.type, payload['type'])
        self.assertEqual(item.quantity, int(payload['quantity']))
        self.assertEqual(str(item.price), payload['price'])
        self.assertEqual(item.status_id, self.draft_status.id)
Пример #10
0
    def test_create(self):
        from papyrus.protocol import Protocol
        from pyramid.request import Request
        from pyramid.response import Response

        engine = self._get_engine()
        Session = self._get_session(engine)
        MappedClass = self._get_mapped_class()

        class MockSession(object):
            def add(self, o):
                Session.add(o)
            def flush(self):
                pass

        # a before_update callback
        def before_create(request, feature, obj):
            if not hasattr(request, '_log'):
                request._log = []
            request._log.append(dict(feature=feature, obj=obj))

        proto = Protocol(MockSession, MappedClass, "geom",
                         before_create=before_create)

        # we need an actual Request object here, for body to do its job
        request = Request({})
        request.method = 'POST'
        request.body = '{"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {"text": "foo"}, "geometry": {"type": "Point", "coordinates": [45, 5]}}, {"type": "Feature", "properties": {"text": "foo"}, "geometry": {"type": "Point", "coordinates": [45, 5]}}]}'
        proto.create(request)
        self.assertEqual(len(request.response_callbacks), 1)
        self.assertEqual(len(Session.new), 2)
        for obj in Session.new:
            self.assertEqual(obj.text, 'foo')
            self.assertEqual(obj.geom.shape.x, 45)
            self.assertEqual(obj.geom.shape.y, 5)
        Session.rollback()

        # test before_create
        self.assertTrue(hasattr(request, '_log'))
        self.assertEqual(len(request._log), 2)
        self.assertEqual(request._log[0]['feature'].properties['text'], 'foo')
        self.assertEqual(request._log[0]['obj'], None)
        self.assertEqual(request._log[1]['feature'].properties['text'], 'foo')
        self.assertEqual(request._log[1]['obj'], None)

        # test response status
        response = Response(status_int=400)
        request._process_response_callbacks(response)
        self.assertEqual(response.status_int, 201)
Пример #11
0
    def test_create_badrequest(self):
        from papyrus.protocol import Protocol
        from pyramid.request import Request

        engine = self._get_engine()
        Session = self._get_session(engine)
        MappedClass = self._get_mapped_class()

        proto = Protocol(Session, MappedClass, "geom")
        # we need an actual Request object here, for body to do its job
        request = Request({})
        request.method = 'POST'
        request.body = '{"type": "Feature", "properties": {"text": "foo"}, "geometry": {"type": "Point", "coordinates": [45, 5]}}'
        response = proto.create(request)
        self.assertEqual(response.status_int, 400)
Пример #12
0
    def test_update_forbidden(self):
        from papyrus.protocol import Protocol
        from pyramid.request import Request

        engine = self._get_engine()
        Session = self._get_session(engine)
        MappedClass = self._get_mapped_class()

        proto = Protocol(Session, MappedClass, "geom", readonly=True)
        # we need an actual Request object here, for body to do its job
        request = Request({})
        request.method = 'PUT'
        request.body = '{"type": "Feature", "id": 1, "properties": {"text": "foo"}, "geometry": {"type": "Point", "coordinates": [45, 5]}}'
        response = proto.update(request, 1)
        self.assertTrue(response.headers.get('Allow') == "GET, HEAD")
        self.assertEqual(response.status_int, 405)
Пример #13
0
    def test_create_empty(self):
        from papyrus.protocol import Protocol
        from pyramid.request import Request
        from pyramid.response import Response

        engine = self._get_engine()
        Session = self._get_session(engine)
        MappedClass = self._get_mapped_class()

        proto = Protocol(Session, MappedClass, "geom")

        # we need an actual Request object here, for body to do its job
        request = Request({})
        request.method = 'POST'
        request.body = '{"type": "FeatureCollection", "features": []}'
        resp = proto.create(request)
        self.assertEqual(resp, None)
Пример #14
0
    def test_update_badrequest(self):
        from papyrus.protocol import Protocol
        from pyramid.request import Request

        # a mock session specific to this test
        class MockSession(object):
            def query(self, mapped_class):
                return {'a': {}}

        proto = Protocol(MockSession, self._get_mapped_class(), "geom")

        # we need an actual Request object here, for body to do its job
        request = Request({})
        request.method = 'PUT'
        request.body = '{"type": "Point", "coordinates": [45, 5]}'
        response = proto.update(request, 'a')
        self.assertEqual(response.status_int, 400)
Пример #15
0
    def test_update(self):
        from papyrus.protocol import Protocol
        from geojson import Feature
        from pyramid.request import Request
        from pyramid.response import Response
        from geoalchemy import WKBSpatialElement

        MappedClass = self._get_mapped_class()

        # a mock session specific to this test
        class MockSession(object):
            def query(self, mapped_class):
                return {'a': MappedClass(Feature(id='a'))}
            def flush(self):
                pass

        # a before_update callback
        def before_update(request, feature, obj):
            request._log = dict(feature=feature, obj=obj)

        proto = Protocol(MockSession, MappedClass, "geom",
                         before_update=before_update)

        # we need an actual Request object here, for body to do its job
        request = Request({})
        request.method = 'PUT'
        request.body = '{"type": "Feature", "id": "a", "properties": {"text": "foo"}, "geometry": {"type": "Point", "coordinates": [45, 5]}}'

        obj = proto.update(request, "a")

        self.assertEqual(len(request.response_callbacks), 1)
        self.assertTrue(isinstance(obj, MappedClass))
        self.assertTrue(isinstance(obj.geom, WKBSpatialElement))
        self.assertEqual(obj.text, "foo")

        # test before_update
        self.assertTrue(hasattr(request, '_log'))
        self.assertEqual(request._log["feature"].id, 'a')
        self.assertEqual(request._log["feature"].properties['text'], 'foo')
        self.assertTrue(isinstance(request._log["obj"], MappedClass))

        # test response status
        response = Response(status_int=400)
        request._process_response_callbacks(response)
        self.assertEqual(response.status_int, 201)
Пример #16
0
    def test_update_notfound(self):
        from papyrus.protocol import Protocol
        from pyramid.request import Request

        engine = self._get_engine()
        Session = self._get_session(engine)
        MappedClass = self._get_mapped_class()

        # a mock session specific to this test
        class MockSession(object):
            def query(self, mapped_class):
                return {}
        proto = Protocol(MockSession, MappedClass, "geom")
        # we need an actual Request object here, for body to do its job
        request = Request({})
        request.method = 'PUT'
        request.body = '{"type": "Feature", "id": 1, "properties": {"text": "foo"}, "geometry": {"type": "Point", "coordinates": [45, 5]}}'
        response = proto.update(request, 1)
        self.assertEqual(response.status_int, 404)
Пример #17
0
    def test_items_put(self):
        """
        Test updating an item.
        """
        self._create_item_status()

        payload = {"name": "Macbook Air", "type": "TRADE", "quantity": "1",
                   "price": "", "description": "Lightweight lappy.",
                   "reason": "", "is_draft": "y", "uuid": str(uuid.uuid4())}

        request = Request({}, method='POST', body=json.dumps(payload))
        request.registry = self.config.registry

        # make the request
        items(request)

        # try retrieving the newly added item
        item = DBSession.query(Item).first()
        self.failUnless(item)

        payload = {"name": "Macbook Pro", "type": "SALE", "quantity": "5",
                   "price": "200.00", "description": "Lightweight lappy.",
                   "reason": "", "is_draft": "n", "id": item.id}

        request.matchdict = {'id': item.id}
        request.method = 'PUT'
        request.body = json.dumps(payload)

        # make the request again
        response = items(request)
        self.assertEqual(response.status_code, 200)

        # reload item
        item = DBSession.query(Item).filter_by(id=item.id).first()
        self.assertEqual(item.name, payload['name'])
        self.assertEqual(item.type, payload['type'])
        self.assertEqual(item.quantity, int(payload['quantity']))
        self.assertEqual(str(item.price), payload['price'])
        self.assertEqual(item.status_id, self.draft_status.id)