当前位置: 首页>>代码示例>>Python>>正文


Python jsonschema.validate方法代码示例

本文整理汇总了Python中jsonschema.validate方法的典型用法代码示例。如果您正苦于以下问题:Python jsonschema.validate方法的具体用法?Python jsonschema.validate怎么用?Python jsonschema.validate使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在jsonschema的用法示例。


在下文中一共展示了jsonschema.validate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _test_validate

# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import validate [as 别名]
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']) 
开发者ID:airshipit,项目名称:drydock,代码行数:24,代码来源:test_schema_validation.py

示例2: validator_fail_with_warning

# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import validate [as 别名]
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 
开发者ID:spectacles-ci,项目名称:spectacles,代码行数:18,代码来源:test_sql_validator.py

示例3: validator_warn

# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import validate [as 别名]
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 
开发者ID:spectacles-ci,项目名称:spectacles,代码行数:18,代码来源:test_sql_validator.py

示例4: test_pydist

# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import validate [as 别名]
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" 
开发者ID:jpush,项目名称:jbox,代码行数:26,代码来源:test_basic.py

示例5: load_repos

# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import validate [as 别名]
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 
开发者ID:cea-hpc,项目名称:pcocc,代码行数:24,代码来源:ObjectStore.py

示例6: _read_meta

# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import validate [as 别名]
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 
开发者ID:cea-hpc,项目名称:pcocc,代码行数:24,代码来源:ObjectStore.py

示例7: _validate_repo_config

# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import validate [as 别名]
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)) 
开发者ID:cea-hpc,项目名称:pcocc,代码行数:19,代码来源:ObjectStore.py

示例8: password_is_complex

# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import validate [as 别名]
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 
开发者ID:rsmusllp,项目名称:king-phisher,代码行数:26,代码来源:utilities.py

示例9: validate_json_schema

# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import validate [as 别名]
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) 
开发者ID:rsmusllp,项目名称:king-phisher,代码行数:18,代码来源:utilities.py

示例10: test_pydist

# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import validate [as 别名]
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" 
开发者ID:abhisuri97,项目名称:auto-alt-text-lambda-api,代码行数:27,代码来源:test_basic.py

示例11: _validate_config

# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import validate [as 别名]
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}") 
开发者ID:albertodonato,项目名称:query-exporter,代码行数:13,代码来源:config.py

示例12: test_scenarios

# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import validate [as 别名]
def test_scenarios(log, name, scenario):
    expect = list(map(lambda item: tuple(item), scenario.pop('report')))
    actual = log(validate(**scenario))
    assert actual == expect 
开发者ID:frictionlessdata,项目名称:goodtables-py,代码行数:6,代码来源:test_scenarios.py

示例13: test_scenarios_return_valid_reports

# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import validate [as 别名]
def test_scenarios_return_valid_reports(name, scenario, report_schema):
    del scenario['report']
    report = validate(**scenario)
    jsonschema.validate(report, report_schema) 
开发者ID:frictionlessdata,项目名称:goodtables-py,代码行数:6,代码来源:test_scenarios.py

示例14: validate_tags

# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import validate [as 别名]
def validate_tags(self, data):
        for key, value in data.items():
            if value is None:  # use NoneType to unset an item
                continue

            # split key into a prefix and name
            if '/' in key:
                prefix, name = key.split('/')
            else:
                prefix, name = None, key

            # validate optional prefix
            if prefix:
                if len(prefix) > 253:
                    raise serializers.ValidationError(
                        "Tag key prefixes must 253 characters or less.")

                for part in prefix.split('/'):
                    if not re.match(TAGVAL_MATCH, part):
                        raise serializers.ValidationError(
                            "Tag key prefixes must be DNS subdomains.")

            # validate required name
            if not re.match(TAGVAL_MATCH, name):
                raise serializers.ValidationError(
                    "Tag keys must be alphanumeric or \"-_.\", and 1-63 characters.")

            # validate value if it isn't empty
            if value and not re.match(TAGVAL_MATCH, str(value)):
                raise serializers.ValidationError(
                    "Tag values must be alphanumeric or \"-_.\", and 1-63 characters.")

        return data 
开发者ID:deis,项目名称:controller,代码行数:35,代码来源:serializers.py

示例15: validate_healthcheck

# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import validate [as 别名]
def validate_healthcheck(self, data):
        for procType, healthcheck in data.items():
            if healthcheck is None:
                continue
            for key, value in healthcheck.items():
                if value is None:
                    continue
                if key not in ['livenessProbe', 'readinessProbe']:
                    raise serializers.ValidationError(
                        "Healthcheck keys must be either livenessProbe or readinessProbe")
                try:
                    jsonschema.validate(value, PROBE_SCHEMA)
                except jsonschema.ValidationError as e:
                    raise serializers.ValidationError(
                        "could not validate {}: {}".format(value, e.message))

            # http://kubernetes.io/docs/api-reference/v1/definitions/#_v1_probe
            # liveness only supports successThreshold=1, no other value
            # This is not in the schema since readiness supports other values
            threshold = jmespath.search('livenessProbe.successThreshold', healthcheck)
            if threshold is not None and threshold != 1:
                raise serializers.ValidationError(
                    'livenessProbe successThreshold can only be 1'
                )

        return data 
开发者ID:deis,项目名称:controller,代码行数:28,代码来源:serializers.py


注:本文中的jsonschema.validate方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。