本文整理汇总了Python中cerberus.Validator方法的典型用法代码示例。如果您正苦于以下问题:Python cerberus.Validator方法的具体用法?Python cerberus.Validator怎么用?Python cerberus.Validator使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cerberus
的用法示例。
在下文中一共展示了cerberus.Validator方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _validate_transform_options
# 需要导入模块: import cerberus [as 别名]
# 或者: from cerberus import Validator [as 别名]
def _validate_transform_options(field, value, error):
# value will be a dict with keys "name" and "options"
transform_name = value["name"]
options = value["options"]
available_transforms = transforms.get_all_transforms()
if transform_name not in available_transforms:
error(field, f"The transform {transform_name} does not exist.")
return
validator = cerberus.Validator(
available_transforms[transform_name].get_options_schema()
)
validator.validate(options)
if validator.errors:
errors = "\n".join(validator.errors)
error(
field,
f"The options schema for transform {transform_name} failed to validate: {errors}",
)
示例2: test_contextual_data_preservation
# 需要导入模块: import cerberus [as 别名]
# 或者: from cerberus import Validator [as 别名]
def test_contextual_data_preservation():
class InheritedValidator(cerberus.Validator):
def __init__(self, *args, **kwargs):
if 'working_dir' in kwargs:
self.working_dir = kwargs['working_dir']
super(InheritedValidator, self).__init__(*args, **kwargs)
def _validate_type_test(self, value):
if self.working_dir:
return True
assert 'test' in InheritedValidator.types
v = InheritedValidator(
{'test': {'type': 'list', 'schema': {'type': 'test'}}}, working_dir='/tmp'
)
assert_success({'test': ['foo']}, validator=v)
示例3: test_docstring_parsing
# 需要导入模块: import cerberus [as 别名]
# 或者: from cerberus import Validator [as 别名]
def test_docstring_parsing():
class CustomValidator(cerberus.Validator):
def _validate_foo(self, argument, field, value):
""" {'type': 'zap'} """
pass
def _validate_bar(self, value):
""" Test the barreness of a value.
The rule's arguments are validated against this schema:
{'type': 'boolean'}
"""
pass
assert 'foo' in CustomValidator.validation_rules
assert 'bar' in CustomValidator.validation_rules
# TODO remove 'validator' as rule parameter with the next major release
示例4: test_check_with_method
# 需要导入模块: import cerberus [as 别名]
# 或者: from cerberus import Validator [as 别名]
def test_check_with_method(rule):
# https://github.com/pyeve/cerberus/issues/265
class MyValidator(cerberus.Validator):
def _check_with_oddity(self, field, value):
if not value & 1:
self._error(field, "Must be an odd number")
v = MyValidator(schema={'amount': {rule: 'oddity'}})
assert_success(document={'amount': 1}, validator=v)
assert_fail(
document={'amount': 2},
validator=v,
error=('amount', (), cerberus.errors.CUSTOM, None, ('Must be an odd number',)),
)
# TODO remove test with the next major release
示例5: test_schema_validation_can_be_disabled_in_schema_setter
# 需要导入模块: import cerberus [as 别名]
# 或者: from cerberus import Validator [as 别名]
def test_schema_validation_can_be_disabled_in_schema_setter():
class NonvalidatingValidator(cerberus.Validator):
"""
Skips schema validation to speed up initialization
"""
@cerberus.Validator.schema.setter
def schema(self, schema):
if schema is None:
self._schema = None
elif self.is_child:
self._schema = schema
elif isinstance(schema, cerberus.schema.DefinitionSchema):
self._schema = schema
else:
self._schema = cerberus.schema.UnvalidatedSchema(schema)
v = NonvalidatingValidator(schema=sample_schema)
assert v.validate(document={'an_integer': 1})
assert not v.validate(document={'an_integer': 'a'})
示例6: test_271_normalising_tuples
# 需要导入模块: import cerberus [as 别名]
# 或者: from cerberus import Validator [as 别名]
def test_271_normalising_tuples():
# https://github.com/pyeve/cerberus/issues/271
schema = {
'my_field': {'type': 'list', 'schema': {'type': ('string', 'number', 'dict')}}
}
document = {'my_field': ('foo', 'bar', 42, 'albert', 'kandinsky', {'items': 23})}
assert_success(document, schema)
normalized = Validator(schema).normalized(document)
assert normalized['my_field'] == (
'foo',
'bar',
42,
'albert',
'kandinsky',
{'items': 23},
)
示例7: test__error_3
# 需要导入模块: import cerberus [as 别名]
# 或者: from cerberus import Validator [as 别名]
def test__error_3():
valids = [
{'type': 'string', 'regex': '0x[0-9a-f]{2}'},
{'type': 'integer', 'min': 0, 'max': 255},
]
v = Validator(schema={'foo': {'oneof': valids}})
v.document = {'foo': '0x100'}
v._error('foo', errors.ONEOF, (), 0, 2)
error = v._errors[0]
assert error.document_path == ('foo',)
assert error.schema_path == ('foo', 'oneof')
assert error.code == 0x92
assert error.rule == 'oneof'
assert error.constraint == valids
assert error.value == '0x100'
assert error.info == ((), 0, 2)
assert error.is_group_error
assert error.is_logic_error
示例8: test_queries
# 需要导入模块: import cerberus [as 别名]
# 或者: from cerberus import Validator [as 别名]
def test_queries():
schema = {'foo': {'type': 'dict', 'schema': {'bar': {'type': 'number'}}}}
document = {'foo': {'bar': 'zero'}}
validator = Validator(schema)
validator(document)
assert 'foo' in validator.document_error_tree
assert 'bar' in validator.document_error_tree['foo']
assert 'foo' in validator.schema_error_tree
assert 'schema' in validator.schema_error_tree['foo']
assert errors.MAPPING_SCHEMA in validator.document_error_tree['foo'].errors
assert errors.MAPPING_SCHEMA in validator.document_error_tree['foo']
assert errors.BAD_TYPE in validator.document_error_tree['foo']['bar']
assert errors.MAPPING_SCHEMA in validator.schema_error_tree['foo']['schema']
assert (
errors.BAD_TYPE in validator.schema_error_tree['foo']['schema']['bar']['type']
)
assert (
validator.document_error_tree['foo'][errors.MAPPING_SCHEMA].child_errors[0].code
== errors.BAD_TYPE.code
)
示例9: test_custom_datatype_rule
# 需要导入模块: import cerberus [as 别名]
# 或者: from cerberus import Validator [as 别名]
def test_custom_datatype_rule():
class MyValidator(Validator):
def _validate_min_number(self, min_number, field, value):
""" {'type': 'number'} """
if value < min_number:
self._error(field, 'Below the min')
# TODO replace with TypeDefintion in next major release
def _validate_type_number(self, value):
if isinstance(value, int):
return True
schema = {'test_field': {'min_number': 1, 'type': 'number'}}
validator = MyValidator(schema)
assert_fail(
{'test_field': '0'},
validator=validator,
error=('test_field', ('test_field', 'type'), errors.BAD_TYPE, 'number'),
)
assert_fail(
{'test_field': 0},
validator=validator,
error=('test_field', (), errors.CUSTOM, None, ('Below the min',)),
)
assert validator.errors == {'test_field': ['Below the min']}
示例10: test_custom_validator
# 需要导入模块: import cerberus [as 别名]
# 或者: from cerberus import Validator [as 别名]
def test_custom_validator():
class MyValidator(Validator):
def _validate_isodd(self, isodd, field, value):
""" {'type': 'boolean'} """
if isodd and not bool(value & 1):
self._error(field, 'Not an odd number')
schema = {'test_field': {'isodd': True}}
validator = MyValidator(schema)
assert_success({'test_field': 7}, validator=validator)
assert_fail(
{'test_field': 6},
validator=validator,
error=('test_field', (), errors.CUSTOM, None, ('Not an odd number',)),
)
assert validator.errors == {'test_field': ['Not an odd number']}
示例11: test_ignore_none_values
# 需要导入模块: import cerberus [as 别名]
# 或者: from cerberus import Validator [as 别名]
def test_ignore_none_values():
field = 'test'
schema = {field: {'type': 'string', 'empty': False, 'required': False}}
document = {field: None}
# Test normal behaviour
validator = Validator(schema, ignore_none_values=False)
assert_fail(document, validator=validator)
validator.schema[field]['required'] = True
validator.schema.validate()
_errors = assert_fail(document, validator=validator)
assert_not_has_error(
_errors, field, (field, 'required'), errors.REQUIRED_FIELD, True
)
# Test ignore None behaviour
validator = Validator(schema, ignore_none_values=True)
validator.schema[field]['required'] = False
validator.schema.validate()
assert_success(document, validator=validator)
validator.schema[field]['required'] = True
_errors = assert_fail(schema=schema, document=document, validator=validator)
assert_has_error(_errors, field, (field, 'required'), errors.REQUIRED_FIELD, True)
assert_not_has_error(_errors, field, (field, 'type'), errors.BAD_TYPE, 'string')
示例12: test_dependencies_errors
# 需要导入模块: import cerberus [as 别名]
# 或者: from cerberus import Validator [as 别名]
def test_dependencies_errors():
v = Validator(
{
'field1': {'required': False},
'field2': {'required': True, 'dependencies': {'field1': ['one', 'two']}},
}
)
assert_fail(
{'field1': 'three', 'field2': 7},
validator=v,
error=(
'field2',
('field2', 'dependencies'),
errors.DEPENDENCIES_FIELD_VALUE,
{'field1': ['one', 'two']},
({'field1': 'three'},),
),
)
示例13: test_require_all_override_by_subdoc_require_all
# 需要导入模块: import cerberus [as 别名]
# 或者: from cerberus import Validator [as 别名]
def test_require_all_override_by_subdoc_require_all(
validator_require_all, sub_doc_require_all
):
sub_schema = {"bar": {"type": "string"}}
schema = {
"foo": {
"type": "dict",
"require_all": sub_doc_require_all,
"schema": sub_schema,
}
}
validator = Validator(require_all=validator_require_all)
assert_success({"foo": {"bar": "baz"}}, schema, validator)
if validator_require_all:
assert_fail({}, schema, validator)
else:
assert_success({}, schema, validator)
if sub_doc_require_all:
assert_fail({"foo": {}}, schema, validator)
else:
assert_success({"foo": {}}, schema, validator)
示例14: test_require_all_and_exclude
# 需要导入模块: import cerberus [as 别名]
# 或者: from cerberus import Validator [as 别名]
def test_require_all_and_exclude():
schema = {
'foo': {'type': 'string', 'excludes': 'bar'},
'bar': {'type': 'string', 'excludes': 'foo'},
}
validator = Validator(require_all=True)
assert_fail(
{},
schema,
validator,
errors=[
('foo', '__require_all__', errors.REQUIRED_FIELD, True),
('bar', '__require_all__', errors.REQUIRED_FIELD, True),
],
)
assert_success({'foo': 'value'}, schema, validator)
assert_success({'bar': 'value'}, schema, validator)
assert_fail({'foo': 'value', 'bar': 'value'}, schema, validator)
validator.require_all = False
assert_success({}, schema, validator)
assert_success({'foo': 'value'}, schema, validator)
assert_success({'bar': 'value'}, schema, validator)
assert_fail({'foo': 'value', 'bar': 'value'}, schema, validator)
示例15: test_validated_schema_cache
# 需要导入模块: import cerberus [as 别名]
# 或者: from cerberus import Validator [as 别名]
def test_validated_schema_cache():
v = Validator({'foozifix': {'coerce': int}})
cache_size = len(v._valid_schemas)
v = Validator({'foozifix': {'type': 'integer'}})
cache_size += 1
assert len(v._valid_schemas) == cache_size
v = Validator({'foozifix': {'coerce': int}})
assert len(v._valid_schemas) == cache_size
max_cache_size = 161
assert cache_size <= max_cache_size, (
"There's an unexpected high amount (%s) of cached valid "
"definition schemas. Unless you added further tests, "
"there are good chances that something is wrong. "
"If you added tests with new schemas, you can try to "
"adjust the variable `max_cache_size` according to "
"the added schemas." % cache_size
)