當前位置: 首頁>>代碼示例>>Python>>正文


Python FormatChecker.checks方法代碼示例

本文整理匯總了Python中jsonschema.FormatChecker.checks方法的典型用法代碼示例。如果您正苦於以下問題:Python FormatChecker.checks方法的具體用法?Python FormatChecker.checks怎麽用?Python FormatChecker.checks使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在jsonschema.FormatChecker的用法示例。


在下文中一共展示了FormatChecker.checks方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_validate_with_format

# 需要導入模塊: from jsonschema import FormatChecker [as 別名]
# 或者: from jsonschema.FormatChecker import checks [as 別名]
def test_validate_with_format(app, db):
    """Test that validation can accept custom format rules."""
    with app.app_context():
        checker = FormatChecker()
        checker.checks("foo")(lambda el: el.startswith("foo"))
        data = {"bar": "foo", "$schema": {"properties": {"bar": {"format": "foo"}}}}

        # test record creation with valid data
        assert data == Record.create(data)
        record = Record.create(data, format_checker=checker)
        # test direct call to validate with valid data
        assert record.validate(format_checker=checker) is None
        # test commit with valid data
        record.commit(format_checker=checker)

        record["bar"] = "bar"
        # test direct call to validate with invalid data
        with pytest.raises(ValidationError) as excinfo:
            record.validate(format_checker=checker)
        assert "'bar' is not a 'foo'" in str(excinfo.value)
        # test commit with invalid data
        with pytest.raises(ValidationError) as excinfo:
            record.commit(format_checker=checker)
        assert "'bar' is not a 'foo'" in str(excinfo.value)

        data["bar"] = "bar"
        # test record creation with invalid data
        with pytest.raises(ValidationError) as excinfo:
            record = Record.create(data, format_checker=checker)
        assert "'bar' is not a 'foo'" in str(excinfo.value)
開發者ID:tiborsimko,項目名稱:invenio-records,代碼行數:32,代碼來源:test_api.py

示例2: test_it_can_register_checkers

# 需要導入模塊: from jsonschema import FormatChecker [as 別名]
# 或者: from jsonschema.FormatChecker import checks [as 別名]
 def test_it_can_register_checkers(self):
     checker = FormatChecker()
     checker.checks("boom")(boom)
     self.assertEqual(
         checker.checkers,
         dict(FormatChecker.checkers, boom=(boom, ()))
     )
開發者ID:Julian,項目名稱:jsonschema,代碼行數:9,代碼來源:test_format.py

示例3: test_it_can_register_checkers

# 需要導入模塊: from jsonschema import FormatChecker [as 別名]
# 或者: from jsonschema.FormatChecker import checks [as 別名]
 def test_it_can_register_checkers(self):
     checker = FormatChecker()
     checker.checks("new")(self.fn)
     self.assertEqual(
         checker.checkers,
         dict(FormatChecker.checkers, new=(self.fn, ()))
     )
開發者ID:BarnetteME1,項目名稱:DnD-stuff,代碼行數:9,代碼來源:test_format.py

示例4: is_valid_json

# 需要導入模塊: from jsonschema import FormatChecker [as 別名]
# 或者: from jsonschema.FormatChecker import checks [as 別名]
def is_valid_json(data, schema):
    checker = FormatChecker();
    # add the "interval" format
    checker.checks("interval")(parse_iso8601_interval)
    validator = Draft4Validator(schema, format_checker=checker)
    errors = []
    for error in validator.iter_errors(data):
        errors.append(error.message)
    return errors
開發者ID:metronotes-beta,項目名稱:metroblockd,代碼行數:11,代碼來源:util.py

示例5: test_format_error_causes_become_validation_error_causes

# 需要導入模塊: from jsonschema import FormatChecker [as 別名]
# 或者: from jsonschema.FormatChecker import checks [as 別名]
    def test_format_error_causes_become_validation_error_causes(self):
        checker = FormatChecker()
        checker.checks("boom", raises=ValueError)(boom)
        validator = Draft4Validator({"format": "boom"}, format_checker=checker)

        with self.assertRaises(ValidationError) as cm:
            validator.validate("BOOM")

        self.assertIs(cm.exception.cause, BOOM)
        self.assertIs(cm.exception.__cause__, BOOM)
開發者ID:Julian,項目名稱:jsonschema,代碼行數:12,代碼來源:test_format.py

示例6: test_format_error_causes_become_validation_error_causes

# 需要導入模塊: from jsonschema import FormatChecker [as 別名]
# 或者: from jsonschema.FormatChecker import checks [as 別名]
    def test_format_error_causes_become_validation_error_causes(self):
        checker = FormatChecker()
        checker.checks("foo", raises=ValueError)(self.fn)
        cause = self.fn.side_effect = ValueError()
        validator = Draft4Validator({"format": "foo"}, format_checker=checker)

        with self.assertRaises(ValidationError) as cm:
            validator.validate("bar")

        self.assertIs(cm.exception.__cause__, cause)
開發者ID:BarnetteME1,項目名稱:DnD-stuff,代碼行數:12,代碼來源:test_format.py

示例7: test_invalid_format_default_message

# 需要導入模塊: from jsonschema import FormatChecker [as 別名]
# 或者: from jsonschema.FormatChecker import checks [as 別名]
    def test_invalid_format_default_message(self):
        checker = FormatChecker(formats=())
        check_fn = mock.Mock(return_value=False)
        checker.checks("thing")(check_fn)

        schema = {"format" : "thing"}
        message = self.message_for("bla", schema, format_checker=checker)

        self.assertIn(repr("bla"), message)
        self.assertIn(repr("thing"), message)
        self.assertIn("is not a", message)
開發者ID:clarete,項目名稱:jsonschema,代碼行數:13,代碼來源:test_validators.py

示例8: test_it_catches_registered_errors

# 需要導入模塊: from jsonschema import FormatChecker [as 別名]
# 或者: from jsonschema.FormatChecker import checks [as 別名]
    def test_it_catches_registered_errors(self):
        checker = FormatChecker()
        checker.checks("boom", raises=type(BOOM))(boom)

        with self.assertRaises(FormatError) as cm:
            checker.check(instance=12, format="boom")

        self.assertIs(cm.exception.cause, BOOM)
        self.assertIs(cm.exception.__cause__, BOOM)

        # Unregistered errors should not be caught
        with self.assertRaises(type(BANG)):
            checker.check(instance="bang", format="boom")
開發者ID:Julian,項目名稱:jsonschema,代碼行數:15,代碼來源:test_format.py

示例9: test_it_catches_registered_errors

# 需要導入模塊: from jsonschema import FormatChecker [as 別名]
# 或者: from jsonschema.FormatChecker import checks [as 別名]
 def test_it_catches_registered_errors(self):
     checker = FormatChecker()
     checker.checks("foo", raises=ValueError)(self.fn)
     # Registered errors should be caught and turned into FormatErrors
     cause = ValueError()
     self.fn.side_effect = cause
     with self.assertRaises(FormatError) as cm:
         checker.check("bar", "foo")
     # Original exception should be attached to cause attribute
     self.assertIs(cm.exception.cause, cause)
     # Unregistered errors should not be caught
     self.fn.side_effect = AttributeError
     with self.assertRaises(AttributeError):
         checker.check("bar", "foo")
開發者ID:alexstrat,項目名稱:jsonschema,代碼行數:16,代碼來源:tests.py

示例10: test_it_catches_registered_errors

# 需要導入模塊: from jsonschema import FormatChecker [as 別名]
# 或者: from jsonschema.FormatChecker import checks [as 別名]
    def test_it_catches_registered_errors(self):
        checker = FormatChecker()
        cause = self.fn.side_effect = ValueError()

        checker.checks("foo", raises=ValueError)(self.fn)

        with self.assertRaises(FormatError) as cm:
            checker.check("bar", "foo")

        self.assertIs(cm.exception.cause, cause)
        self.assertIs(cm.exception.__cause__, cause)

        # Unregistered errors should not be caught
        self.fn.side_effect = AttributeError
        with self.assertRaises(AttributeError):
            checker.check("bar", "foo")
開發者ID:BarnetteME1,項目名稱:DnD-stuff,代碼行數:18,代碼來源:test_format.py

示例11: test_validate_with_format

# 需要導入模塊: from jsonschema import FormatChecker [as 別名]
# 或者: from jsonschema.FormatChecker import checks [as 別名]
def test_validate_with_format(app, db):
    """Test that validation can accept custom format rules."""
    with app.app_context():
        checker = FormatChecker()
        checker.checks('foo')(lambda el: el.startswith('foo'))
        record = Record.create({
            'bar': 'foo',
            '$schema': {
                'properties': {
                    'bar': {'format': 'foo'}
                }
            }
        })

        assert record.validate(format_checker=checker) is None

        record['bar'] = 'bar'

        with pytest.raises(ValidationError) as excinfo:
            record.validate(format_checker=checker)
        assert "'bar' is not a 'foo'" in str(excinfo.value)
開發者ID:hachreak,項目名稱:invenio-records,代碼行數:23,代碼來源:test_api.py

示例12: formatchecker_factory

# 需要導入模塊: from jsonschema import FormatChecker [as 別名]
# 或者: from jsonschema.FormatChecker import checks [as 別名]
def formatchecker_factory(**checkerdict):
    """Converts a dictionary of strings:checkers into a formatchecker object"""
    fc = FormatChecker()
    for format_name, checker in checkerdict.items():
        fc.checks(format_name)(checker)
    return fc
開發者ID:nesaro,項目名稱:pydsl,代碼行數:8,代碼來源:check.py

示例13: checker

# 需要導入模塊: from jsonschema import FormatChecker [as 別名]
# 或者: from jsonschema.FormatChecker import checks [as 別名]
def checker(ontology):
    modelname_checker = FormatChecker()
    # Pass the ontology object as a closure
    modelname_checker.checks("modelname", raises=ValidationError)(is_modelname(ontology))
    # Returns the checker after configuring it
    return modelname_checker
開發者ID:IvanJijon,項目名稱:detective.io,代碼行數:8,代碼來源:schema.py

示例14: Spec

# 需要導入模塊: from jsonschema import FormatChecker [as 別名]
# 或者: from jsonschema.FormatChecker import checks [as 別名]
class Spec(object):
    """Represents a Swagger Specification for a service.

    :param spec_dict: Swagger API specification in json-like dict form
    :param origin_url: URL from which the spec was retrieved.
    :param http_client: Used to retrive the spec via http/https.
    :type http_client: :class:`bravado.http_client.HTTPClient`
    :param config: Configuration dict. See CONFIG_DEFAULTS.
    """
    def __init__(self, spec_dict, origin_url=None, http_client=None,
                 config=None):
        self.spec_dict = spec_dict
        self.origin_url = origin_url
        self.http_client = http_client
        self.api_url = None
        self.config = dict(CONFIG_DEFAULTS, **(config or {}))

        # (key, value) = (simple format def name, Model type)
        # (key, value) = (#/ format def ref, Model type)
        self.definitions = None

        # (key, value) = (simple resource name, Resource)
        # (key, value) = (#/ format resource ref, Resource)
        self.resources = None

        # (key, value) = (simple ref name, param_spec in dict form)
        # (key, value) = (#/ format ref name, param_spec in dict form)
        self.params = None

        # Built on-demand - see get_op_for_request(..)
        self._request_to_op_map = None

        # (key, value) = (format name, SwaggerFormat)
        self.user_defined_formats = {}
        self.format_checker = FormatChecker()

    @classmethod
    def from_dict(cls, spec_dict, origin_url=None, http_client=None,
                  config=None):
        """
        Build a :class:`Spec` from Swagger API Specificiation

        :param spec_dict: swagger spec in json-like dict form.
        :param origin_url: the url used to retrieve the spec, if any
        :type  origin_url: str
        :param config: Configuration dict. See CONFIG_DEFAULTS.
        """
        tag_models(spec_dict)
        fix_malformed_model_refs(spec_dict)
        spec_dict = jsonref.JsonRef.replace_refs(spec_dict,
                                                 base_uri=origin_url or '')
        replace_jsonref_proxies(spec_dict)
        spec = cls(spec_dict, origin_url, http_client, config)
        spec.build()
        return spec

    def build(self):
        if self.config['validate_swagger_spec']:
            validator20.validate_spec(self.spec_dict)

        self.api_url = build_api_serving_url(self.spec_dict, self.origin_url)
        self.definitions = build_models(self.spec_dict.get('definitions', {}))
        self.resources = build_resources(self)

    def get_op_for_request(self, http_method, path_pattern):
        """
        Return the Swagger operation for the passed in request http method
        and path pattern. Makes it really easy for server-side implementations
        to map incoming requests to the Swagger spec.

        :param http_method: http method of the request
        :param path_pattern: request path pattern. e.g. /foo/{bar}/baz/{id}
        :returns: the matching operation or None if a match couldn't be found
        :rtype: :class:`bravado_core.operation.Operation`
        """
        if self._request_to_op_map is None:
            # lazy initialization
            self._request_to_op_map = {}
            base_path = self.spec_dict.get('basePath', '').rstrip('/')
            for resource in self.resources.values():
                for op in resource.operations.values():
                    full_path = base_path + op.path_name
                    key = (op.http_method, full_path)
                    self._request_to_op_map[key] = op

        key = (http_method.lower(), path_pattern)
        return self._request_to_op_map.get(key)

    def register_format(self, user_defined_format):
        """Registers a user-defined format to be used with this spec.

        :type user_defined_format:
            :class:`bravado_core.formatter.SwaggerFormat`
        """
        name = user_defined_format.format
        self.user_defined_formats[name] = user_defined_format
        validate = return_true_wrapper(user_defined_format.validate)
        self.format_checker.checks(
            name, raises=(SwaggerValidationError,))(validate)

#.........這裏部分代碼省略.........
開發者ID:laucia,項目名稱:bravado-core,代碼行數:103,代碼來源:spec.py

示例15: Spec

# 需要導入模塊: from jsonschema import FormatChecker [as 別名]
# 或者: from jsonschema.FormatChecker import checks [as 別名]

#.........這裏部分代碼省略.........
        :type  origin_url: str
        :param config: Configuration dict. See CONFIG_DEFAULTS.
        """
        spec = cls(spec_dict, origin_url, http_client, config)
        spec.build()
        return spec

    def build(self):
        if self.config['validate_swagger_spec']:
            self.resolver = validator20.validate_spec(
                self.spec_dict, spec_url=self.origin_url or '',
                http_handlers=build_http_handlers(self.http_client))

        post_process_spec(
            self,
            on_container_callbacks=[
                functools.partial(
                    tag_models, visited_models={}, swagger_spec=self),
                functools.partial(
                    collect_models, models=self.definitions,
                    swagger_spec=self)
            ])

        for format in self.config['formats']:
            self.register_format(format)

        self.api_url = build_api_serving_url(self.spec_dict, self.origin_url)
        self.resources = build_resources(self)

    def deref(self, ref_dict):
        """Dereference ref_dict (if it is indeed a ref) and return what the
        ref points to.

        :param ref_dict:  {'$ref': '#/blah/blah'}
        :return: dereferenced value of ref_dict
        :rtype: scalar, list, dict
        """
        if ref_dict is None or not is_ref(ref_dict):
            return ref_dict

        # Restore attached resolution scope before resolving since the
        # resolver doesn't have a traversal history (accumulated scope_stack)
        # when asked to resolve.
        with in_scope(self.resolver, ref_dict):
            log.debug('Resolving {0} with scope {1}: {2}'.format(
                ref_dict['$ref'],
                len(self.resolver._scopes_stack),
                self.resolver._scopes_stack))

            _, target = self.resolver.resolve(ref_dict['$ref'])
            return target

    def get_op_for_request(self, http_method, path_pattern):
        """Return the Swagger operation for the passed in request http method
        and path pattern. Makes it really easy for server-side implementations
        to map incoming requests to the Swagger spec.

        :param http_method: http method of the request
        :param path_pattern: request path pattern. e.g. /foo/{bar}/baz/{id}

        :returns: the matching operation or None if a match couldn't be found
        :rtype: :class:`bravado_core.operation.Operation`
        """
        if self._request_to_op_map is None:
            # lazy initialization
            self._request_to_op_map = {}
            base_path = self.spec_dict.get('basePath', '').rstrip('/')
            for resource in self.resources.values():
                for op in resource.operations.values():
                    full_path = base_path + op.path_name
                    key = (op.http_method, full_path)
                    self._request_to_op_map[key] = op

        key = (http_method.lower(), path_pattern)
        return self._request_to_op_map.get(key)

    def register_format(self, user_defined_format):
        """Registers a user-defined format to be used with this spec.

        :type user_defined_format:
            :class:`bravado_core.formatter.SwaggerFormat`
        """
        name = user_defined_format.format
        self.user_defined_formats[name] = user_defined_format
        validate = return_true_wrapper(user_defined_format.validate)
        self.format_checker.checks(
            name, raises=(SwaggerValidationError,))(validate)

    def get_format(self, name):
        """
        :param name: Name of the format to retrieve
        :rtype: :class:`bravado_core.formatters.SwaggerFormat`
        """
        if name in formatter.DEFAULT_FORMATS:
            return formatter.DEFAULT_FORMATS[name]
        format = self.user_defined_formats.get(name)
        if format is None:
            warnings.warn('{0} format is not registered with bravado-core!'
                          .format(name), Warning)
        return format
開發者ID:msander,項目名稱:bravado-core,代碼行數:104,代碼來源:spec.py


注:本文中的jsonschema.FormatChecker.checks方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。