async def test_validate_swagger_definition(container_requester): async with container_requester as requester: for path in ("/", "/db", "/db/guillotina"): resp, status = await requester("GET", os.path.join(path, "@swagger")) assert status == 200 validate_v3_spec(resp)
def test_openapi_endpoint(self): with app.test_client() as c: response = c.get("/openapi-spec.yaml") self.assertEqual(response.status_code, 200) self.assertIn(b"title: 'Karmen API'", response.data) specs = yaml.safe_load(str(response.data, "utf8")) openapi_spec_validator.validate_v3_spec(specs)
def _validate_openapi_spec_validator(self, spec_version): # pragma: nocover from openapi_spec_validator import validate_v2_spec, validate_v3_spec from jsonschema.exceptions import ValidationError as JSEValidationError from jsonschema.exceptions import RefResolutionError # Validate according to detected version. Unsupported versions are # already caught outside of this function. from .util.exceptions import raise_from if spec_version[0] == 3: # Set the version independently of whether validation succeeds self.__set_version(BaseParser.SPEC_VERSION_3_PREFIX, spec_version) try: validate_v3_spec(self.specification) except TypeError as type_ex: # pragma: nocover raise_from(ValidationError, type_ex) except JSEValidationError as v3_ex: raise_from(ValidationError, v3_ex) except RefResolutionError as ref_ex: raise_from(ValidationError, ref_ex) elif spec_version[0] == 2: # Set the version independently of whether validation succeeds self.__set_version(BaseParser.SPEC_VERSION_2_PREFIX, spec_version) try: validate_v2_spec(self.specification) except TypeError as type_ex: # pragma: nocover raise_from(ValidationError, type_ex) except JSEValidationError as v2_ex: raise_from(ValidationError, v2_ex) except RefResolutionError as ref_ex: raise_from(ValidationError, ref_ex)
def test_app(): client = app.test_client() spec = openapi.load_specification(app) validate_v3_spec(spec) assert client.get(openapi.config["specification_url"]).json == spec assert client.get(openapi.config["swagger_url"]).status_code == 200 assert client.get(openapi.config["redoc_url"]).status_code == 200 # -- with pytest.raises(Exception): assert client.get("/dog/1") == 200 with pytest.raises(Exception): assert client.get("/dog/1?test_param1=test") == 200 assert (client.get("/dog/1?test_param1=test", headers={ "test_param2": "test" }).status_code == 200) with pytest.raises(Exception): assert client.post("/dogs/", json={ "id": 1, "name": "doge" }).status_code == 200 assert (client.post("/dogs/", json={ "id": 1, "name": "doge", "age": 3 }).status_code == 200)
def __init__( self, app: web.Application, ui_path: Optional[str] = None, spec_file: str = "", *, validate: bool = True, request_key: str = "data", swagger_ui_settings: Optional[SwaggerUiSettings] = None, redoc_ui_settings: Optional[ReDocUiSettings] = None, ) -> None: if not spec_file: raise Exception("spec file with swagger schema must be provided") with open(spec_file) as f: spec = yaml.safe_load(f) validate_v3_spec(spec) if swagger_ui_settings is None and ui_path is not None: warnings.warn( "ui_path is deprecated and will be removed in 0.4.0, use swagger_ui_settings instead.", FutureWarning, ) swagger_ui_settings = SwaggerUiSettings(path=ui_path) super().__init__( app, validate=validate, spec=spec, request_key=request_key, swagger_ui_settings=swagger_ui_settings, redoc_ui_settings=redoc_ui_settings, ) self._app[_SWAGGER_SPECIFICATION] = self.spec
def _validate_file(self): import yaml import openapi_spec_validator print('validating {}...'.format(self._output_filename)) with open(self._output_filename) as fid: yobject = yaml.safe_load(fid) openapi_spec_validator.validate_v3_spec(yobject) print('validating complete')
def __init__( self, app: web.Application, ui_path: str, spec_file: str, *, request_key: str = "data", ) -> None: with open(spec_file) as f: spec = yaml.safe_load(f) validate_v3_spec(spec) super().__init__(app, ui_path, spec, request_key) self._app[_SWAGGER_SPECIFICATION] = spec
def _wrap_handler(self, method: str, path: str, handler: _SwaggerHandler, *, is_method: bool) -> _SwaggerHandler: if not handler.__doc__ or "---" not in handler.__doc__: return handler *_, spec = handler.__doc__.split("---") method_spec = yaml.safe_load(spec) self.spec["paths"][path][method] = method_spec validate_v3_spec(self.spec) self._app[_SWAGGER_SPECIFICATION] = self.spec if not self.validate: return handler route = SwaggerRoute(method, path, handler, swagger=self) if is_method: return functools.partialmethod( # type: ignore self._handle_swagger_method_call, route) return functools.partial(self._handle_swagger_call, route)
def __init__( self, app: web.Application, ui_path: Optional[str] = None, *, validate: bool = True, request_key: str = "data", title: str = "OpenAPI3", version: str = "1.0.0", description: Optional[str] = None, components: Optional[str] = None, swagger_ui_settings: Optional[SwaggerUiSettings] = None, redoc_ui_settings: Optional[ReDocUiSettings] = None, ) -> None: spec: Dict = { "openapi": "3.0.0", "info": {"title": title, "version": version}, "paths": defaultdict(lambda: defaultdict(dict)), } if description is not None: spec["info"]["description"] = description if components: with open(components) as f: spec.update(yaml.safe_load(f)) validate_v3_spec(spec) if swagger_ui_settings is None and ui_path is not None: warnings.warn( "ui_path is deprecated and will be removed in 0.4.0, use swagger_ui_settings instead.", FutureWarning, ) swagger_ui_settings = SwaggerUiSettings(path=ui_path) super().__init__( app, validate=validate, spec=spec, request_key=request_key, swagger_ui_settings=swagger_ui_settings, redoc_ui_settings=redoc_ui_settings, ) self._app[_SWAGGER_SPECIFICATION] = self.spec
def run(): """ The main function. Reads CRDs from URLs, intelligently extracts OpenAPIV3Schema(s) from each CRD, appends OpenAPIV3Schema to a designated file and verifies through OpenAPIValidator """ openapi_schema = yaml.load(openapi_schema_pattern) schemas = openapi_schema["components"]["schemas"] with open(crd_list, 'r') as crd_list_file: # read file with CRD locations crd_list_data = yaml.load(crd_list_file) for crd_path in crd_list_data['crdList']: crd_data = yaml.load_all( request.urlopen(crd_path).read().decode( 'utf-8')) # read CRD from URL for crd in crd_data: try: if check_yaml_kind(crd): process_crd( crd, schemas, crd_list_data["schemasLocation"], basename(urlparse(crd_path).path) == phase_rendered and getenv(rewrite_env) is not None) except Exception as exc: error( "An error occurred while processing CRD data from {}\n{}". format(crd_path, exc)) # Validate output V3 spec try: validate_v3_spec(openapi_schema) info("Validation of OpenAPIV3Schemas is successful") except OpenAPIValidationError as exc: error("An error occurred while validating OpenAPIV3Schema") raise exc # Rewrite openAPI schema file with open(openapi_schema_path, 'w') as openapi_schema_file: info("Saving OpenAPIV3Schemas") yaml.dump(openapi_schema, openapi_schema_file) # run openapi2jsonschema conversion command.default()
def _validate_openapi_spec_validator(self, spec_version): # pragma: nocover from openapi_spec_validator import validate_v2_spec, validate_v3_spec from jsonschema.exceptions import ValidationError as JSEValidationError from jsonschema.exceptions import RefResolutionError # Try v3 first, then fall back to v2 from .util.exceptions import raise_from try: try: validate_v3_spec(self.specification) self.__set_version(BaseParser.SPEC_VERSION_3_PREFIX, spec_version) except TypeError as type_ex: # pragma: nocover raise_from(ValidationError, type_ex) except JSEValidationError as v3_ex: try: validate_v2_spec(self.specification) self.__set_version(BaseParser.SPEC_VERSION_2_PREFIX, spec_version) except TypeError as type_ex: # pragma: nocover raise_from(ValidationError, type_ex) except RefResolutionError as ref_ex: raise_from(ValidationError, ref_ex)
def parse_spec(spec: t.Dict[str, t.Any]) -> model.OASSpecification: try: osv.validate_v3_spec(spec) except osv.exceptions.OpenAPIValidationError: logger.exception('Provided specification does not seem to be valid') raise else: return model.OASSpecification( version=spec['openapi'], servers=[ model.OASServer( url=s['url'], variables={ k: v['default'] for k, v in s.get('variables', {}).items() }, ) for s in spec['servers'] ], operations=_resolve_operations( paths=spec.get('paths', {}), components=spec.get('components', {}), ), )
def add_route( self, method: str, path: str, handler: Union[_WebHandler, AbstractView], *, name: Optional[str] = None, expect_handler: Optional[_ExpectHandler] = None, ) -> web.AbstractRoute: if handler.__doc__ and "---" in handler.__doc__: *_, spec = handler.__doc__.split("---") method_spec = yaml.safe_load(spec) method_lower = method.lower() self.spec["paths"][path][method_lower] = method_spec validate_v3_spec(self.spec) route = SwaggerRoute(method_lower, path, handler, swagger=self) self._app[_SWAGGER_SPECIFICATION] = self.spec handler = functools.partial(self._handle_swagger_call, route) return self._app.router.add_route(method, path, handler, name=name, expect_handler=expect_handler)
def test_schema(app: Starlette): validate_v3_spec(apiman.specification)
def test_valid_openapi_spec(): app = create_app() api.register(app) spec = api.spec validate_v3_spec(spec)
def test_apiman(): validate_v3_spec(apiman.specification)