Python jsonschema.validate() Examples
The following are 30
code examples of jsonschema.validate().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
jsonschema
, or try the search function
.
Example #1
Source File: config.py From query-exporter with GNU General Public License v3.0 | 8 votes |
def _validate_config(config: Dict[str, Any]): schema_path = PACKAGE.get_resource_filename( # type: ignore None, "query_exporter/schemas/config.yaml" ) with open(schema_path) as fd: schema = yaml.safe_load(fd) try: jsonschema.validate(config, schema) except jsonschema.ValidationError as e: path = "/".join(str(item) for item in e.absolute_path) raise ConfigError(f"Invalid config at {path}: {e.message}")
Example #2
Source File: test_schema_validation.py From drydock with Apache License 2.0 | 7 votes |
def _test_validate(self, schema, expect_failure, input_files, input): """validates input yaml against schema. :param schema: schema yaml file :param expect_failure: should the validation pass or fail. :param input_files: pytest fixture used to access the test input files :param input: test input yaml doc filename""" schema_dir = pkg_resources.resource_filename('drydock_provisioner', 'schemas') schema_filename = os.path.join(schema_dir, schema) schema_file = open(schema_filename, 'r') schema = yaml.safe_load(schema_file) input_file = input_files.join(input) instance_file = open(str(input_file), 'r') instance = yaml.safe_load(instance_file) if expect_failure: with pytest.raises(ValidationError): jsonschema.validate(instance['spec'], schema['data']) else: jsonschema.validate(instance['spec'], schema['data'])
Example #3
Source File: test_basic.py From auto-alt-text-lambda-api with MIT License | 6 votes |
def test_pydist(): """Make sure pydist.json exists and validates against our schema.""" # XXX this test may need manual cleanup of older wheels import jsonschema def open_json(filename): with open(filename, 'rb') as json_file: return json.loads(json_file.read().decode('utf-8')) pymeta_schema = open_json(resource_filename('wheel.test', 'pydist-schema.json')) valid = 0 for dist in ("simple.dist", "complex-dist"): basedir = pkg_resources.resource_filename('wheel.test', dist) for (dirname, subdirs, filenames) in os.walk(basedir): for filename in filenames: if filename.endswith('.whl'): whl = ZipFile(os.path.join(dirname, filename)) for entry in whl.infolist(): if entry.filename.endswith('/metadata.json'): pymeta = json.loads(whl.read(entry).decode('utf-8')) jsonschema.validate(pymeta, pymeta_schema) valid += 1 assert valid > 0, "No metadata.json found"
Example #4
Source File: test_basic.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
def test_pydist(): """Make sure pydist.json exists and validates against our schema.""" # XXX this test may need manual cleanup of older wheels import jsonschema def open_json(filename): return json.loads(open(filename, 'rb').read().decode('utf-8')) pymeta_schema = open_json(resource_filename('wheel.test', 'pydist-schema.json')) valid = 0 for dist in ("simple.dist", "complex-dist"): basedir = pkg_resources.resource_filename('wheel.test', dist) for (dirname, subdirs, filenames) in os.walk(basedir): for filename in filenames: if filename.endswith('.whl'): whl = ZipFile(os.path.join(dirname, filename)) for entry in whl.infolist(): if entry.filename.endswith('/metadata.json'): pymeta = json.loads(whl.read(entry).decode('utf-8')) jsonschema.validate(pymeta, pymeta_schema) valid += 1 assert valid > 0, "No metadata.json found"
Example #5
Source File: test_basic.py From jbox with MIT License | 6 votes |
def test_pydist(): """Make sure pydist.json exists and validates against our schema.""" # XXX this test may need manual cleanup of older wheels import jsonschema def open_json(filename): return json.loads(open(filename, 'rb').read().decode('utf-8')) pymeta_schema = open_json(resource_filename('wheel.test', 'pydist-schema.json')) valid = 0 for dist in ("simple.dist", "complex-dist"): basedir = pkg_resources.resource_filename('wheel.test', dist) for (dirname, subdirs, filenames) in os.walk(basedir): for filename in filenames: if filename.endswith('.whl'): whl = ZipFile(os.path.join(dirname, filename)) for entry in whl.infolist(): if entry.filename.endswith('/metadata.json'): pymeta = json.loads(whl.read(entry).decode('utf-8')) jsonschema.validate(pymeta, pymeta_schema) valid += 1 assert valid > 0, "No metadata.json found"
Example #6
Source File: utilities.py From king-phisher with BSD 3-Clause "New" or "Revised" License | 6 votes |
def validate_json_schema(data, schema_file_id): """ Validate the specified data against the specified schema. The schema file will be searched for and loaded based on it's id. If the validation fails a :py:class:`~jsonschema.exceptions.ValidationError` will be raised. :param data: The data to validate against the schema. :param schema_file_id: The id of the schema to load. """ schema_file_name = schema_file_id + '.json' file_path = find.data_file(os.path.join('schemas', 'json', schema_file_name)) if file_path is None: raise FileNotFoundError('the json schema file was not found') with open(file_path, 'r') as file_h: schema = json.load(file_h) jsonschema.validate(data, schema)
Example #7
Source File: utilities.py From king-phisher with BSD 3-Clause "New" or "Revised" License | 6 votes |
def password_is_complex(password, min_len=12): """ Check that the specified string meets standard password complexity requirements. :param str password: The password to validate. :param int min_len: The mininum length the password should be. :return: Whether the strings appears to be complex or not. :rtype: bool """ has_upper = False has_lower = False has_digit = False if len(password) < min_len: return False for char in password: if char.isupper(): has_upper = True if char.islower(): has_lower = True if char.isdigit(): has_digit = True if has_upper and has_lower and has_digit: return True return False
Example #8
Source File: ObjectStore.py From pcocc with GNU General Public License v3.0 | 6 votes |
def _validate_repo_config(self): try: with open(self._config_path) as f: repo_config = yaml.safe_load(f) jsonschema.validate(repo_config, yaml.safe_load(repo_config_schema)) except (yaml.YAMLError, IOError, jsonschema.exceptions.ValidationError) as err: raise PcoccError( 'Bad repository config file {0} : {1}'.format(self._config_path, err)) if repo_config['version'] != 1: raise InvalidConfigurationError( 'unsupported repository {0} version'.format(self.name))
Example #9
Source File: ObjectStore.py From pcocc with GNU General Public License v3.0 | 6 votes |
def _read_meta(self, meta_path, name, revision): if not os.path.isfile(meta_path): raise ObjectNotFound(name, self._name, revision) try: with open(meta_path, 'r') as f: meta = yaml.safe_load(f) except (OSError, IOError) as e: raise PcoccError('Unable to get metadata for {0}: {1}'.format( name, e)) except yaml.YAMLError as e: raise PcoccError('Bad metadata for {0}: {1}'.format( name, e)) try: jsonschema.validate(meta, yaml.safe_load(metadata_schema)) except jsonschema.exceptions.ValidationError as e: raise PcoccError('Bad metadata for {0}: {1}'.format( name, e)) return meta
Example #10
Source File: ObjectStore.py From pcocc with GNU General Public License v3.0 | 6 votes |
def load_repos(self, repo_config_file, tag): try: stream = file(repo_config_file, 'r') repo_config = yaml.safe_load(stream) except (yaml.YAMLError, IOError) as err: raise InvalidConfigurationError(str(err)) try: jsonschema.validate(repo_config, yaml.safe_load(repo_definition_schema)) except jsonschema.exceptions.ValidationError as err: raise InvalidConfigurationError(err.message) for repo in repo_config['repos']: if repo['name'] in self._repos.keys(): raise InvalidConfigurationError('Duplicate repository: {0}'.format( repo['name'])) repo['tag'] = tag repo['store'] = ObjectStore(Config().resolve_path(repo['path']), repo['name']) self._repos[repo['name']] = repo
Example #11
Source File: test_sql_validator.py From spectacles with MIT License | 6 votes |
def validator_fail_with_warning( self, record_mode, validator ) -> Iterable[Tuple[SqlValidator, Dict]]: with vcr.use_cassette( "tests/cassettes/test_sql_validator/fixture_validator_fail_with_warning.yaml", match_on=["uri", "method", "raw_body"], filter_headers=["Authorization"], record_mode=record_mode, ): # Move to dev mode to test conditional logic warning validator.client.update_workspace("eye_exam", "dev") validator.client.checkout_branch("eye_exam", "pytest") validator.build_project(selectors=["eye_exam/users__fail_and_warn"]) results = validator.validate(mode="hybrid") yield validator, results
Example #12
Source File: test_sql_validator.py From spectacles with MIT License | 6 votes |
def validator_warn( self, record_mode, validator ) -> Iterable[Tuple[SqlValidator, Dict]]: with vcr.use_cassette( "tests/cassettes/test_sql_validator/fixture_validator_pass_with_warning.yaml", match_on=["uri", "method", "raw_body"], filter_headers=["Authorization"], record_mode=record_mode, ): # Move to dev mode to test conditional logic warning validator.client.update_workspace("eye_exam", "dev") validator.client.checkout_branch("eye_exam", "pytest") validator.build_project(selectors=["eye_exam/users__warn"]) results = validator.validate(mode="hybrid") yield validator, results
Example #13
Source File: validate.py From knitlib with GNU Lesser General Public License v3.0 | 5 votes |
def validate(): validate_file = file("knitting_pattern_sample.json", "rb") schema_file = file("knitting_pattern_schema.json", "rb") data = json.load(validate_file) schema = json.load(schema_file) jsonschema.validate(data, schema)
Example #14
Source File: test_batch_recognition.py From cloud-asr with Apache License 2.0 | 5 votes |
def assertResponseHasCorrectSchema(self, response): schema = { "type": "object", "properties": { "result": { "type": "array", "items": { "type": "object", "properties": { "alternative": { "type": "array", "items": { "type": "object", "properties": { "confidence": {"type": "number"}, "transcript": {"type": "string"}, }, "required": ["confidence", "transcript"], "additionalProperties": False, }, "minItems": 1, }, "final": {"type": "boolean"}, }, "required": ["alternative", "final"], "additionalProperties": False, }, "minItems": 1, }, "result_index": {"type": "number"}, "chunk_id": {"type": "string"}, "request_id": {"type": "string"}, }, "required": ["result", "result_index", "request_id"], "additionalProperties": False, } validationResult = validate(json.loads(response), schema) self.assertIsNone(validationResult, msg="Response has invalid schema")
Example #15
Source File: __init__.py From knitlib with GNU Lesser General Public License v3.0 | 5 votes |
def validate_dict(loaded_json_data): """Checks if a dict is a valid Knitpat format. Validates if a dict, loaded from a json file, is valid according to the Knitpat scheme. Returns: True if valid, False if not. """ try: jsonschema.validate(loaded_json_data, __SCHEMA_DICT) return True except Exception as e: logging.error(e) return False
Example #16
Source File: tensorflow_detection.py From BMW-TensorFlow-Inference-API-CPU with Apache License 2.0 | 5 votes |
def validate_json_configuration(self, data): with open(os.path.join('inference', 'ConfigurationSchema.json')) as f: schema = json.load(f) try: jsonschema.validate(data, schema) except Exception as e: raise InvalidModelConfiguration(e)
Example #17
Source File: validate.py From tcex with Apache License 2.0 | 5 votes |
def interactive(self): """Run in interactive mode.""" while True: line = sys.stdin.readline().strip() if line == 'quit': sys.exit() elif line == 'validate': self.check_syntax() self.check_imports() self.check_install_json() self.check_layout_json() self.print_json() # reset validation_data self.validation_data = self._validation_data
Example #18
Source File: Batch.py From pcocc with GNU General Public License v3.0 | 5 votes |
def client_cert(self): return self.ca_cert # Schema to validate the global pkey state in the key/value store
Example #19
Source File: utils.py From marvin-python-toolbox with Apache License 2.0 | 5 votes |
def validate_json(data, schema): if isinstance(data, str): data = from_json(data) if isinstance(schema, str): schema = from_json(schema) try: jsonschema.validate(data, schema) except jsonschema.ValidationError as e: raise InvalidJsonException(e.message)
Example #20
Source File: Batch.py From pcocc with GNU General Public License v3.0 | 5 votes |
def load(batch_config_file, batchid, batchname, default_batchname, proc_type, batchuser): """Factory function to initialize a batch manager""" try: stream = file(batch_config_file, 'r') batch_config = yaml.safe_load(stream) except yaml.YAMLError as err: raise InvalidConfigurationError(str(err)) except IOError as err: raise InvalidConfigurationError(str(err)) try: jsonschema.validate(batch_config, yaml.safe_load(batch_config_schema)) except jsonschema.exceptions.ValidationError as err: raise InvalidConfigurationError(str(err)) settings = batch_config['settings'] if batch_config['type'] == 'slurm': return SlurmManager( batchid, batchname, default_batchname, settings, proc_type, batchuser) elif batch_config['type'] == 'local': return LocalManager( batchid, batchname, default_batchname, settings, proc_type, batchuser) else: raise InvalidConfigurationError("Invalid batch manager type")
Example #21
Source File: Batch.py From pcocc with GNU General Public License v3.0 | 5 votes |
def __init__(self, error): super(KeyCredentialError, self).__init__( 'Keystore authentication error: ' + error) # Schema to validate batch.yaml config file
Example #22
Source File: patch.py From csvdiff with BSD 3-Clause "New" or "Revised" License | 5 votes |
def load(istream, strict=True): "Deserialize a patch object." try: diff = json.load(istream) if strict: jsonschema.validate(diff, SCHEMA) except ValueError: raise InvalidPatchError('patch is not valid JSON') except jsonschema.exceptions.ValidationError as e: raise InvalidPatchError(e.message) return diff
Example #23
Source File: patch.py From csvdiff with BSD 3-Clause "New" or "Revised" License | 5 votes |
def validate(diff): """ Check the diff against the schema, raising an exception if it doesn't match. """ return jsonschema.validate(diff, SCHEMA)
Example #24
Source File: patch.py From csvdiff with BSD 3-Clause "New" or "Revised" License | 5 votes |
def is_valid(diff): """ Validate the diff against the schema, returning True if it matches, False otherwise. """ try: validate(diff) except jsonschema.ValidationError: return False return True
Example #25
Source File: repositories.py From probe-scraper with Mozilla Public License 2.0 | 5 votes |
def parse(self, filename=None, glean_repo=None): self.validate(filename) repos = self._get_repos(filename) repos = [ Repository(name, definition) for name, definition in list(repos.items()) ] return self.filter_repos(repos, glean_repo)
Example #26
Source File: repositories.py From probe-scraper with Mozilla Public License 2.0 | 5 votes |
def validate(self, filename=None): repos = self._get_repos(filename) with open(REPOSITORIES_SCHEMA, 'r') as f: schema = json.load(f) jsonschema.validate(repos, schema)
Example #27
Source File: register.py From resolwe with Apache License 2.0 | 5 votes |
def valid(self, instance, schema): """Validate schema.""" try: jsonschema.validate(instance, schema) except jsonschema.exceptions.ValidationError as ex: self.stderr.write( " VALIDATION ERROR: {}".format( instance["name"] if "name" in instance else "" ) ) self.stderr.write(" path: {}".format(ex.path)) self.stderr.write(" message: {}".format(ex.message)) self.stderr.write(" validator: {}".format(ex.validator)) self.stderr.write(" val. value: {}".format(ex.validator_value)) return False try: # Check that default values fit field schema. for field in ["input", "output", "schema"]: for schema, _, path in iterate_schema({}, instance.get(field, {})): if "default" in schema: validate_schema({schema["name"]: schema["default"]}, [schema]) except ValidationError: self.stderr.write(" VALIDATION ERROR: {}".format(instance["name"])) self.stderr.write( " Default value of field '{}' is not valid.".format(path) ) return False return True
Example #28
Source File: migration_ops.py From resolwe with Apache License 2.0 | 5 votes |
def __init__(self, process, field, schema, default=None): """Construct a process field add operation. :param process: Process slug :param field: Dot-separated field path, starting with the top-level database field name (must be either ``input`` or ``output``) :param schema: Field schema definition :param default: An operation that generates default values, which must be an instance of :class:`DataDefaultOperation` or its subclass """ self._raw_field = field self.field = field.split(".") if self.field[0] not in ("input", "output"): raise ValueError("Field path must start with either input or output") if len(self.field) < 2: raise ValueError("Field path must contain at least two levels") if len(self.field) != 2: # TODO: Support nested fields. raise NotImplementedError("Field path must contain exactly two levels") schema_type = self.field.pop(0) self.schema = schema jsonschema.validate([schema], FIELD_SCHEMA) if schema["name"] != self.field[-1]: raise ValueError("Field name in schema differs from field path") if not default and schema.get("required", True): raise ValueError("A required field must have a default") if default and not isinstance(default, DataDefaultOperation): raise TypeError("Default must be an instance of DataDefaultOperation") self.default = default super().__init__( process=process, schema_type=schema_type, field=field, schema=schema, default=default, )
Example #29
Source File: configuration.py From armory with MIT License | 5 votes |
def validate_config(config: dict) -> dict: """ Validates that a config matches the default JSON Schema """ schema = _load_schema() jsonschema.validate(instance=config, schema=schema) return config
Example #30
Source File: Batch.py From pcocc with GNU General Public License v3.0 | 5 votes |
def _validate_job_state(self, state): if state is None: job_alloc_state = {'jobs': {}, 'next_batchid': 1} elif isinstance(state, dict): job_alloc_state = state else: job_alloc_state = yaml.safe_load(state) schema = yaml.safe_load(local_job_allocation_schema) jsonschema.validate(job_alloc_state, schema) return job_alloc_state