• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python core.Core类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pykwalify.core.Core的典型用法代码示例。如果您正苦于以下问题:Python Core类的具体用法?Python Core怎么用?Python Core使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



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

示例1: run

    def run(self, event, context):

        gh_hook = json.loads(event['body'])
        repo = gh_hook['repository']['full_name']
        sha = gh_hook['pull_request']['head']['sha']

        try:
            hooks_yml = get_github().get_repo(repo, lazy=True).get_file_contents('.hooks.yml', ref=sha)
            logger.info("Fetched .hooks.yml from repo {}".format(repo))
        except github.GithubException:
            logger.error("Missig .hooks.yml on repo {}".format(repo))
            send_status(event, context, gh_hook, self.configname, 'success', ".hooks.yml not present in branch")
            return

        try:
            hook_config = yaml.safe_load(hooks_yml.decoded_content)
            logger.info("Basic yml validation passed")
        except Exception as e:
            logger.error("Failed to decode hook yaml: " + e.message)
            send_status(event, context, gh_hook, self.configname, 'failure', "Could not decode branch .hooks.yml")
            return

        logger.info("Advanced schema validation")
        c = Core(source_data=hook_config,
                 schema_files=[os.path.join(os.path.dirname(__file__), "..", "hooks.schema.yml")])
        c.validate(raise_exception=False)
        vc = len(c.validation_errors)
        if vc > 0:
            for err in c.validation_errors:
                logger.error(" - {}".format(err))
            send_status(event, context, gh_hook, self.configname, 'failure', ".hooks.yml has {} validation errors; see log".format(vc))
            return

        send_status(event, context, gh_hook, self.configname, 'success', ".hooks.yml present and valid")
开发者ID:chuyskywalker,项目名称:aws-lambda-github-webhook,代码行数:34,代码来源:hooks_schema.py


示例2: _validate_cfg

    def _validate_cfg(self):
        """
        Open and parse the YAML configuration file and ensure it matches
        our Schema for a Dogen configuration.
        """
        # Fail early if descriptor file is not found
        if not os.path.exists(self.descriptor):
            raise Error("Descriptor file '%s' could not be found. Please make sure you specified correct path." % self.descriptor)

        schema_path = os.path.join(self.pwd, "schema", "kwalify_schema.yaml")
        schema = {}
        with open(schema_path, 'r') as fh:
            schema = yaml.safe_load(fh)

        if schema is None:
            raise Error("couldn't read a valid schema at %s" % schema_path)

        for plugin in self.plugins:
            plugin.extend_schema(schema)

        with open(self.descriptor, 'r') as stream:
            self.cfg = yaml.safe_load(stream)

        c = Core(source_data=self.cfg, schema_data=schema)
        try:
            c.validate(raise_exception=True)
        except SchemaError as e:
            raise Error(e)
开发者ID:jboss-dockerfiles,项目名称:dogen,代码行数:28,代码来源:generator.py


示例3: test_files_with_unicode_content_success

    def test_files_with_unicode_content_success(self):
        """
        These tests should pass with no exception raised
        """
        _pass_tests = [
            # Test mapping with unicode key and value
            u"1s.yaml",
            # Test unicode filename
            u"2så.yaml",
            # Test sequence with unicode keys
            u"3s.yaml",
        ]

        for passing_test_files in _pass_tests:
            f = unicode(self.f(passing_test_files))

            with open(f, "r") as stream:
                yaml_data = yaml.load(stream)
                data = yaml_data["data"]
                schema = yaml_data["schema"]

            try:
                print(u"Running test files: {}".format(f))
                c = Core(source_data=data, schema_data=schema)
                c.validate()
                compare(c.validation_errors, [], prefix="No validation errors should exist...")
            except Exception as e:
                print(u"ERROR RUNNING FILES: {}".format(f))
                raise e

            # This serve as an extra schema validation that tests more complex structures then testrule.py do
            compare(c.root_rule._schema_str, schema, prefix=u"Parsed rules is not correct, something have changed... files : {}".format(f))
开发者ID:hideaki-t,项目名称:pykwalify,代码行数:32,代码来源:test_unicode.py


示例4: test_files_with_unicode_content_failing

    def test_files_with_unicode_content_failing(self):
        """
        These tests should fail with the specified exception
        """
        _fail_tests = [
            # Test mapping with unicode key and value but wrong type
            (u"1f.yaml", SchemaError),
            # Test unicode filename with validation errors
            (u"2få.yaml", SchemaError),
            # Test unicode data inside seq but wrong type
            (u"3f.yaml", SchemaError),
        ]

        for failing_test, exception_type in _fail_tests:
            # f = self.f(os.path.join("fail", failing_test))
            f = unicode(self.f(failing_test))

            with open(f, "r") as stream:
                yaml_data = yaml.load(stream)
                data = yaml_data["data"]
                schema = yaml_data["schema"]
                errors = yaml_data["errors"]

            try:
                print(u"Running test files: {}".format(f))
                c = Core(source_data=data, schema_data=schema)
                c.validate()
            except exception_type:
                pass  # OK
            else:
                raise AssertionError(u"Exception {} not raised as expected... FILES: {} : {}".format(exception_type, exception_type))

            compare(sorted(c.validation_errors), sorted(errors), prefix=u"Wrong validation errors when parsing files : {}".format(f))
开发者ID:hideaki-t,项目名称:pykwalify,代码行数:33,代码来源:test_unicode.py


示例5: load_config

def load_config(path):

    """validates, loads and configures the yaml document at the specified path

    :param path: the path to the file
    :return: the parsed yaml document
    :raises SchemaError: if the yaml document does not validate
    """

    validator = Core(source_file=path, schema_data=config_schema)
    validator.validate(raise_exception=True)

    pattern = re.compile(r'^(.*)<%= ENV\[\'(.*)\'\] %>(.*)$')
    yaml.add_implicit_resolver('!env_regex', pattern)

    def env_regex(loader, node):
        value = loader.construct_scalar(node)
        front, variable_name, back = pattern.match(value).groups()
        return str(front) + os.environ[variable_name] + str(back)

    yaml.add_constructor('!env_regex', env_regex)

    with open(path, 'r') as stream:
        doc = yaml.load(stream)
        return doc
开发者ID:datawire,项目名称:presence,代码行数:25,代码来源:presence.py


示例6: incoming

def incoming(event, context):
    """
    Validate the incoming event from the API gateway
    """

    print json.dumps(event)  # not logger.info() so it doesn't show up in logview itself :)

    # validate the secret
    if not validate_secret(event['headers'].get('X-Hub-Signature'), event['body']):
        return {"body": json.dumps({"error": "invalid signature"}), "statusCode": 403}

    # Get the hook info
    try:
        hookdata = json.loads(event['body'])
    except Exception:
        logger.error("Failed to decode json")
        return {"body": json.dumps({"error": "json decode failure"}), "statusCode": 500}

    # this will only work, for now, with hooks that include repo information
    if 'repository' not in hookdata:
        logger.error("No repository in the hook, no processing")
        return {"body": json.dumps({"error": "unsupported hook type; missing repository information"}), "statusCode": 501}

    repo = hookdata['repository']['full_name']

    # Now, we fetch the config from the repo to see what hooks we should trigger
    try:
        hooks_yml = get_github().get_repo(repo, lazy=True).get_file_contents('.hooks.yml')
        logger.info("Fetched .hooks.yml from repo {}".format(repo))
    except github.GithubException:
        logger.error("Missig .hooks.yml on repo {}".format(repo))
        return {"body": json.dumps({"error": "no .hooks.yml present"}), "statusCode": 501}

    try:
        hook_config = yaml.safe_load(hooks_yml.decoded_content)
    except Exception:
        logger.error("Failed to decode hook yaml")
        return {"body": json.dumps({"error": "hook yaml failure"}), "statusCode": 500}

    # Schema based validation
    c = Core(source_data=hook_config, schema_files=[os.path.join(os.path.dirname(__file__), "..", "hooks.schema.yml")])
    c.validate(raise_exception=False)
    if len(c.validation_errors) > 0:
        logger.error(c.validation_errors)
        return {"body": json.dumps({"error": "invalid hooks configuration"}), "statusCode": 501}

    ghevent = event['headers'].get('X-GitHub-Event', '')

    # Check hooks!
    logger.info("Qualifying checks:")
    for name, check in all_checks.get_all_checks().iteritems():
        check_config = check.qualify(ghevent, hookdata, hook_config)
        if check_config != False: # use boolean in case of "empty" configs
            logger.info("- {} passed qualify, invoking secondary call".format(name))
            invoke_secondary(name, check_config, event)
        else:
            logger.info("- {} did not qualify, skipping".format(name))

    # all done!
    return {"body": json.dumps({"message": "Thanks"}), "statusCode": 200}
开发者ID:chuyskywalker,项目名称:aws-lambda-github-webhook,代码行数:60,代码来源:incoming.py


示例7: load

    def load(self, config_file):
        """Load configuration from config_file."""
        with resource_stream(__name__, 'config-schema.yaml') as schema_stream:
            schema = yaml.load(schema_stream)

        core = Core(source_file=config_file, schema_data=schema)
        self.config = core.validate(raise_exception=True)
开发者ID:dtaylor84,项目名称:pysnapsync,代码行数:7,代码来源:snapsync.py


示例8: check_schema_test

def check_schema_test(opts, file):
    logging.info("check schema...: %s" % file)
    try:
        c = Core(source_file=file, schema_files=[opts.yaml_schema])
        c.validate(raise_exception=True)
    except SchemaError, e:
        print "check schema: %-80s  %s" % (file, RET_ERROR)
        raise
开发者ID:CingHu,项目名称:lagopus,代码行数:8,代码来源:ds_test.py


示例9: validate_result

def validate_result(data):
    try:
        validator = Core(source_data=data, schema_data=result_schema)
        validator.validate(raise_exception=True)
    except SchemaError as se:
        raise PresenceError(se)

    return data
开发者ID:datawire,项目名称:presence,代码行数:8,代码来源:presence.py


示例10: validate_config

 def validate_config(self):
     try:
         c = Core(source_file="/Users/JohnS5/dev/replication_manager/src/webapp/bdr_app.yml",
             schema_files=['/Users/JohnS5/dev/replication_manager/src/webapp/schema.yml'])
         return c.validate(raise_exception=True)
     except Exception as e:
         print "LOG: ERROR: config file is not valid"
         print e
         return None
开发者ID:sebinjohn,项目名称:replication_manager,代码行数:9,代码来源:config.py


示例11: validate_with_schema

def validate_with_schema(source_data, schema_file):
    core = Core(source_data=source_data, schema_files=[schema_file])
    try:
        core.validate(raise_exception=True)
    except Exception as error:
        if len(core.errors) > 0:
            show_validation_errors(source_data, core.errors)
        else:
            raise error
开发者ID:piranha,项目名称:osgameclones,代码行数:9,代码来源:_ext.py


示例12: load

 def load(self, validate=True):
     schema_file = os.path.join(sys._MEIPASS, 'schema.yml') \
         if hasattr(sys, '_MEIPASS') else self._default_schema_path
     try:
         self._yaml = anyconfig.load(self.path, ignore_missing=False)
     except FileNotFoundError:
         panic('ERROR - %s configuration file does not exist' % self.path)
     if validate:
         validator = Core(source_file=self.path, schema_files=[schema_file])
         validator.validate(raise_exception=True)
开发者ID:rabbitstack,项目名称:fibratus,代码行数:10,代码来源:config.py


示例13: check_schema_test

def check_schema_test(opts, file):
    logging.info("check schema...: %s" % file)
    try:
        c = Core(source_file=file, schema_files=[opts.yaml_schema])
        c.validate(raise_exception=True)
    except SchemaError as e:
        six.print_("check schema: %-80s  ERROR" % file)
        raise
    else:
        six.print_("check schema: %-80s  OK" % file)
开发者ID:1514louluo,项目名称:lagopus,代码行数:10,代码来源:lagopus_test.py


示例14: validate_config_yaml

def validate_config_yaml(package_name):
  """Check that an integration's config.yaml file has a valid schema

  Raises:
    Exception if the config.yaml file has an improper schema
  """
  resource_path = os.path.join('schema_files', 'config_schema.yaml')
  file_path = pkg_resources.resource_filename(resource_package, resource_path)
  schema_validator = Core(source_file=os.path.join(package_name, 'config.yaml'), schema_files=[file_path])
  schema_validator.validate(raise_exception=True)
开发者ID:optimizely,项目名称:optimizely_dev_tools,代码行数:10,代码来源:validate.py


示例15: test_validation_error_but_not_raise_exception

    def test_validation_error_but_not_raise_exception(self):
        """
        Test that if 'raise_exception=False' when validating that no exception is raised.

        Currently file 2a.yaml & 2b.yaml is designed to cause exception.
        """
        c = Core(source_file=self.f("cli", "2a.yaml"), schema_files=[self.f("cli", "2b.yaml")])
        c.validate(raise_exception=False)

        assert c.validation_errors == ["Value: 1 is not of type 'str' : /0", "Value: 2 is not of type 'str' : /1", "Value: 3 is not of type 'str' : /2"]
开发者ID:huanghao,项目名称:pykwalify,代码行数:10,代码来源:testcore.py


示例16: test_files_with_unicode_content_failing

    def test_files_with_unicode_content_failing(self, tmpdir):
        """
        These tests should fail with the specified exception
        """
        # To trigger schema exception we must pass in a source file
        fail_data_2f_yaml = {
            'schema': {
                'type': 'map',
                'mapping': {
                    'msg': {
                        'type': 'int',
                    },
                }
            },
            'data': {
                'msg': 'Foobar',
            },
            'errors': ["Value 'Foobar' is not of type 'int'. Path: '/msg'"]
        }

        source_f = tmpdir.join(u"2få.json")
        source_f.write(yaml.safe_dump(fail_data_2f_yaml, allow_unicode=True))

        _fail_tests = [
            # Test mapping with unicode key and value but wrong type
            (u"1f.yaml", SchemaError),
            # Test unicode filename with validation errors.
            # It is not possible to package a file with unicode characters
            # like åäö in the filename in some python versions.
            # Mock a file with åäö during testing to properly simulate this again.
            (unicode(source_f), SchemaError),
            # Test unicode data inside seq but wrong type
            (u"3f.yaml", SchemaError),
        ]

        for failing_test, exception_type in _fail_tests:
            f = self.f(failing_test)

            with open(f, "r") as stream:
                yaml_data = yaml.safe_load(stream)
                data = yaml_data["data"]
                schema = yaml_data["schema"]
                errors = yaml_data["errors"]

            try:
                print(u"Running test files: {0}".format(f))
                c = Core(source_data=data, schema_data=schema)
                c.validate()
            except exception_type:
                pass  # OK
            else:
                raise AssertionError(u"Exception {0} not raised as expected... FILES: {1} : {2}".format(exception_type, exception_type))

            compare(sorted(c.validation_errors), sorted(errors), prefix=u"Wrong validation errors when parsing files : {0}".format(f))
开发者ID:Grokzen,项目名称:pykwalify,代码行数:54,代码来源:test_unicode.py


示例17: test_component_data_valid

def test_component_data_valid():
    """ Check that the content of data fits with masonry schema v2 """
    validator = Core(source_data={}, schema_data=get_schema())
    for component_file in iglob('*/component.yaml'):
        print(component_file)
        source_data = yaml.load(open(component_file))
        validator.source = source_data
        try:
            validator.validate(raise_exception=True)
        except:
            assert False, "Error found in: {0}".format(component_file)
开发者ID:GSA-Jared,项目名称:cg-compliance,代码行数:11,代码来源:test_data_valid.py


示例18: test_files_with_unicode_content_success

    def test_files_with_unicode_content_success(self, tmpdir):
        """
        These tests should pass with no exception raised
        """
        fail_data_2s_yaml = {
            'schema': {
                'type': 'map',
                'mapping': {
                    'msg': {
                        'type': 'int',
                    },
                }
            },
            'data': {
                'msg': 123,
            },
            'errors': []
        }

        source_f = tmpdir.join(u"2så.json")
        source_f.write(yaml.safe_dump(fail_data_2s_yaml, allow_unicode=True))

        _pass_tests = [
            # Test mapping with unicode key and value
            u"1s.yaml",
            # # Test unicode filename.
            # It is not possible to package a file with unicode characters
            # like åäö in the filename in some python versions.
            # Mock a file with åäö during testing to properly simulate this again.
            unicode(source_f),
            # Test sequence with unicode keys
            u"3s.yaml",
        ]

        for passing_test_files in _pass_tests:
            f = self.f(passing_test_files)

            with open(f, "r") as stream:
                yaml_data = yaml.safe_load(stream)
                data = yaml_data["data"]
                schema = yaml_data["schema"]

            try:
                print(u"Running test files: {0}".format(f))
                c = Core(source_data=data, schema_data=schema)
                c.validate()
                compare(c.validation_errors, [], prefix="No validation errors should exist...")
            except Exception as e:
                print(u"ERROR RUNNING FILES: {0}".format(f))
                raise e

            # This serve as an extra schema validation that tests more complex structures then testrule.py do
            compare(c.root_rule.schema_str, schema, prefix=u"Parsed rules is not correct, something have changed... files : {0}".format(f))
开发者ID:Grokzen,项目名称:pykwalify,代码行数:53,代码来源:test_unicode.py


示例19: validate_fittings

def validate_fittings(file_path):
    with open(file_path, 'r') as document_stream:
        document = document_stream.read()
        for settings in yaml.load_all(document):
            logging.debug("Validating source data %s",
                         settings)

            c = Core(source_data=settings, schema_files=["schema.yaml"])
            try:
                c.validate(raise_exception=True)
            except pykwalify.errors.SchemaError as schema_error:
                logging.error("Validation of %s failed.", file_path)
                logging.error(schema_error)
开发者ID:DimensionDataResearch,项目名称:plumbery-contrib,代码行数:13,代码来源:validation.py


示例20: validate_parameters

def validate_parameters(parameters, kliko):
    """
    validate a set of parameters given a kliko definition

    args:
        parameters (dict): A structure that should follow the given kliko structure
        kliko (dict): A nested dict which defines the valid parameters in Kliko format

    returns:
        str: the parsed parameters

    raises:
        an exception if the string can't be parsed or is not in the defining valid parameters
    """
    schema = convert_to_parameters_schema(kliko)
    c = Core(source_data=parameters, schema_data=schema)
    c.validate(raise_exception=True)
    return True
开发者ID:gijzelaerr,项目名称:kliko,代码行数:18,代码来源:validate.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python pylab.absolute函数代码示例发布时间:2022-05-25
下一篇:
Python pykt.KyotoTycoon类代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap