def test_create_update(self): from papyrus.protocol import Protocol from pyramid.testing import DummyRequest 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 = DummyRequest({}) 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]}}]}' # NOQA 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)))
def test_post_getcaps_request(self): request = DummyRequest(post={}) request.body = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <GetCapabilities service="WPS" acceptVersions="1.0.0" language="en-CA"/>""" ows_req = OWSRequest(request) assert ows_req.request == 'getcapabilities' assert ows_req.service == 'wps'
def test_post_getcaps_request(self): request = DummyRequest(post={}) request.body = b"""<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <GetCapabilities service="WPS" acceptVersions="1.0.0" language="en-CA"/>""" ows_req = OWSRequest(request) assert ows_req.request == 'getcapabilities' assert ows_req.service == 'wps'
def test_create_update(self): from papyrus.protocol import Protocol from pyramid.testing import DummyRequest 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 = DummyRequest({}) 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)))
def test_post_execute_request(self): request = DummyRequest(post={}) request.body = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <wps:Execute service="WPS" version="1.0.0" xmlns:wps="http://www.opengis.net/wps/1.0.0" xmlns:ows="http://www.opengis.net/ows/1.1" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/wps/1.0.0/../wpsExecute_request.xsd"> <ows:Identifier>Buffer</ows:Identifier> <wps:DataInputs> <wps:Input> <ows:Identifier>InputPolygon</ows:Identifier> <ows:Title>Playground area</ows:Title> <wps:Reference xlink:href="http://foo.bar/some_WFS_request.xml"/> </wps:Input> <wps:Input> <ows:Identifier>BufferDistance</ows:Identifier> <ows:Title>Distance which people will walk to get to a playground.</ows:Title> <wps:Data> <wps:LiteralData>400</wps:LiteralData> </wps:Data> </wps:Input> </wps:DataInputs> <wps:ResponseForm> <wps:ResponseDocument storeExecuteResponse="true"> <wps:Output asReference="true"> <ows:Identifier>BufferedPolygon</ows:Identifier> <ows:Title>Area serviced by playground.</ows:Title> <ows:Abstract>Area within which most users of this playground will live.</ows:Abstract> </wps:Output> </wps:ResponseDocument> </wps:ResponseForm> </wps:Execute>""" ows_req = OWSRequest(request) assert ows_req.request == 'execute' assert ows_req.service == 'wps' assert ows_req.version == '1.0.0'
def _makeDummyRequest(self, request_data=None): from pyramid.testing import DummyRequest request = DummyRequest() request.matched_route = DummyRoute('JSON-RPC') if request_data is not None: request.body = json.dumps(request_data) request.content_length = len(request.body) return request
def test_post_describeprocess_request(self): request = DummyRequest(post={}) request.body = b"""<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <DescribeProcess service="WPS" version="1.0.0" language="en" xmlns:ows="http://www.opengis.net/ows/1.1"> <ows:Identifier>intersection</ows:Identifier> <ows:Identifier>union</ows:Identifier> </DescribeProcess>""" ows_req = OWSRequest(request) assert ows_req.request == 'describeprocess' assert ows_req.service == 'wps' assert ows_req.version == '1.0.0'
def test_post_describeprocess_request(self): request = DummyRequest(post={}) request.body = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <DescribeProcess service="WPS" version="1.0.0" language="en" xmlns:ows="http://www.opengis.net/ows/1.1"> <ows:Identifier>intersection</ows:Identifier> <ows:Identifier>union</ows:Identifier> </DescribeProcess>""" ows_req = OWSRequest(request) assert ows_req.request == 'describeprocess' assert ows_req.service == 'wps' assert ows_req.version == '1.0.0'
def test_create(self): from papyrus.protocol import Protocol from pyramid.testing import DummyRequest 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 = DummyRequest({}) 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(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 self.assertEqual(request.response.status_int, 201)
def test_create_badrequest(self): from papyrus.protocol import Protocol from pyramid.testing import DummyRequest 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 = DummyRequest({}) 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)
def test_create_badrequest(self): from papyrus.protocol import Protocol from pyramid.testing import DummyRequest 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 = DummyRequest({}) request.method = 'POST' request.body = '{"type": "Feature", "properties": {"text": "foo"}, "geometry": {"type": "Point", "coordinates": [45, 5]}}' # NOQA response = proto.create(request) self.assertEqual(response.status_int, 400)
def test_create_empty(self): from papyrus.protocol import Protocol from pyramid.testing import DummyRequest 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 = DummyRequest({}) request.method = 'POST' request.body = '{"type": "FeatureCollection", "features": []}' resp = proto.create(request) self.assertEqual(resp, None)
def test_update_forbidden(self): from papyrus.protocol import Protocol from pyramid.testing import DummyRequest 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 = DummyRequest({}) request.method = 'PUT' request.body = '{"type": "Feature", "id": 1, "properties": {"text": "foo"}, "geometry": {"type": "Point", "coordinates": [45, 5]}}' # NOQA response = proto.update(request, 1) self.assertTrue(response.headers.get('Allow') == "GET, HEAD") self.assertEqual(response.status_int, 405)
def test_update_forbidden(self): from papyrus.protocol import Protocol from pyramid.testing import DummyRequest 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 = DummyRequest({}) 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)
def test_update_badrequest(self): from papyrus.protocol import Protocol from pyramid.testing import DummyRequest # 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 = DummyRequest({}) request.method = 'PUT' request.body = '{"type": "Point", "coordinates": [45, 5]}' response = proto.update(request, 'a') self.assertEqual(response.status_int, 400)
def test_update_notfound(self): from papyrus.protocol import Protocol from pyramid.testing import DummyRequest 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 = DummyRequest({}) request.method = 'PUT' request.body = '{"type": "Feature", "id": 1, "properties": {"text": "foo"}, "geometry": {"type": "Point", "coordinates": [45, 5]}}' # NOQA response = proto.update(request, 1) self.assertEqual(response.status_int, 404)
def test_pattern_clearer_JSON(self): """ This method tests the JSON clearer view linked to the pattern input page. The expected result of this test is for the correct JSON response to be retrieved. """ # Setup request = DummyRequest(route='/pattern_clearer.json') input = create_input_pattern() request.body = json.dumps(input) request.content_type = "application/json" request.json_body = input request.session["pattern"] = input response = pattern_input_clearer_JSON(request) # Assert that the pattern has been removed from the session assert "pattern" not in response.keys()
def test_create(self): from papyrus.protocol import Protocol from pyramid.testing import DummyRequest 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 = DummyRequest({}) 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]}}]}' # NOQA proto.create(request) 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 self.assertEqual(request.response.status_int, 201)
def test_update(self): from papyrus.protocol import Protocol from geojson import Feature from pyramid.testing import DummyRequest from pyramid.response import Response from geoalchemy2.elements import WKBElement 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 = DummyRequest({}) request.method = 'PUT' request.body = '{"type": "Feature", "id": "a", "properties": {"text": "foo"}, "geometry": {"type": "Point", "coordinates": [45, 5]}}' obj = proto.update(request, "a") self.assertTrue(isinstance(obj, MappedClass)) self.assertTrue(isinstance(obj.geom, WKBElement)) 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 self.assertEqual(request.response.status_int, 201)
def mock_request( request_path_query="", # type: str method="GET", # type: str params=None, # type: Optional[Dict[str, str]] body="", # type: Union[str, JSON] content_type=None, # type: Optional[str] headers=None, # type: Optional[AnyHeadersType] cookies=None, # type: Optional[AnyCookiesType] settings=None, # type: SettingsType ): # type: (...) -> Request """ Generates a fake request with provided arguments. Can be employed by functions that expect a request object as input to retrieve details such as body content, the request path, or internal settings, but that no actual request needs to be accomplished. """ parts = request_path_query.split("?") path = parts[0] query = dict() if len(parts) > 1 and parts[1]: for part in parts[1].split("&"): kv = part.split( "=") # handle trailing keyword query arguments without values if kv[0]: # handle invalid keyword missing query[kv[0]] = kv[1] if len(kv) > 1 else None elif params: query = params request = DummyRequest(path=path, params=query) request.path_qs = request_path_query request.method = method request.content_type = content_type request.headers = headers or {} request.cookies = cookies or {} request.matched_route = None # cornice method if content_type: request.headers["Content-Type"] = content_type request.body = body try: if body: # set missing DummyRequest.json attribute request.json = json_pkg.loads(body) # type: ignore except (TypeError, ValueError): pass request.registry.settings = settings or {} return request # noqa # fake type of what is normally expected just to avoid many 'noqa'
def view_request_test(request): """ View method to test the calculation using a saved request. Calls view_callback :param request: HTTP Request object :type request: pyramid.request.Request :return: Dictionary of values to be used in the template """ id = request.matchdict['id'] req = DBSession.query(QuoteRequest).filter_by(id=id).first() fakereq = DummyRequest() fakereq.body = req.json.encode('utf-8') response = view_callback(fakereq, save=False) response_data = response.body.decode('utf-8') response_data = prettify_json(response_data) return {'result': response_data}
def test_update(self): from papyrus.protocol import Protocol from geojson import Feature from pyramid.testing import DummyRequest from geoalchemy2.elements import WKBElement 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 = DummyRequest({}) request.method = 'PUT' request.body = '{"type": "Feature", "id": "a", "properties": {"text": "foo"}, "geometry": {"type": "Point", "coordinates": [45, 5]}}' # NOQA obj = proto.update(request, "a") self.assertTrue(isinstance(obj, MappedClass)) self.assertTrue(isinstance(obj.geom, WKBElement)) 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 self.assertEqual(request.response.status_int, 201)
def test_post_execute_request(self): request = DummyRequest(post={}) request.body = b"""<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <wps:Execute service="WPS" version="1.0.0" xmlns:wps="http://www.opengis.net/wps/1.0.0" xmlns:ows="http://www.opengis.net/ows/1.1" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/wps/1.0.0/../wpsExecute_request.xsd"> <ows:Identifier>Buffer</ows:Identifier> <wps:DataInputs> <wps:Input> <ows:Identifier>InputPolygon</ows:Identifier> <ows:Title>Playground area</ows:Title> <wps:Reference xlink:href="http://foo.bar/some_WFS_request.xml"/> </wps:Input> <wps:Input> <ows:Identifier>BufferDistance</ows:Identifier> <ows:Title>Distance which people will walk to get to a playground.</ows:Title> <wps:Data> <wps:LiteralData>400</wps:LiteralData> </wps:Data> </wps:Input> </wps:DataInputs> <wps:ResponseForm> <wps:ResponseDocument storeExecuteResponse="true"> <wps:Output asReference="true"> <ows:Identifier>BufferedPolygon</ows:Identifier> <ows:Title>Area serviced by playground.</ows:Title> <ows:Abstract>Area within which most users of this playground will live.</ows:Abstract> </wps:Output> </wps:ResponseDocument> </wps:ResponseForm> </wps:Execute>""" ows_req = OWSRequest(request) assert ows_req.request == 'execute' assert ows_req.service == 'wps' assert ows_req.version == '1.0.0'
def test_pattern_input_receiver_JSON(self): """ This method tests the JSON receiver view linked to the pattern input page. The expected result of this test is for the correct JSON response to be retrieved. """ # Setup request = DummyRequest(route='/pattern_receiver.json') input = create_input_pattern() request.body = json.dumps(input) request.content_type = "application/json" request.json_body = input response = pattern_input_receiver_JSON(request) # Assert that there is a pattern in the session. assert request.session["pattern"] == input responseDict = response # Assert that the correct number of turns has been calculated and stored. assert responseDict["turns"] == 53 # Assert that the correct run time has been calculated and stored. assert responseDict["runtime"] == SLEEP_TIME * 53
def test_post_false_service(self): request = DummyRequest(post={}) request.body = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <GetCapabilities service="ATM" acceptVersions="1.0.0" language="en-CA"/>""" with pytest.raises(OWSInvalidParameterValue) as e_info: ows_req = OWSRequest(request)
def test_adds_body_error_if_json_invalid(self): request = DummyRequest() request.body = b'{wrong,"format"}' request.errors = Errors() validator(request, mock.Mock()) self.assertEqual('body', request.errors[0]['location'])
def _make_request(self, body): request = DummyRequest() request.body = body return request
def test_post_false_service(self): request = DummyRequest(post={}) request.body = b"""<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <GetCapabilities service="ATM" acceptVersions="1.0.0" language="en-CA"/>""" with pytest.raises(OWSInvalidParameterValue): OWSRequest(request)
def test_upload(): """ Reference: Resumable uploads over HTTP. Protocol specification http://www.grid.net.ru/nginx/resumable_uploads.en.html """ with tempfile.TemporaryDirectory() as tempdir: #Example 1: Request from client containing the first segment of the file # #POST /upload HTTP/1.1 #Host: example.com #Content-Length: 51201 #Content-Type: application/octet-stream #Content-Disposition: attachment; filename="big.TXT" #X-Content-Range: bytes 0-51200/511920 #Session-ID: 1111215056 # #<bytes 0-51200> #env = copy.copy(request_environ) #env.update({'REQUEST_METHOD': 'POST'}) request = DummyRequest(headers={ 'Content-Length': 51201, 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment; filename="big.TXT"', 'X-Content-Range': 'bytes 0-51200/511920', 'Session-ID': 1111215056, }) request.registry.settings = {'upload.path': tempdir} request.body = ('x' * 51201).encode('utf-8') # fake body content response = Upload(request).post() #Example 2: Response to a request containing first segment of a file # #HTTP/1.1 201 Created #Date: Thu, 02 Sep 2010 12:54:40 GMT #Content-Length: 14 #Connection: close #Range: 0-51200/511920 # #0-51200/511920 assert request.response.status_code == 201 assert response == '0-51200/511920' assert request.response.headers['Range'] == '0-51200/511920' # Simulate writing the middle of file with open(os.path.join(tempdir, '1111215056', 'big.TXT', '51200'), 'wb') as file: file.write(('z' * 409608).encode('utf-8')) #Example 3: Request from client containing the last segment of the file # #POST /upload HTTP/1.1 #Host: example.com #Content-Length: 51111 #Content-Type: application/octet-stream #Content-Disposition: attachment; filename="big.TXT" #X-Content-Range: bytes 460809-511919/511920 #Session-ID: 1111215056 # #<bytes 460809-511919> request = DummyRequest(headers={ 'Content-Length': 51111, 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment; filename="big.TXT"', 'X-Content-Range': 'bytes 460809-511919/511920', 'Session-ID': 1111215056, }) request.registry.settings = {'upload.path': tempdir} request.route_url = Mock(return_value='') request.body = ('y' * 51111).encode('utf-8') # fake body content response = Upload(request).post() #Example 4: Response to a request containing last segment of a file # #HTTP/1.1 200 OK #Date: Thu, 02 Sep 2010 12:54:43 GMT #Content-Type: text/html #Connection: close #Content-Length: 2270 # #<response body> assert response['files'][0]['name'] == 'big.TXT' assert response['files'][0]['size'] == 511920 with open(os.path.join(tempdir, 'big.TXT'), 'rb') as file: data = file.read() assert chr(data[0]) == 'x' assert chr(data[-1]) == 'y'