def test_questions_match_schema(all_files): question_schema = load_jsonschema('tests/schemas/question.json') for path in all_files: with open(path) as f: data = yaml.load(f) try: validator_for(question_schema)(question_schema).validate(data) except ValidationError as e: pytest.fail("{} failed validation with: {}".format(path, e))
def test_draft_4(self): schema = {"$schema": "http://json-schema.org/draft-04/schema"} self.assertIs( validators.validator_for(schema), validators.Draft4Validator, ) schema = {"$schema": "http://json-schema.org/draft-04/schema#"} self.assertIs( validators.validator_for(schema), validators.Draft4Validator, )
def test_draft_6(self): schema = {"$schema": "http://json-schema.org/draft-06/schema"} self.assertIs( validators.validator_for(schema), validators.Draft6Validator, ) schema = {"$schema": "http://json-schema.org/draft-06/schema#"} self.assertIs( validators.validator_for(schema), validators.Draft6Validator, )
def adjust_swagger_body_item_to_json_schema(schema: Mapping) -> Mapping: required = schema.get('required', False) _schema = schema.get('schema') new_schema = deepcopy(_schema) if not required: new_schema = { 'anyOf': [ { 'type': 'null' }, new_schema, ] } validators.validator_for(new_schema).check_schema(new_schema) return new_schema
def main(here: str): args = parse_args() meta = load_hocon(here + "/meta.conf") validator_for(meta).check_schema(meta) driver = LazyDriver() collisions = {} for schema_file in args.files: if Path(schema_file).name.startswith("_"): continue try: schema = validate_file(meta, schema_file) except InvalidFile as e: if args.linter and driver.driver: open_linter(driver, meta, load_hocon(schema_file)) elif args.raise_: e.raise_original() e.report(schema_file) except ValidationError as e: e.report(schema_file) else: for def_name, value in schema.get("_definitions", {}).items(): service_name = str(Path(schema_file).stem) remove_description(value) collisions.setdefault(def_name, {})[service_name] = value warning = color("warning", fg="red") if args.detect_collisions: for name, values in collisions.items(): if len(values) <= 1: continue groups = [[service for (service, _) in pairs] for _, pairs in groupby(values.items(), itemgetter(1))] if not groups: raise RuntimeError("Unknown error") print( "{}: collision for {}:\n{}".format(warning, name, yaml.dump(groups)), end="", ) driver.wait()
def validate_config(config): from jsonschema import validators _validator_class = validators.validator_for(__SCHEMA__) _validator_class.check_schema(__SCHEMA__) validator = _validator_class(__SCHEMA__) validator.validate(config)
def validate(self, **kwargs): if ('publication_state' in self and self['publication_state'] == PublicationStates.draft.name): if 'community' not in self: raise ValidationError('Missing required field "community"') try: community_id = uuid.UUID(self['community']) except (ValueError, KeyError) as e: raise InvalidDepositError('Community ID is not a valid UUID.') \ from e default_validator = validator_for( CommunitySchema.get_community_schema(community_id).build_json_schema()) if 'required' not in default_validator.VALIDATORS: raise NotImplementedError('B2Share does not support schemas ' 'which have no "required" keyword.') DraftDepositValidator = type( 'DraftDepositValidator', (default_validator,), dict(VALIDATORS=copy.deepcopy(default_validator.VALIDATORS)) ) # function ignoring the validation of the given keyword ignore = lambda *args, **kwargs: None DraftDepositValidator.VALIDATORS['required'] = ignore DraftDepositValidator.VALIDATORS['minItems'] = ignore kwargs['validator'] = DraftDepositValidator return super(Deposit, self).validate(**kwargs)
def validate_json_response(schema, *args, **kwargs): cls = validator_for(schema) cls.check_schema(schema) validator = cls(schema, *args, **kwargs) def wrapper(func): @functools.wraps(func) def validate_json_schema(*args, **kwargs): response: HttpResponse = func(*args, **kwargs) if response['Content-Type'] == 'application/json': errors = list( validator.iter_errors(json.loads(response.content))) if errors: log.error("Invalid response. %d errors encountered", len(errors)) for error in errors: log.error("%s", error) print(error) return HttpResponseServerError( "The server generated an invalid response.") return response return validate_json_schema return wrapper
def create_form(self, schema: dict, ui_schema: dict, state=None) -> widgets.SchemaWidgetMixin: validator_cls = self.validator_cls if validator_cls is None: validator_cls = validator_for(schema) validator_cls.check_schema(schema) validator = validator_cls(schema) schema_widget = self.create_widget(schema, ui_schema, state) form = widgets.FormWidget(schema_widget) def validate(data): form.clear_errors() errors = [*validator.iter_errors(data)] if errors: form.display_errors(errors) for err in errors: schema_widget.handle_error(err.path, err) schema_widget.on_changed.connect(validate) return form
def validate_request_body(flask_request): with open(file_name, encoding='utf-8') as f: json_content = json.load(f) user_schema = json_content['components']['schemas']['User'] # try: # result = validate(flask_request.get_json(), user_schema, format_checker=FormatChecker()) # except Exception as ex: # # return ex.__repr__() #or # error_param = ex.context[-1].instance if hasattr(ex, 'context') and len(ex.context) > 0 else ex # return ex.message # v = Draft4Validator(user_schema) cls = validator_for(user_schema) cls.check_schema(user_schema) tree = ErrorTree( cls(user_schema, format_checker=FormatChecker()).iter_errors(json_content)) # tree = ErrorTree(v.iter_errors(flask_request.get_json())) if tree.total_errors > 0: print(tree.total_errors) error_list = parse_tree_errors(tree) pprint.pprint(error_list) return ', '.join(e['message'] for e in error_list) if error_list else None
def validate(payload, schema): """Validate a payload according to a given schema""" validator_cls = validator_for(schema) validator = validator_cls(schema=schema) errors = list(validator.iter_errors(payload)) if errors: raise JsonValidationError("Payload is not valid", errors)
def validate_node_model(target, service, role): ''' Validates pillar by schema for given given minion, service and role. If no service and role is specified, method will validate all defined services on minion. CLI Example: .. code-block:: bash salt-run modelschema.validate_node_model ''' client = salt.client.LocalClient(__opts__['conf_file']) schema = _get_schemas()[service][role] result = {} validator = validator_for(schema) try: validator.check_schema(schema) except SchemaError as exception: LOG.error(exception) return result minions = client.cmd(target, 'pillar.data', timeout=1) for minion, pillar in minions.items(): model = pillar[service][role] validation_result = validator(schema).validate(model) result[minion] = validation_result return result
def validate(self, **kwargs): if ('publication_state' in self and self['publication_state'] == PublicationStates.draft.name): if 'community' not in self: raise ValidationError('Missing required field "community"') try: community_id = uuid.UUID(self['community']) except (ValueError, KeyError) as e: raise InvalidDepositError('Community ID is not a valid UUID.') \ from e default_validator = validator_for( CommunitySchema.get_community_schema( community_id).build_json_schema()) if 'required' not in default_validator.VALIDATORS: raise NotImplementedError('B2Share does not support schemas ' 'which have no "required" keyword.') DraftDepositValidator = type( 'DraftDepositValidator', (default_validator, ), dict(VALIDATORS=copy.deepcopy(default_validator.VALIDATORS))) # function ignoring the validation of the given keyword ignore = lambda *args, **kwargs: None DraftDepositValidator.VALIDATORS['required'] = ignore DraftDepositValidator.VALIDATORS['minItems'] = ignore kwargs['validator'] = DraftDepositValidator return super(Deposit, self).validate(**kwargs)
def validate(instance, schema, cls=None, *args, inject_defaults=False, **kwargs): """ Drop-in replacement for jsonschema.validate(), with the following extended functionality: - Specifically allow types from ruamel.yaml.comments - If inject_defaults is True, this function *modifies* the instance IN-PLACE to fill missing properties with their schema-provided default values. See the jsonschema FAQ: http://python-jsonschema.readthedocs.org/en/latest/faq/ """ if cls is None: cls = validators.validator_for(schema) cls.check_schema(schema) if inject_defaults: # Add default-injection behavior to the validator cls = extend_with_default(cls) # By default, jsonschema expects JSON objects to be of type 'dict'. # We also want to permit ruamel.yaml.comments.CommentedSeq and CommentedMap # https://python-jsonschema.readthedocs.io/en/stable/validate/?highlight=str#validating-with-additional-types kwargs["types"] = {"object": (CommentedMap, dict), "array": (CommentedSeq, list)} # Can't use collections.abc.Sequence because that would catch strings, too! # Validate and inject defaults. cls(schema, *args, **kwargs).validate(instance)
def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) if not cls.kind: raise ProgrammingError(f"{cls} does not have a kind attribute set") if not cls.version: raise ProgrammingError( f"{cls} does not have a version attribute set") if cls.kind in long_names: raise ProgrammingError( f"{cls} is a duplicate of resource kind {cls.kind}") long_names[cls.kind] = cls for short_name in cls.short_names: if short_name in short_names: raise ProgrammingError( f"{cls} is a duplicate of short name {short_name}") short_names[short_name] = cls package_root = pathlib.Path(__file__).parent.parent with open(package_root / "schemas" / f"{cls.kind}.json", "r") as fp: schema_data = json.load(fp) validator_cls = validator_for(schema_data) validator_cls.check_schema(schema_data) cls.validator = validator_cls(schema_data)
def _load_schema_and_validator(): basepath = os.path.dirname(__file__) filepath = os.path.join(basepath, 'schemas/json-table-schema.json') with open(filepath) as file: json_table_schema = json.load(file) BaseValidator = validator_for(json_table_schema) return json_table_schema, BaseValidator
def validate(instance, schema, cls=None, *args, inject_defaults=False, **kwargs): """ Drop-in replacement for jsonschema.validate(), with the following extended functionality: - Specifically allow types from ruamel.yaml.comments - If inject_defaults is True, this function *modifies* the instance IN-PLACE to fill missing properties with their schema-provided default values. See the jsonschema FAQ: http://python-jsonschema.readthedocs.org/en/latest/faq/ """ if cls is None: cls = validators.validator_for(schema) cls.check_schema(schema) if inject_defaults: # Add default-injection behavior to the validator cls = extend_with_default(cls) # By default, jsonschema expects JSON objects to be of type 'dict'. # We also want to permit ruamel.yaml.comments.CommentedSeq and CommentedMap # https://python-jsonschema.readthedocs.io/en/stable/validate/?highlight=str#validating-with-additional-types kwargs["types"] = { "object": (CommentedMap, dict), "array": (CommentedSeq, list) } # Can't use collections.abc.Sequence because that would catch strings, too! # Validate and inject defaults. cls(schema, *args, **kwargs).validate(instance)
def __init__(self, *args, **kwargs): self.__dict__["schema"] = schema cls = validator_for(self.schema) self.__dict__["validator_instance"] = cls(schema) baseJSchema.__init__(self, *args, **kwargs)
def validate(filename): """ Validates provided JSON dictionary based on our schema :param filename: file to be validated :return: list of errors """ # Load schema and initialize validator schema_data = Utils._load_schema() validator = validator_for(schema_data) # Read file, convert to a JSON dictionary and validate data = Utils._convert_config_file_to_json_dict(filename) errors = validator(schema=schema_data).iter_errors(data) # Convert errors to our own class data = [] for error in errors: data.append( ValidationError( title=error.schema['title'], section=error.path[0], setting=error.path[1] if len(error.path) > 1 else None, message=error.message)) return data
def decorated(*args, **kwargs): schema = current_app.extensions['jsonschema'].get_schema(path) validator_class = validator_for(schema) validator = validator_class(schema, format_checker=self.format_checker) errors = list(validator.iter_errors(request.json)) if errors: raise ValidationError('Error validation request against schema', errors) return fn(*args, **kwargs)
def check_schema(schema): """ Check a given schema to make sure it is valid YAML schema. """ create_validator() cls = validators.validator_for(schema) cls.check_schema(schema)
def validate_json_schema(self, json_schema): """Make sure the json schema provided in the VALIDATION_FIELD field is valid source code from: https://python-jsonschema.readthedocs.io/en/stable/_modules/jsonschema/validators/#validate TODO: Maybe add additional check,e.g. fields in "required" should appear in "properties" """ cls = validators.validator_for(json_schema) cls.check_schema(json_schema)
def get_validator(schema_name: str): store = _get_schema_store() schema = store[_schema_id_base + schema_name] return validator_for(schema)( schema, resolver=RefResolver("", schema, store), format_checker=draft7_format_checker, )
def load_jsonschema_validator(path): if path not in schema_cache: with open(path) as f: schema = json.load(f) validator = validator_for(schema) validator.check_schema(schema) schema_cache[path] = validator(schema) return schema_cache[path]
def _add_schema(self, schema: Dict): cls = validator_for(schema) cls.check_schema(schema) assert 'id' in schema # Normalize root schemas by appending empty fragments. if '#' not in schema['id']: schema['id'] += '#' assert schema['id'] not in self._schemas self._schemas[schema['id']] = schema
def validate_schema(self, data_file, file_base): return_value = True schema_file = self.get_schema_path(file_base) try: schema_contents = CPConfigFile.parse(schema_file) data_contents = CPConfigFile.parse(data_file) # We've already checked the input files for errors, but not the # schema files schema_errors = CPConfigFile.errors(schema_file) schema_warnings = CPConfigFile.warnings(schema_file) if schema_warnings: self._warnings += schema_warnings if schema_errors: self._errors += schema_errors return False except Exception as e: msg = ( 'Syntax errors detected, data:"%s" schema "%s" errors "%s" ' % (data_file, schema_file, e)) self.add_error(msg) return_value = False try: schema_check = validators.validator_for(schema_contents) schema_check.check_schema(schema_contents) except SchemaError as e: self.add_error('Schema "%s" is invalid: %s' % (schema_contents, e)) return False try: validate = Draft4Validator(schema_contents) error_list = [err for err in validate.iter_errors(data_contents)] if len(error_list) > 0: error_string = '\n\nInput\n%s\n\nCould not be validated - list of errors:\n' % ( _utils.indent( yaml.dump(data_contents, default_flow_style=False, indent=4))) for e in error_list: error_string += "%s\n%s\n%s\n" % ( _utils.indent("Index of error: %s" % _utils.format_as_index(deque(e.path))), _utils.indent(" Erroneous value: %s" % pprint.pformat(e.instance, width=72)), _utils.indent( " Expected type: %s" % e.validator_value)) self.add_error(error_string) return_value = False except Exception as e: self.add_error('File "%s" or "%s" could not be loaded: %s' % (schema_file, data_file, e)) return_value = False return return_value
def __init__(self, name, schema, required=False, session=None): self._name = name self._schema = schema self._required = required self._session = session validator_cls = validator_for(schema) validator_cls.check_schema(schema) self._validator = validator_cls(schema)
def is_valid(self, value: Any) -> bool: """ Determine whether a given object conforms to this schema. :param value: An object to test for validity against this schema :return: True if the object is valid, otherwise False """ return validator_for(self.jsonschema_full_schema)( self.jsonschema_full_schema).is_valid(value)
def parse_args(args): arguments = vars(parser.parse_args(args=args or ["--help"])) if arguments["validator"] is None: arguments["validator"] = validator_for(arguments["schema"]) if arguments["output"] != "plain" and arguments["error_format"]: raise parser.error( "--error-format can only be used with --output plain") if arguments["output"] == "plain" and arguments["error_format"] is None: arguments["error_format"] = "{error.instance}: {error.message}\n" return arguments
def test_custom_validator_draft6(self): Validator = validators.create( meta_schema={"$id": "meta schema $id"}, version="13", ) schema = {"$schema": "meta schema $id"} self.assertIs( validators.validator_for(schema), Validator, )
def test_custom_validator(self): Validator = validators.create( meta_schema={"id": "meta schema id"}, version="12", ) schema = {"$schema": "meta schema id"} self.assertIs( validators.validator_for(schema), Validator, )
def decorated(*args, **kwargs): schema = current_app.extensions['jsonschema'].get_schema(path) validator_class = validator_for(schema) validator = validator_class(schema, format_checker=self.format_checker) errors = list(validator.iter_errors(request.json)) if errors: raise ValidationError( 'Error validation request against schema', errors) return fn(*args, **kwargs)
def get_validator(filename, allow_additional_properties=True): with open(join(dirname(__file__), join("schemas", filename))) as schema_file: schema = json.load(schema_file) if not allow_additional_properties: schema["additionalProperties"] = False validator_class = validator_for(schema) validator_class.check_schema(schema) return validator_class(schema)
def get_validator(schema_name, enforce_required=True, required_fields=None): if required_fields is None: required_fields = [] if enforce_required: schema = _SCHEMAS[schema_name] else: schema = copy.deepcopy(_SCHEMAS[schema_name]) schema["required"] = [field for field in schema.get("required", []) if field in required_fields] schema.pop("anyOf", None) return validator_for(schema)(schema, format_checker=FORMAT_CHECKER)
def check(name, correct_schema): schema = validator.schema[name] cls = validator_for(schema) is_valid_schema = True try: cls.check_schema(schema) except SchemaError: is_valid_schema = False assert is_valid_schema assert schema == correct_schema
def json_validator(schema: Dict[Text, Any]) -> Callable[[Dict[Text, Any]], Any]: """ implements that fastjsonschema.compile API with jsonschema """ validator_cls = validator_for(schema) def _validate(instance: Dict[Text, Any]) -> Any: validate(instance, schema, cls=validator_cls) return instance return _validate
def load_schemas(schema_paths): loaded_schemas = {} for schema_path in schema_paths: schema_name = os.path.splitext(os.path.basename(schema_path))[0] with open(schema_path) as f: schema = json.load(f) validator = validator_for(schema) validator.check_schema(schema) loaded_schemas[schema_name] = schema return loaded_schemas
def validate_schema(self, data_file, file_base): return_value = True schema_file = self.get_schema_path(file_base) try: schema_contents = CPConfigFile.parse(schema_file) data_contents = CPConfigFile.parse(data_file) # We've already checked the input files for errors, but not the # schema files schema_errors = CPConfigFile.errors(schema_file) schema_warnings = CPConfigFile.warnings(schema_file) if schema_warnings: self._warnings += schema_warnings if schema_errors: self._errors += schema_errors return False except Exception as e: msg = ('Syntax errors detected, data:"%s" schema "%s" errors "%s" ' % (data_file, schema_file, e)) self.add_error(msg) return_value = False try: schema_check = validators.validator_for(schema_contents) schema_check.check_schema(schema_contents) except SchemaError as e: self.add_error('Schema "%s" is invalid: %s' % ( schema_contents, e)) return False try: validate = Draft4Validator(schema_contents) error_list = [err for err in validate.iter_errors(data_contents)] if len(error_list) > 0: error_string = '\n\nInput\n%s\n\nCould not be validated - list of errors:\n' % ( _utils.indent(yaml.dump(data_contents, default_flow_style=False, indent=4))) for e in error_list: error_string += "%s\n%s\n%s\n" % ( _utils.indent("Index of error: %s" % _utils.format_as_index(deque(e.path))), _utils.indent(" Erroneous value: %s" % pprint.pformat(e.instance, width=72)), _utils.indent(" Expected type: %s" % e.validator_value)) self.add_error(error_string) return_value = False except Exception as e: self.add_error('File "%s" or "%s" could not be loaded: %s' % ( schema_file, data_file, e)) return_value = False return return_value
def load_schemas(schemas_path, schema_names): loaded_schemas = {} for schema_name in schema_names: schema_path = os.path.join(schemas_path, '{}.json'.format(schema_name)) with open(schema_path) as f: schema = json.load(f) validator = validator_for(schema) validator.check_schema(schema) loaded_schemas[schema_name] = schema return loaded_schemas
def get_validator(schema_name, enforce_required=True, required_fields=None): if required_fields is None: required_fields = [] if enforce_required: schema = _SCHEMAS[schema_name] else: schema = _SCHEMAS[schema_name].copy() schema['required'] = [ field for field in schema.get('required', []) if field in required_fields ] return validator_for(schema)(schema, format_checker=FORMAT_CHECKER)
def inject_defaults(instance, schema, include_yaml_comments=False, yaml_indent=2, cls=None, *args, **kwargs): """ Like the above validate_and_inject_defaults, but: 1. Ignore schema validation errors and 'required' property errors 2. If no default is given for a property, inject '{{NO_DEFAULT}}', even if the property isn't supposed to be a string. 3. If include_yaml_comments is True, insert CommentedMap objects instead of ordinary dicts, and insert a comment above each key, with the contents of the property "description" in the schema. Args: instance: The Python object to inject defaults into. May be an empty dict ({}). schema: The schema data to pull defaults from include_yaml_comments: Whether or not to return ruamel.yaml-compatible dicts so that comments will be written when the data is dumped to YAML. yaml_indent: To ensure correctly indented comments, you must specify the indent step you plan to use when this data is eventually dumped as yaml. Returns: A copy of instance, with default values injected, and comments if specified. """ if cls is None: cls = validators.validator_for(schema) cls.check_schema(schema) # Add default-injection behavior to the validator extended_cls = extend_with_default_without_validation(cls, include_yaml_comments, yaml_indent) if include_yaml_comments: instance = CommentedMap(instance) instance.key_indent = 0 # monkey-patch! else: instance = dict(instance) # Inject defaults. extended_cls(schema, *args, **kwargs).validate(instance) return instance
def validate_and_inject_defaults(instance, schema, cls=None, *args, **kwargs): """ Drop-in replacement for jsonschema.validate(), but also *modifies* the instance to fill missing properties with their schema-provided default values. See the jsonschema FAQ: http://python-jsonschema.readthedocs.org/en/latest/faq/ """ if cls is None: cls = validators.validator_for(schema) cls.check_schema(schema) # Add default-injection behavior to the validator extended_cls = extend_with_default(cls) # Validate and inject defaults. extended_cls(schema, *args, **kwargs).validate(instance)
def validate_against(self, instance, schemauris=[], strict=False): """ validate the instance against each of the schemas identified by the list of schemauris. For the instance to be considered valid, it must validate against each of the named schemas. $extensionSchema properties within the instance are ignored. :argument instance: a parsed JSON document to be validated. :argument list schemauris: a list of URIs of the schemas to validate against. :argument bool strict: if True, validation will fail if any of the schema URIs cannot be resolved to a schema. if False, unresolvable schemas URIs will be ignored and validation against that schema will be skipped. """ if isinstance(schemauris, str) or isinstance(schemauris, unicode): schemauris = [ schemauris ] schema = None out = True for uri in schemauris: val = self._validators.get(uri) if not val: (urib,frag) = self._spliturifrag(uri) schema = self._schemaStore.get(urib) if not schema: try: schema = self._loader(urib) except KeyError, e: if strict: raise SchemaError("Unable to resolve schema for " + urib) continue resolver = jsch.RefResolver(uri, schema, self._schemaStore, handlers=self._handler) if frag: try: schema = resolver.resolve_fragment(schema, frag) except RefResolutionError, ex: raise SchemaError("Unable to resolve fragment, "+frag+ "from schema, "+ urib) cls = jsch.validator_for(schema) cls.check_schema(schema) val = cls(schema, resolver=resolver)
def getValidator(schema, schema_store): """ Get a L{jsonschema} validator for C{schema}. @param schema: The JSON Schema to validate against. @type schema: L{dict} @param dict schema_store: A mapping between schema paths (e.g. ``b/v1/types.json``) and the JSON schema structure. """ # The base_uri here isn't correct for the schema, # but does give proper relative paths. resolver = LocalRefResolver( base_uri=b'', referrer=schema, store=schema_store) return validator_for(schema)( schema, resolver=resolver, format_checker=draft4_format_checker)
def __init__(self, raw_schema, base_uri=None, resolver=None, resolver_cls=None, validator=None, validator_cls=None): self.raw_schema = raw_schema if resolver is None: if resolver_cls is None: resolver_cls = jsonschema.RefResolver if base_uri is None: base_uri = self.raw_schema.get(u'id', u'') resolver = resolver_cls(base_uri, self.raw_schema) self.resolver = resolver if validator is None: if validator_cls is None: validator_cls = validator_for(self.raw_schema) validator = validator_cls(self.raw_schema, resolver=self.resolver) self.validator = validator
def validate(instance, schema, *args, **kwargs): """ Validate the given instance against the given schema using the YAML schema extensions to JSON schema. The arguments are the same as to `jsonschema.validate`. """ create_validator() if 'resolver' not in kwargs: kwargs['resolver'] = RESOLVER # We don't just call validators.validate() directly here, because # that validates the schema itself, wasting a lot of time (at the # time of this writing, it was half of the runtime of the unit # test suite!!!). Instead, we assume that the schemas are valid # through the running of the unit tests, not at run time. cls = validators.validator_for(schema) cls(schema, *args, **kwargs).validate(instance)
def validate(instance, schema, resolver=None, *args, **kwargs): """ Validate the given instance against the given schema using the YAML schema extensions to JSON schema. The arguments are the same as to `jsonschema.validate`. """ create_validator() handlers = {} for x in ['http', 'https', 'file']: handlers[x] = _make_schema_loader(resolver) kwargs['resolver'] = validators.RefResolver( schema.get('id', ''), schema, cache_remote=False, handlers=handlers) # We don't just call validators.validate() directly here, because # that validates the schema itself, wasting a lot of time (at the # time of this writing, it was half of the runtime of the unit # test suite!!!). Instead, we assume that the schemas are valid # through the running of the unit tests, not at run time. cls = validators.validator_for(schema) cls(schema, *args, **kwargs).validate(instance)
def test_validator_for_custom_default(self): self.assertIs(validator_for({}, default=None), None)
def test_validator_for_jsonschema_default(self): self.assertIs(validator_for({}), Draft4Validator)
def test_draft_3(self): schema = {"$schema" : "http://json-schema.org/draft-03/schema"} self.assertIs(validator_for(schema), Draft3Validator) schema = {"$schema" : "http://json-schema.org/draft-03/schema#"} self.assertIs(validator_for(schema), Draft3Validator)
def get_validator(schema_name): schema = _SCHEMAS[schema_name] return validator_for(schema)(schema, format_checker=FORMAT_CHECKER)
def load_jsonschema(path): with open(path) as f: schema = json.load(f) validator = validator_for(schema) validator.check_schema(schema) return schema
def check_data_type_schema_is_valid(data_type): schema = get_schema('example', data_type) validator_for(schema).check_schema(schema)
Arguments: g4_g5_export_file The file to process ''' import sys import json from jsonschema import validate, ValidationError from jsonschema.validators import validator_for with open("../json_schemas/services-g5.json") as json_schema: G5_SCHEMA = json.load(json_schema) print("Loaded Schema") G5_VALIDATOR = validator_for(G5_SCHEMA) print("Got validator") G5_VALIDATOR.check_schema(G5_SCHEMA) print("Checked schema") G5_VALIDATOR = G5_VALIDATOR(G5_SCHEMA) print("G5 Schema is GO!") with open("../json_schemas/services-g4.json") as json_schema2: G4_SCHEMA = json.load(json_schema2) print("Loaded Schema") G4_VALIDATOR = validator_for(G4_SCHEMA) print("Got validator") G4_VALIDATOR.check_schema(G4_SCHEMA) print("Checked schema") G4_VALIDATOR = G4_VALIDATOR(G4_SCHEMA) print("G4 Schema is GO!")
def _get_validator_cls(validate_args, schema): cls = validate_args.get('cls') if cls is None: cls = validator_for(schema) return cls
def load_validator(): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'json-table-schema.json') with open(filepath) as f: json_table_schema = json.load(f) return json_table_schema, validator_for(json_table_schema)
def parse_args(args): arguments = vars(parser.parse_args(args=args or ["--help"])) if arguments["validator"] is None: arguments["validator"] = validator_for(arguments["schema"]) return arguments