def create(cls, response): return OpenAPIResponse( data=response.data, status_code=response._status_code, headers=response.headers, mimetype=response.mimetype, )
def create(cls, response: HTTPResponse) -> OpenAPIResponse: mimetype = response.headers.get("Content-Type", "text/html") return OpenAPIResponse( data=response.body.decode("utf-8") if response.body else "", status_code=response.code, mimetype=mimetype, )
def create(cls, response): mimetype = response.headers.get('Content-Type') return OpenAPIResponse( data=response.raw, status_code=response.status_code, mimetype=mimetype, )
def create(self, response): return OpenAPIResponse( data=self._get_data(response), status_code=self._get_status_code(response), headers=self._get_header(response), mimetype=self._get_mimetype(response), )
def create(cls, response): mimetype = response["Content-Type"] return OpenAPIResponse( data=response.content, status_code=response.status_code, mimetype=mimetype, )
def wrap_response(response): """Wrap a tornado response as an open api response""" mimetype = response.headers.get('Content-Type') or 'application/json' return OpenAPIResponse( data=response.body, status_code=response.code, mimetype=mimetype, )
def create(cls: t.Type["PyramidOpenAPIResponseFactory"], response: Response) -> "OpenAPIResponse": """Create OpenAPIResponse from Pyramid Response.""" return OpenAPIResponse( data=response.body, status_code=response.status_code, mimetype=response.content_type, )
def create( cls, data, status_code=200, headers=None, mimetype='application/json'): return OpenAPIResponse( data=data, status_code=status_code, headers=headers or {}, mimetype=mimetype, )
def create(cls, response): mimetype = response.headers.get('Content-Type') headers = dict(response.headers) return OpenAPIResponse( data=response.content, status_code=response.status_code, headers=headers, mimetype=mimetype, )
def create(cls, response): mimetype = response["Content-Type"] headers = get_response_headers(response) return OpenAPIResponse( data=response.content, status_code=response.status_code, headers=headers.items(), mimetype=mimetype, )
def test_get_metadata_for_combine_archive_url(self): archive_filename = os.path.join( self.FIXTURES_DIR, 'Ciliberto-J-Cell-Biol-2003-morphogenesis-checkpoint-continuous.omex' ) with open(archive_filename, 'rb') as file: archive_url_content = file.read() archive_url = 'https://archive.combine.org' data = MultiDict([ ('url', archive_url), ('omexMetadataFormat', OmexMetadataInputFormat.rdfxml.value), ]) response = mock.Mock( raise_for_status=lambda: None, content=archive_url_content, ) endpoint = '/combine/metadata/biosimulations' with mock.patch('requests.get', return_value=response): with app.app.app.test_client() as client: response = client.post(endpoint, data=data, content_type='multipart/form-data') self.assertEqual(response.status_code, 200, response.json) metadata = response.json sed_output_specs_filename = os.path.join( self.FIXTURES_DIR, 'Ciliberto-J-Cell-Biol-2003-morphogenesis-checkpoint-continuous.md.json' ) with open(sed_output_specs_filename, 'r') as file: expected_metadata = json.load(file) self.assertEqual(metadata, expected_metadata, metadata) # validate request and response if hasattr(self, "request_validator"): request = OpenAPIRequest( full_url_pattern= 'https://127.0.0.1/combine/metadata/biosimulations', method='post', body={ 'url': archive_url, 'omexMetadataFormat': OmexMetadataInputFormat.rdfxml.value, }, mimetype='multipart/form-data', parameters=RequestParameters(), ) result = self.request_validator.validate(request) result.raise_for_errors() response = OpenAPIResponse(data=json.dumps(expected_metadata), status_code=200, mimetype='application/json') result = self.response_validator.validate(request, response) result.raise_for_errors()
def test_response(self) -> None: tornado_request = HTTPRequest(url="http://example.com") tornado_response = HTTPResponse(request=tornado_request, code=200) expected = OpenAPIResponse( data=b"", status_code=200, mimetype="text/html", ) openapi_response = TornadoResponseFactory.create(tornado_response) self.assertEqual(attr.asdict(expected), attr.asdict(openapi_response))
def create(cls, data, status_code=200, headers=None, mimetype="application/json"): headers = Headers(headers or {}) return OpenAPIResponse( data=data, status_code=status_code, headers=headers, mimetype=mimetype, )
def test_validate_is_valid(self): archive_filename = os.path.join(self.FIXTURES_DIR, self.TEST_CASE + '.omex') fid = open(archive_filename, 'rb') data = MultiDict([ ('file', fid), ('omexMetadataFormat', OmexMetadataInputFormat.rdfxml.value), ('omexMetadataSchema', OmexMetadataSchema.biosimulations.value), ('validateSedmlModels', False), ]) endpoint = '/combine/validate' with app.app.app.test_client() as client: response = client.post(endpoint, data=data, content_type="multipart/form-data") fid.close() self.assertEqual(response.status_code, 200, response.json) validation_report = response.json validation_report.pop('warnings') self.assertEqual(validation_report, { "_type": "ValidationReport", "status": "warnings" }) # validate request and response if hasattr(self, "request_validator"): with open(archive_filename, 'rb') as file: file_content = file.read() request = OpenAPIRequest( full_url_pattern='https://127.0.0.1/combine/validate', method='post', body={ 'file': file_content, 'omexMetadataFormat': OmexMetadataInputFormat.rdfxml.value, 'omexMetadataSchema': OmexMetadataSchema.biosimulations.value, }, mimetype='multipart/form-data', parameters=RequestParameters(), ) result = self.request_validator.validate(request) result.raise_for_errors() response = OpenAPIResponse(data=json.dumps(validation_report), status_code=200, mimetype='application/json') result = self.response_validator.validate(request, response) result.raise_for_errors()
def create(cls, response): status_code = int(response.status[:3]) mimetype = '' if response.content_type: mimetype = response.content_type.partition(";")[0] else: mimetype = response.options.default_media_type return OpenAPIResponse( data=response.body, status_code=status_code, mimetype=mimetype, )
def create_and_validate_response(request, response): """ Helper function to create OpenAPIResponse and validate it :param request: OpenAPIRequest :param response: API response :return: - result: result of response validation """ response = OpenAPIResponse(data=response.content, status_code=response.status_code, mimetype='application/json') validator = ResponseValidator(spec) result = validator.validate(request, response) return result
def test_get_file_in_combine_archive_url(self): archive_filename = os.path.join( self.FIXTURES_DIR, 'Ciliberto-J-Cell-Biol-2003-morphogenesis-checkpoint-continuous.omex' ) with open(archive_filename, 'rb') as file: archive_url_content = file.read() archive_url = 'https://archive.combine.org' resolve_archive_response = mock.Mock( raise_for_status=lambda: None, content=archive_url_content, ) endpoint = '/combine/file?url={}&location={}'.format( urllib.parse.quote(archive_url), urllib.parse.quote('Figure1.jpg'), ) with mock.patch('requests.get', return_value=resolve_archive_response): with app.app.app.test_client() as client: response = client.get(endpoint) self.assertEqual(response.status_code, 200, response.json) image_filename = os.path.join(self.temp_dirname, 'image') with open(image_filename, 'wb') as file: file.write(response.data) self.assertEqual(imghdr.what(image_filename), 'jpeg') # validate request and response if hasattr(self, "request_validator"): request = OpenAPIRequest( full_url_pattern='https://127.0.0.1/combine/file', method='get', body={ 'url': archive_url, 'location': 'Figure1.jpg', }, mimetype='multipart/form-data', parameters=RequestParameters(url=archive_url, location='Figure1.jpg'), ) result = self.request_validator.validate(request) result.raise_for_errors() response = OpenAPIResponse(data=response.data, status_code=200, mimetype='image/jpeg') result = self.response_validator.validate(request, response) result.raise_for_errors()
def create(cls, response): status_code = int(response.status[:3]) mimetype = '' if response.content_type: mimetype = response.content_type.partition(";")[0] else: mimetype = response.options.default_media_type data = get_response_text(response) return OpenAPIResponse( data=data, status_code=status_code, headers=response.headers, mimetype=mimetype, )
def test_get_file_in_combine_archive_error_handling(self): endpoint = '/combine/file?url={}&location={}'.format( urllib.parse.quote('x'), urllib.parse.quote('Figure1.jpg'), ) with app.app.app.test_client() as client: response = client.get(endpoint) self.assertEqual(response.status_code, 400, response.json) self.assertTrue(response.json['title'].startswith( 'COMBINE/OMEX archive could not be loaded')) if hasattr(self, "response_validator"): request = OpenAPIRequest( full_url_pattern='https://127.0.0.1/combine/file', method='get', mimetype=None, parameters=RequestParameters(url='x', location='Figure1.jpg'), ) response = OpenAPIResponse(data=json.dumps(response.json), status_code=400, mimetype='image/jpeg') result = self.response_validator.validate(request, response) result.raise_for_errors() archive_filename = os.path.join( self.FIXTURES_DIR, 'Ciliberto-J-Cell-Biol-2003-morphogenesis-checkpoint-continuous.omex' ) with open(archive_filename, 'rb') as file: archive_url_content = file.read() archive_url = 'https://archive.combine.org' resolve_archive_response = mock.Mock( raise_for_status=lambda: None, content=archive_url_content, ) endpoint = '/combine/file?url={}&location={}'.format( urllib.parse.quote(archive_url), urllib.parse.quote('undefined'), ) with mock.patch('requests.get', return_value=resolve_archive_response): with app.app.app.test_client() as client: response = client.get(endpoint) self.assertEqual(response.status_code, 400, response.json) self.assertIn('not a valid location', response.json['title'])
def test_get_metadata_for_combine_archive_error_handling(self): endpoint = '/combine/metadata/biosimulations' data = MultiDict([ ('omexMetadataFormat', OmexMetadataInputFormat.rdfxml.value), ]) with app.app.app.test_client() as client: response = client.post(endpoint, data=data, content_type='multipart/form-data') self.assertEqual(response.status_code, 400, response.json) self.assertIn('must be used', response.json['title']) if hasattr(self, "response_validator"): request = OpenAPIRequest( full_url_pattern= 'https://127.0.0.1/combine/metadata/biosimulations', method='post', body={ 'url': 'x', 'omexMetadataFormat': OmexMetadataInputFormat.rdfxml.value, }, mimetype=None, parameters=RequestParameters(), ) response = OpenAPIResponse(data=json.dumps(response.json), status_code=400, mimetype='application/json') result = self.response_validator.validate(request, response) result.raise_for_errors() archive_filename = os.path.join(self.FIXTURES_DIR, 'invalid-metadata.omex') fid = open(archive_filename, 'rb') data = MultiDict([ ('file', fid), ('omexMetadataFormat', OmexMetadataInputFormat.rdfxml.value), ]) with app.app.app.test_client() as client: response = client.post(endpoint, data=data, content_type="multipart/form-data") self.assertEqual(response.status_code, 400, response.json) self.assertIn('is not valid', response.json['title']) fid.close()
def test_get_metadata_for_combine_archive_file_as_rdf_triples(self): archive_filename = os.path.join( self.FIXTURES_DIR, 'Ciliberto-J-Cell-Biol-2003-morphogenesis-checkpoint-continuous.omex' ) fid = open(archive_filename, 'rb') data = MultiDict([ ('file', fid), ('omexMetadataFormat', OmexMetadataInputFormat.rdfxml.value), ]) endpoint = '/combine/metadata/rdf' with app.app.app.test_client() as client: response = client.post(endpoint, data=data, content_type="multipart/form-data") self.assertEqual(response.status_code, 200, response.json) metadata = response.json self.assertEqual( metadata[0], { '_type': 'RdfTriple', 'subject': { '_type': 'RdfUriNode', 'value': 'http://omex-library.org/Ciliberto-J-Cell-Biol-2003-morphogenesis-checkpoint-continuous.omex', }, 'predicate': { '_type': 'RdfUriNode', 'value': 'http://purl.org/dc/elements/1.1/title', }, 'object': { '_type': 'RdfLiteralNode', 'value': 'Morphogenesis checkpoint in budding yeast (continuous) (Ciliberto et al., Journal Cell Biology, 2003)', } }) fid.close() # validate request and response if hasattr(self, "request_validator"): with open(archive_filename, 'rb') as file: file_content = file.read() request = OpenAPIRequest( full_url_pattern='https://127.0.0.1/combine/metadata/rdf', method='post', body={ 'file': file_content, 'omexMetadataFormat': OmexMetadataInputFormat.rdfxml.value, }, mimetype='multipart/form-data', parameters=RequestParameters(), ) result = self.request_validator.validate(request) result.raise_for_errors() response = OpenAPIResponse(data=json.dumps(metadata), status_code=200, mimetype='application/json') result = self.response_validator.validate(request, response) result.raise_for_errors()
def test_get_manifest_for_combine_archive_error_handling(self): endpoint = '/combine/manifest' data = MultiDict([ ('url', 'x'), ]) with app.app.app.test_client() as client: response = client.post(endpoint, data=data, content_type="multipart/form-data") self.assertEqual(response.status_code, 400, response.json) self.assertTrue( response.json['title'].startswith('File could not be loaded from')) if hasattr(self, "response_validator"): request = OpenAPIRequest( full_url_pattern='https://127.0.0.1/combine/manifest', method='post', body={ 'url': 'x', }, mimetype=None, parameters=RequestParameters(), ) response = OpenAPIResponse(data=json.dumps(response.json), status_code=400, mimetype='application/json') result = self.response_validator.validate(request, response) result.raise_for_errors() response = mock.Mock( raise_for_status=lambda: None, content=b'.', ) with mock.patch('requests.get', return_value=response): with app.app.app.test_client() as client: response = client.post(endpoint, data=data, content_type="multipart/form-data") self.assertEqual(response.status_code, 400, response.json) self.assertIn( 'File is not a valid manifest or a COMBINE/OMEX which contains a valid manifest', response.json['title']) archive_filename = os.path.join(self.FIXTURES_DIR, 'no-manifest.omex') with open(archive_filename, 'rb') as file: archive_url_content = file.read() response = mock.Mock( raise_for_status=lambda: None, content=archive_url_content, ) with mock.patch('requests.get', return_value=response): with app.app.app.test_client() as client: response = client.post(endpoint, data=data, content_type="multipart/form-data") self.assertEqual(response.status_code, 400, response.json) self.assertIn('does not contain a manifest', response.json['title']) archive_filename = os.path.join(self.FIXTURES_DIR, 'bad-manifest.omex') with open(archive_filename, 'rb') as file: archive_url_content = file.read() response = mock.Mock( raise_for_status=lambda: None, content=archive_url_content, ) with mock.patch('requests.get', return_value=response): with app.app.app.test_client() as client: response = client.post(endpoint, data=data, content_type="multipart/form-data") self.assertEqual(response.status_code, 400, response.json) self.assertIn( 'File is not a valid manifest or a COMBINE/OMEX which contains a valid manifest', response.json['title'])
def test_get_parameters_variables_for_simulation_from_file(self): endpoint = '/sed-ml/get-parameters-variables-for-simulation' model_filename = os.path.abspath( os.path.join(self.FIXTURES_DIR, 'Chaouiya-BMC-Syst-Biol-2013-EGF-TNFa-signaling.xml')) model_fid = open(model_filename, 'rb') data = MultiDict([ ('modelLanguage', 'urn:sedml:language:sbml'), ('modelingFramework', 'SBO_0000547'), ('simulationType', 'SedUniformTimeCourseSimulation'), ('simulationAlgorithm', 'KISAO_0000450'), ('modelFile', model_fid), ]) with app.app.app.test_client() as client: response = client.post(endpoint, data=data, content_type="multipart/form-data") model_fid.close() self.assertEqual(response.status_code, 200, response.json) sed_doc = response.json vars = [ data_gen['variables'][0] for data_gen in sed_doc['dataGenerators'] ] self.assertEqual(vars[0]['id'], 'time') self.assertEqual(vars[0]['name'], 'Time') self.assertEqual(vars[0]['symbol'], Symbol.time) self.assertNotIn('target', vars[0]) self.assertEqual(vars[-1]['id'], 'level_species_nik') self.assertEqual(vars[-1]['name'], 'Level of species "nik"') self.assertNotIn('symbol', vars[-1]) vars[-1]['target']['namespaces'].sort(key=lambda ns: ns['prefix']) self.assertEqual( vars[-1]['target'], { "_type": "SedTarget", "value": "/sbml:sbml/sbml:model/qual:listOfQualitativeSpecies/qual:qualitativeSpecies[@qual:id='nik']", "namespaces": [ { "_type": "Namespace", "prefix": "qual", "uri": "http://www.sbml.org/sbml/level3/version1/qual/version1" }, { "_type": "Namespace", "prefix": "sbml", "uri": "http://www.sbml.org/sbml/level3/version1/core" }, ] }, ) # validate request and response if hasattr(self, "request_validator"): with open(model_filename, 'rb') as file: model_content = file.read() request = OpenAPIRequest( full_url_pattern='https://127.0.0.1/' + endpoint, method='post', body={ 'modelLanguage': 'urn:sedml:language:sbml', 'modelingFramework': 'SBO_0000547', 'simulationType': 'SedUniformTimeCourseSimulation', 'simulationAlgorithm': 'KISAO_0000029', 'modelFile': model_content, }, mimetype='multipart/form-data', parameters=RequestParameters(), ) result = self.request_validator.validate(request) result.raise_for_errors() response = OpenAPIResponse(data=json.dumps(sed_doc), status_code=200, mimetype='application/json') result = self.response_validator.validate(request, response) result.raise_for_errors()
def create(cls, response): return OpenAPIResponse( data=response.body, status_code=response.status_code, mimetype=response.headers.get("content-type"), )
def _bottle_response_to_openapi_response(resp: Response) -> OpenAPIResponse: return OpenAPIResponse( data=resp.body, status_code=resp.status_code, mimetype=_get_mimetype(resp.content_type) )
def test_get_manifest_for_combine_archive_url(self): archive_filename = os.path.join(self.FIXTURES_DIR, self.TEST_CASE + '.omex') with open(archive_filename, 'rb') as file: archive_url_content = file.read() archive_url = 'https://archive.combine.org' data = MultiDict([ ('url', archive_url), ]) response = mock.Mock( raise_for_status=lambda: None, content=archive_url_content, ) endpoint = '/combine/manifest' with mock.patch('requests.get', return_value=response): with app.app.app.test_client() as client: response = client.post(endpoint, data=data, content_type="multipart/form-data") self.assertEqual(response.status_code, 200, response.json) manifest = response.json expected_manifest = { '_type': 'CombineArchiveManifest', 'contents': [{ '_type': 'CombineArchiveManifestContent', 'format': 'http://identifiers.org/combine.specifications/sbml', 'location': { '_type': 'CombineArchiveManifestLocation', 'path': './Caravagna2010.xml', 'value': { '_type': 'CombineArchiveContentFile', 'filename': 'Caravagna2010.xml', }, }, 'master': False }, { '_type': 'CombineArchiveManifestContent', 'format': 'http://identifiers.org/combine.specifications/sed-ml', 'location': { '_type': 'CombineArchiveManifestLocation', 'path': './BIOMD0000000912_sim.sedml', 'value': { '_type': 'CombineArchiveContentFile', 'filename': 'BIOMD0000000912_sim.sedml', }, }, 'master': True }, { '_type': 'CombineArchiveManifestContent', 'format': 'http://identifiers.org/combine.specifications/omex', 'location': { '_type': 'CombineArchiveManifestLocation', 'path': '.', 'value': { '_type': 'CombineArchiveContentFile', 'filename': '.', }, }, 'master': False }, { '_type': 'CombineArchiveManifestContent', 'format': 'http://identifiers.org/combine.specifications/omex-metadata', 'location': { '_type': 'CombineArchiveManifestLocation', 'path': 'metadata.rdf', 'value': { '_type': 'CombineArchiveContentFile', 'filename': 'metadata.rdf', }, }, 'master': False }] } self.assertEqual(manifest, expected_manifest, manifest) # validate request and response if hasattr(self, "request_validator"): request = OpenAPIRequest( full_url_pattern='https://127.0.0.1/combine/manifest', method='post', body={ 'url': archive_url, }, mimetype='multipart/form-data', parameters=RequestParameters(), ) result = self.request_validator.validate(request) result.raise_for_errors() response = OpenAPIResponse(data=json.dumps(expected_manifest), status_code=200, mimetype='application/json') result = self.response_validator.validate(request, response) result.raise_for_errors()