def create(cls, request): """ Create OpenAPIRequest from falcon Request and route params. """ method = request.method.lower() # gets deduced by path finder against spec path = {} # Support falcon-jsonify. body = (dumps(request.json) if getattr(request, "json", None) else request.bounded_stream.read()) mimetype = request.options.default_media_type if request.content_type: mimetype = request.content_type.partition(";")[0] query = ImmutableMultiDict(request.params.items()) parameters = RequestParameters( query=query, header=request.headers, cookie=request.cookies, path=path, ) return OpenAPIRequest( full_url_pattern=request.url, method=method, parameters=parameters, body=body, mimetype=mimetype, )
def create( cls, host_url, method, path, path_pattern=None, args=None, view_args=None, headers=None, cookies=None, data=None, mimetype="application/json", ): path_pattern = path_pattern or path path = view_args or {} query = ImmutableMultiDict(args or {}) header = Headers(headers or {}) cookie = ImmutableMultiDict(cookies or {}) parameters = RequestParameters( path=path, query=query, header=header, cookie=cookie, ) method = method.lower() body = data or "" full_url_pattern = urljoin(host_url, path_pattern) return OpenAPIRequest( full_url_pattern=full_url_pattern, method=method, parameters=parameters, body=body, mimetype=mimetype, )
def create(cls, request, default_when_empty={}): """ Create OpenAPIRequest from falcon Request and route params. """ default = default_when_empty method = request.method.lower() # gets deduced by path finder against spec path = {} media = get_request_media(request, default=default) # Support falcon-jsonify. body = ( dumps(getattr(request, "json", media)) ) mimetype = request.options.default_media_type if request.content_type: mimetype = request.content_type.partition(";")[0] query = ImmutableMultiDict(request.params.items()) parameters = RequestParameters( query=query, header=request.headers, cookie=request.cookies, path=path, ) url_pattern = request.prefix + request.path return OpenAPIRequest( full_url_pattern=url_pattern, method=method, parameters=parameters, body=body, mimetype=mimetype, )
def create(cls: t.Type["PyramidOpenAPIRequestFactory"], request: Request) -> "OpenAPIRequest": """Create OpenAPIRequest from Pyramid Request.""" method = request.method.lower() path_pattern = (request.matched_route.pattern if request.matched_route else request.path_info) # a path pattern is not normalized in pyramid so it may or may not # start with a leading /, so normalize it here path_pattern = path_pattern.lstrip("/") full_url_pattern = request.application_url + "/" + path_pattern parameters = RequestParameters( path=request.matchdict, query=request.GET, header=request.headers, cookie=request.cookies, ) return OpenAPIRequest( full_url_pattern=full_url_pattern, method=method, parameters=parameters, body=request.body, mimetype=request.content_type, )
async def create(cls, request): path_pattern = request["path"] for route in request.app.router.routes: match, _ = route.matches(request) if match == Match.FULL: path_pattern = route.path break host_url = f"{request.url.scheme}://{request.url.hostname}" if request.url.port: host_url = f"{host_url}:{request.url.port}" parameters = RequestParameters( path=request.path_params, query=request.query_params, header=dict(request.headers), cookie=request.cookies, ) return OpenAPIRequest( full_url_pattern=urljoin(host_url, path_pattern), method=request.method.lower(), parameters=parameters, body=await request.body(), mimetype=request.headers.get("content-type"), )
def create(cls, request): method = request.method.lower() if request.resolver_match is None: path_pattern = request.path else: route = cls.path_regex.sub(r'{\1}', request.resolver_match.route) path_pattern = '/' + route path = request.resolver_match and request.resolver_match.kwargs or {} headers = get_headers(request) parameters = RequestParameters( path=path, query=request.GET, header=headers.items(), cookie=request.COOKIES, ) current_scheme_host = get_current_scheme_host(request) full_url_pattern = urljoin(current_scheme_host, path_pattern) return OpenAPIRequest( full_url_pattern=full_url_pattern, method=method, parameters=parameters, body=request.body, mimetype=request.content_type, )
def create_and_validate_request(endpoint, method, payload='', params=[], headers=[]): """ Helper function to create OpenAPIRequest and validate it :param endpoint: API endpoint :param method: API request method :param payload: API request payload :param params: API request payload :param headers: API request headers :return: - request: OpenAPIRequest - request_result: result of request validation """ parameters = RequestParameters(query=ImmutableMultiDict(params), path=endpoint, header=headers) request = OpenAPIRequest( full_url_pattern=endpoint, method=method, parameters=parameters, body=payload, mimetype='application/json', ) validator = RequestValidator(spec) request_result = validator.validate(request) return request, request_result
def create(cls, request): method = request.method.lower() if request.resolver_match is None: path_pattern = request.path else: route = cls.path_regex.sub( r'{\1}', request.resolver_match.route) path_pattern = '/' + route path = request.resolver_match and request.resolver_match.kwargs or {} parameters = RequestParameters( path=path, query=request.GET, header=request.headers, cookie=request.COOKIES, ) return OpenAPIRequest( host_url=request._current_scheme_host, path=request.path, method=method, path_pattern=path_pattern, parameters=parameters, body=request.body, mimetype=request.content_type, )
def create(self, request): """ Create OpenAPIRequest from falcon Request and route params. """ method = request.method.lower() media = request.get_media(default_when_empty=self.default_when_empty) # Support falcon-jsonify. body = dumps(getattr(request, "json", media)) mimetype = request.options.default_media_type if request.content_type: mimetype = request.content_type.partition(";")[0] query = ImmutableMultiDict(list(request.params.items())) header = Headers(request.headers) # Path gets deduced by path finder against spec parameters = RequestParameters( query=query, header=header, cookie=request.cookies, ) url_pattern = request.prefix + request.path return OpenAPIRequest( full_url_pattern=url_pattern, method=method, parameters=parameters, body=body, mimetype=mimetype, )
def create(cls, host_url, method, path, path_pattern=None, args=None, view_args=None, headers=None, cookies=None, data=None, mimetype='application/json'): parameters = RequestParameters( path=view_args or {}, query=ImmutableMultiDict(args or []), header=headers or {}, cookie=cookies or {}, ) path_pattern = path_pattern or path method = method.lower() body = data or '' return OpenAPIRequest( host_url=host_url, path=path, path_pattern=path_pattern, method=method, parameters=parameters, body=body, mimetype=mimetype, )
def create( cls, request: Union[HTTPRequest, HTTPServerRequest]) -> OpenAPIRequest: if isinstance(request, HTTPRequest): if request.url: path, _, querystring = request.url.partition("?") query_arguments: ImmutableMultiDict[str, str] = ImmutableMultiDict( parse_qsl(querystring)) else: path = "" query_arguments = ImmutableMultiDict() else: if request.uri: path, _, _ = request.uri.partition("?") else: path = "" query_arguments = ImmutableMultiDict( itertools.chain( *[[(k, v.decode("utf-8")) for v in vs] for k, vs in request.query_arguments.items()])) return OpenAPIRequest( full_url_pattern=path, method=request.method.lower() if request.method else "get", parameters=RequestParameters(query=query_arguments, header=Headers( request.headers.get_all())), body=request.body.decode("utf-8") if request.body else "", mimetype=request.headers.get("Content-Type", "application/x-www-form-urlencoded"), )
def create(self, request): return OpenAPIRequest( full_url_pattern=self._get_full_url_pattern(request), method=self._get_method(request), parameters=self._get_parameters(request), body=self._get_body(request), mimetype=self._get_mimetype(request), )
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 wrap_request(request, spec): """Wrap a tornado request as an open api request""" # Extract cookie dict from cookie header cookie = SimpleCookie() cookie.load(request.headers.get("Set-Cookie", "")) cookies = {} for key, morsel in cookie.items(): cookies[key] = morsel.value # extract the path o = urlparse(request.url) # extract the best matching url # work around lack of support for path parameters which can contain slashes # https://github.com/OAI/OpenAPI-Specification/issues/892 url = None for path in spec["paths"]: if url: continue has_arg = "{" in path if has_arg: path = path[: path.index("{")] if path in o.path: u = o.path[o.path.index(path) :] if not has_arg and len(u) == len(path): url = u if has_arg and not u.endswith("/"): url = u[: len(path)] + r"foo" if url is None: raise ValueError(f"Could not find matching pattern for {o.path}") # gets deduced by path finder against spec path = {} # Order matters because all tornado requests # include Accept */* which does not necessarily match the content type mimetype = ( request.headers.get("Content-Type") or request.headers.get("Accept") or "application/json" ) parameters = RequestParameters( query=parse_qs(o.query), header=dict(request.headers), cookie=cookies, path=path, ) return OpenAPIRequest( full_url_pattern=url, method=request.method.lower(), parameters=parameters, body=request.body, mimetype=mimetype, )
def create(cls, request): """ Converts a requests request to an OpenAPI one Internally converts to a `PreparedRequest` first to parse the exact payload being sent """ if isinstance(request, Request): request = request.prepare() # Method method = request.method.lower() # Cookies cookie = {} if request._cookies is not None: # cookies are stored in a cookiejar object cookie = request._cookies.get_dict() # Preparing a request formats the URL with params, strip them out again o = urlparse(request.url) params = parse_qs(o.query) # extract the URL without query parameters url = o._replace(query=None).geturl() # gets deduced by path finder against spec path = {} # Order matters because all python requests issued from a session # include Accept */* which does not necessarily match the content type mimetype = request.headers.get('Content-Type') or \ request.headers.get('Accept') # Headers - request.headers is not an instance of dict # which is expected header = dict(request.headers) # Body # TODO: figure out if request._body_position is relevant body = request.body parameters = RequestParameters( query=ImmutableMultiDict(params), header=header, cookie=cookie, path=path, ) return OpenAPIRequest( full_url_pattern=url, method=method, parameters=parameters, body=body, mimetype=mimetype, )
def _bottle_request_to_openapi_request(req: Request) -> OpenAPIRequest: # TODO: The default JSON deserializer for the OpenAPI toolkit does not handle # bytes I/O or streams, it looks like it requires strings. Can we bolt in an # alternate deserializer to make this work better? return OpenAPIRequest( full_url_pattern=BOTTLE_PATH_PARAMETER_REGEX.sub(r'/{\1}', req.route.rule), method=req.method.lower(), parameters=_generate_request_parameters(req), body=req.body.read(), mimetype=_get_mimetype(req.content_type) )
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 test_http_request(self, opts) -> None: url, parameters = opts request_url = f"{url}?{urlencode(parameters)}" if url else "" tornado_request = HTTPRequest(method="GET", url=request_url) expected = OpenAPIRequest( full_url_pattern=url, method="get", parameters=RequestParameters(query=ImmutableMultiDict(parameters)), body="", mimetype="application/x-www-form-urlencoded", ) openapi_request = TornadoRequestFactory.create(tornado_request) self.assertEqual(attr.asdict(expected), attr.asdict(openapi_request))
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 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 create(cls, request): method = request.method.lower() if request.url_rule is None: path_pattern = request.path else: path_pattern = cls.path_regex.sub(r'{\1}', request.url_rule.rule) parameters = RequestParameters( path=request.view_args, query=request.args, header=request.headers, cookie=request.cookies, ) full_url_pattern = urljoin(request.host_url, path_pattern) return OpenAPIRequest( full_url_pattern=full_url_pattern, method=method, parameters=parameters, body=request.data, mimetype=request.mimetype, )
def create( cls, request: Union[HTTPRequest, HTTPServerRequest]) -> OpenAPIRequest: """Creates an OpenAPI request from Tornado request objects. Supports both :class:`tornado.httpclient.HTTPRequest` and :class:`tornado.httputil.HTTPServerRequest` objects. """ if isinstance(request, HTTPRequest): if request.url: path, _, querystring = request.url.partition("?") query_arguments: ImmutableMultiDict[str, str] = ImmutableMultiDict( parse_qsl(querystring)) else: path = "" query_arguments = ImmutableMultiDict() else: path, _, _ = request.full_url().partition("?") if path == "://": path = "" query_arguments = ImmutableMultiDict( itertools.chain( *[[(k, v.decode("utf-8")) for v in vs] for k, vs in request.query_arguments.items()])) return OpenAPIRequest( full_url_pattern=path, method=request.method.lower() if request.method else "get", parameters=RequestParameters( query=query_arguments, header=Headers(request.headers.get_all()), cookie=parse_cookie(request.headers.get("Cookie", "")), ), body=request.body if request.body else b"", mimetype=parse_mimetype( request.headers.get("Content-Type", "application/x-www-form-urlencoded")), )
def create(cls: t.Type["PyramidOpenAPIRequestFactory"], request: Request) -> "OpenAPIRequest": """Create OpenAPIRequest from Pyramid Request.""" method = request.method.lower() path_pattern = (request.matched_route.pattern if request.matched_route else request.path) parameters = RequestParameters( path=request.matchdict, query=request.GET, header=request.headers, cookie=request.cookies, ) full_url_pattern = urljoin(request.host_url, path_pattern) return OpenAPIRequest( full_url_pattern=full_url_pattern, method=method, parameters=parameters, body=request.body, mimetype=request.content_type, )
def test_http_server_request(self, opts: Tuple[str, Dict[str, str]]) -> None: url, parameters = opts request_url = f"{url}?{urlencode(parameters)}" if url else "" parsed = urlparse(request_url) tornado_request = HTTPServerRequest( method="GET", uri=f"{parsed.path}?{parsed.query}", ) tornado_request.protocol = parsed.scheme tornado_request.host = parsed.netloc.split(":")[0] expected = OpenAPIRequest( full_url_pattern=url, method="get", parameters=RequestParameters(query=ImmutableMultiDict(parameters), path={}, cookie={}), body=b"", mimetype="application/x-www-form-urlencoded", ) openapi_request = TornadoRequestFactory.create(tornado_request) self.assertEqual(attr.asdict(expected), attr.asdict(openapi_request))
def create(cls, request): method = request.method.lower() cookie = request.cookies or {} # gets deduced by path finder against spec path = {} mimetype = request.headers.get('Accept') or \ request.headers.get('Content-Type') parameters = RequestParameters( query=ImmutableMultiDict(request.params), header=request.headers, cookie=cookie, path=path, ) return OpenAPIRequest( full_url_pattern=request.url, method=method, parameters=parameters, body=request.data, mimetype=mimetype, )
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()
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()