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


Python schema.SchemaError方法代码示例

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


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

示例1: main

# 需要导入模块: import schema [as 别名]
# 或者: from schema import SchemaError [as 别名]
def main():
    """
    The main function for Skelebot CLI where the config is loaded,
    arguments are parsed, and commands are executed
    """

    try:
        env = get_env()
        config = yaml.loadConfig(env)
        parser = skeleParser.SkeleParser(config, env)
        executor.execute(config, parser)
    except SchemaError as error:
        print(SCHEMA_ERROR.format(error))
        sys.exit(1)
    except RuntimeError as error:
        print(ERROR.format(error))
        sys.exit(1) 
开发者ID:carsdotcom,项目名称:skelebot,代码行数:19,代码来源:skelebot.py

示例2: load

# 需要导入模块: import schema [as 别名]
# 或者: from schema import SchemaError [as 别名]
def load(cls, config):
        """Instantiate the Repository Class Object based on a config dict"""

        cls.validate(config)

        s3 = None
        artifactory = None
        if ("s3" in config):
            s3 = S3Repo.load(config["s3"])
        elif ("artifactory" in config):
            artifactory = ArtifactoryRepo.load(config["artifactory"])
        else:
            raise SchemaError(None, "Repository must contain 's3' or 'artifactory' config")

        artifactDicts = config["artifacts"]
        artifacts = []
        for artifact in artifactDicts:
            newArtifact = Artifact.load(artifact)
            artifacts.append(newArtifact)

        return cls(artifacts, s3, artifactory) 
开发者ID:carsdotcom,项目名称:skelebot,代码行数:23,代码来源:repository.py

示例3: test_validate_mising

# 需要导入模块: import schema [as 别名]
# 或者: from schema import SchemaError [as 别名]
def test_validate_mising(self):
        artifactoryDict = copy.deepcopy(self.artifactoryDict)
        del artifactoryDict['url']
        del artifactoryDict['repo']
        del artifactoryDict['path']

        try:
            sb.components.artifactory.Artifactory.validate(artifactoryDict)
        except SchemaError as error:
            self.assertEqual(error.code, "Missing keys: 'path', 'repo', 'url'")

        artifactDict = copy.deepcopy(self.artifactDict)
        del artifactDict['name']
        del artifactDict['file']

        try:
            sb.components.artifactory.Artifact.validate(artifactDict)
        except SchemaError as error:
            self.assertEqual(error.code, "Missing keys: 'file', 'name'") 
开发者ID:carsdotcom,项目名称:skelebot,代码行数:21,代码来源:test_components_artifactory.py

示例4: Scm

# 需要导入模块: import schema [as 别名]
# 或者: from schema import SchemaError [as 别名]
def Scm(spec, env, overrides, recipeSet):
    # resolve with environment
    spec = { k : ( env.substitute(v, "checkoutSCM::"+k) if isinstance(v, str) else v)
        for (k, v) in spec.items() }

    # apply overrides before creating scm instances. It's possible to switch the Scm type with an override..
    matchedOverrides = []
    for override in overrides:
        matched, spec = override.mangle(spec, env)
        if matched:
            matchedOverrides.append(override)

    # check schema again if any SCM override matched
    if matchedOverrides:
        try:
            recipeSet.SCM_SCHEMA.validate({ k:v for k,v in spec.items()
                if k != '__source' and k != 'recipe' })
        except schema.SchemaError as e:
            raise ParseError("Error validating SCM after applying scmOverrides: {}".format(str(e)))

    # create scm instance
    return getScm(spec, matchedOverrides, recipeSet) 
开发者ID:BobBuildTool,项目名称:bob,代码行数:24,代码来源:input.py

示例5: auditFromData

# 需要导入模块: import schema [as 别名]
# 或者: from schema import SchemaError [as 别名]
def auditFromData(data):
    typ = data.get("type")
    if typ == "git":
        scm = GitAudit
    elif typ == "import":
        scm = ImportAudit
    elif typ == "url":
        scm = UrlAudit
    elif typ == "svn":
        scm = SvnAudit
    else:
        from ..errors import ParseError
        raise ParseError("Cannot handle SCM: " + str(typ))

    try:
        data = scm.SCHEMA.validate(data)
        return scm.fromData(data)
    except schema.SchemaError as e:
        from ..errors import ParseError
        raise ParseError("Error while validating audit: {} {}".format(str(e), str(data))) 
开发者ID:BobBuildTool,项目名称:bob,代码行数:22,代码来源:__init__.py

示例6: test_same_name_func

# 需要导入模块: import schema [as 别名]
# 或者: from schema import SchemaError [as 别名]
def test_same_name_func():
    """`name_func` should be used for generating method names."""

    @testsuite
    class MySuite(object):
        @testcase(
            parameters=(("foo", "bar"), ("alpha", "beta")),
            name_func=lambda func_name, kwargs: "same_name",
        )
        def sample_test(self, env, result, a, b):
            pass

        @testcase(
            parameters=(("foo", "bar"), ("alpha", "beta")),
            name_func=lambda func_name, kwargs: "same_name",
        )
        def other_test(self, env, result, a, b):
            pass

    with pytest.raises(SchemaError):
        MultiTest(name="abc", suites=[MySuite()]) 
开发者ID:Morgan-Stanley,项目名称:testplan,代码行数:23,代码来源:test_parametrization.py

示例7: param

# 需要导入模块: import schema [as 别名]
# 或者: from schema import SchemaError [as 别名]
def param(self, schema):
        """A decorator for validate request data"""
        if not isinstance(schema, collections.Mapping):
            raise TypeError('schema must be Mapping')
        # add error message
        schema = {k: And(v, error='%s invalid' % k)
                  for k, v in schema.items()}
        validate = Schema(schema).validate

        def decorator(f):
            @functools.wraps(f)
            def wrapper(*args, **kwargs):
                data = self.get_data()
                try:
                    data = validate(data)
                except SchemaError as ex:
                    self.handle_error(str(ex))
                kwargs.update(data)
                return f(*args, **kwargs)
            return wrapper
        return decorator 
开发者ID:NetEaseGame,项目名称:git-webhook,代码行数:23,代码来源:validator.py

示例8: validate_extras

# 需要导入模块: import schema [as 别名]
# 或者: from schema import SchemaError [as 别名]
def validate_extras(self, data, algo_type):
        builtin_key = self.builtin_keys[algo_type]
        if (builtin_key in data) and (set(data.keys()) & self.customized_keys):
            raise SchemaError('{} and {} cannot be specified at the same time.'.format(
                builtin_key, set(data.keys()) & self.customized_keys
            ))

        if self.missing_customized_keys(data) and builtin_key not in data:
            raise SchemaError('Either customized {} ({}) or builtin {} ({}) must be set.'.format(
                algo_type, self.customized_keys, algo_type, builtin_key))

        if not self.missing_customized_keys(data):
            class_file_name = os.path.join(data['codeDir'], data['classFileName'])
            if not os.path.isfile(class_file_name):
                raise SchemaError('classFileName {} not found.'.format(class_file_name))

        builtin_name = data.get(builtin_key)
        class_args = data.get('classArgs')
        self.validate_class_args(class_args, algo_type, builtin_name) 
开发者ID:microsoft,项目名称:nni,代码行数:21,代码来源:config_schema.py

示例9: validate_kubeflow_operators

# 需要导入模块: import schema [as 别名]
# 或者: from schema import SchemaError [as 别名]
def validate_kubeflow_operators(self, experiment_config):
        '''Validate whether the kubeflow operators are valid'''
        if experiment_config.get('kubeflowConfig'):
            if experiment_config.get('kubeflowConfig').get('operator') == 'tf-operator':
                if experiment_config.get('trial').get('master') is not None:
                    raise SchemaError('kubeflow with tf-operator can not set master')
                if experiment_config.get('trial').get('worker') is None:
                    raise SchemaError('kubeflow with tf-operator must set worker')
            elif experiment_config.get('kubeflowConfig').get('operator') == 'pytorch-operator':
                if experiment_config.get('trial').get('ps') is not None:
                    raise SchemaError('kubeflow with pytorch-operator can not set ps')
                if experiment_config.get('trial').get('master') is None:
                    raise SchemaError('kubeflow with pytorch-operator must set master')

            if experiment_config.get('kubeflowConfig').get('storage') == 'nfs':
                if experiment_config.get('kubeflowConfig').get('nfs') is None:
                    raise SchemaError('please set nfs configuration!')
            elif experiment_config.get('kubeflowConfig').get('storage') == 'azureStorage':
                if experiment_config.get('kubeflowConfig').get('azureStorage') is None:
                    raise SchemaError('please set azureStorage configuration!')
            elif experiment_config.get('kubeflowConfig').get('storage') is None:
                if experiment_config.get('kubeflowConfig').get('azureStorage'):
                    raise SchemaError('please set storage type!') 
开发者ID:microsoft,项目名称:nni,代码行数:25,代码来源:config_schema.py

示例10: validate_annotation_content

# 需要导入模块: import schema [as 别名]
# 或者: from schema import SchemaError [as 别名]
def validate_annotation_content(self, experiment_config, spec_key, builtin_name):
        '''
        Valid whether useAnnotation and searchSpacePath is coexist
        spec_key: 'advisor' or 'tuner'
        builtin_name: 'builtinAdvisorName' or 'builtinTunerName'
        '''
        if experiment_config.get('useAnnotation'):
            if experiment_config.get('searchSpacePath'):
                raise SchemaError('If you set useAnnotation=true, please leave searchSpacePath empty')
        else:
            # validate searchSpaceFile
            if experiment_config[spec_key].get(builtin_name) == 'NetworkMorphism':
                return
            if experiment_config[spec_key].get(builtin_name):
                if experiment_config.get('searchSpacePath') is None:
                    raise SchemaError('Please set searchSpacePath!')
                self.validate_search_space_content(experiment_config) 
开发者ID:microsoft,项目名称:nni,代码行数:19,代码来源:config_schema.py

示例11: parse_config

# 需要导入模块: import schema [as 别名]
# 或者: from schema import SchemaError [as 别名]
def parse_config(
    file_path: Path, config_schema: Optional[schema.Schema] = None
) -> Config:
    try:
        contents = file_path.read_text()
    except OSError as os_error:
        raise tsrc.InvalidConfig(file_path, os_error)
    try:
        yaml = ruamel.yaml.YAML(typ="safe", pure=True)
        parsed = yaml.load(contents)
    except ruamel.yaml.error.YAMLError as yaml_error:
        raise tsrc.InvalidConfig(file_path, yaml_error)
    if config_schema:
        try:
            config_schema.validate(parsed)
        except schema.SchemaError as schema_error:
            raise tsrc.InvalidConfig(file_path, schema_error)
    return Config(parsed) 
开发者ID:TankerHQ,项目名称:tsrc,代码行数:20,代码来源:config.py

示例12: check

# 需要导入模块: import schema [as 别名]
# 或者: from schema import SchemaError [as 别名]
def check(conf_schema, conf):
    """
    Validates a user-supplied JSON vs a defined schema.

    Arguments:
        conf_schema: The Schema object that defines the required structure.
        conf: The user-supplied schema to validate against the required structure.
    Returns:
        Boolean: The decision about whether the JSON meets expected Schema requirements
    """
    try:
        conf_schema.validate(conf)
        return True
    except SchemaError as schema_error:
        try:
            # workarounds for Schema's logging approach
            print(schema_error.autos[0])
            detailed_error_message = schema_error.autos[2]
            print(detailed_error_message.split(" in {'")[0])
            # for error in schema_error.autos:
        except:  # pylint: disable=bare-except
            logger.critical(schema_error)
        return False 
开发者ID:salesforce,项目名称:policy_sentry,代码行数:25,代码来源:validate.py

示例13: validate_condition_block

# 需要导入模块: import schema [as 别名]
# 或者: from schema import SchemaError [as 别名]
def validate_condition_block(condition_block):
    """
    Validates the format of the condition block that should be supplied in the template.

    Arguments:
        condition_block: {"condition_key_string": "ec2:ResourceTag/purpose", "condition_type_string": "StringEquals", "condition_value": "test"}
    Returns:
        Boolean: The decision
    """

    # TODO: Validate that the values are legit somehow
    CONDITION_BLOCK_SCHEMA = Schema(
        {
            "condition_key_string": And(Use(str)),
            "condition_type_string": And(Use(str)),
            "condition_value": And(Use(str)),
        }
    )
    try:
        CONDITION_BLOCK_SCHEMA.validate(condition_block)
        # TODO: Try to validate whether or not the condition keys are legit
        return True
    except SchemaError as s_e:
        logger.warning(s_e)
        return False 
开发者ID:salesforce,项目名称:policy_sentry,代码行数:27,代码来源:validate.py

示例14: hard_validation

# 需要导入模块: import schema [as 别名]
# 或者: from schema import SchemaError [as 别名]
def hard_validation(inputs, errors):
    """
    Parse input data for the hard validation.

    :param inputs:
        Input data.
    :type inputs: dict

    :param errors:
        Errors container.
    :type errors: dict

    :return:
        Parsed input data and errors container.
    :rtype: dict, dict
    """
    from schema import SchemaError
    for k, v in sh.stack_nested_keys(inputs, depth=3):
        for c, msg in _hard_validation(v, *k):
            sh.get_nested_dicts(errors, *k)[c] = SchemaError([], [msg])
    return inputs, errors 
开发者ID:JRCSTU,项目名称:CO2MPAS-TA,代码行数:23,代码来源:hard.py

示例15: validate

# 需要导入模块: import schema [as 别名]
# 或者: from schema import SchemaError [as 别名]
def validate(data):
        if isinstance(data, str) and data == 'EMPTY':
            return sh.EMPTY

        try:
            empty = not (data or data == 0)
        except ValueError:
            empty = np.isnan(data).all()

        if empty:
            return sh.NONE
        else:
            raise SchemaError('%r is not empty' % data)


# noinspection PyUnusedLocal 
开发者ID:JRCSTU,项目名称:CO2MPAS-TA,代码行数:18,代码来源:schema.py


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