Python cerberus.Validator() Examples
The following are 30
code examples of cerberus.Validator().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
cerberus
, or try the search function
.
Example #1
Source File: test_validation.py From pipenv with MIT License | 6 votes |
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'},), ), )
Example #2
Source File: flaw.py From RVD with GNU General Public License v3.0 | 6 votes |
def validate(self): """ Validate flaw against the schema :return bool """ validated = False # reflect whether the overall process suceeded v = Validator(SCHEMA, allow_unknown=True) # allow unknown values if not v.validate(self.document(), SCHEMA): # print(v.errors) for key in v.errors.keys(): print("\t" + str(key) + ": ", end="") red("not valid", end="") print(": " + str(v.errors[key])) else: # print(v.validated(doc)) # valid_documents = [x for x in v.validated(doc)] # for document in valid_documents: # print("\t" + str(document) + ": ", end='') # green("valid") green("Validated successfully!") validated = True return validated
Example #3
Source File: test_customization.py From pipenv with MIT License | 6 votes |
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
Example #4
Source File: config.py From tile-generator with Apache License 2.0 | 6 votes |
def __init__(self, *arg, **kw): super(Config, self).__init__(*arg, **kw) class ConfigValidator(cerberus.Validator): def validate(self, document, schema=None, update=False, normalize=True): validated = super(ConfigValidator, self).validate(document, schema, update, normalize) if not validated: print(document.get('name'), '-> Failed to validate:', self.errors, file=sys.stderr) # TODO: remove the sys.exit (everywhere!) and raise instead sys.exit(1) return self.document self._validator = ConfigValidator() # This should really not be set but because we don't have the full # list of options in the schema it has to be set to pass self._validator.allow_unknown = True self._package_defs = dict() # Nasty way of mapping package types to the relevant classes # reall should be explictly importing them for k, v in package_definitions.__dict__.items(): if k.startswith('Package'): self._package_defs[v.package_type] = v
Example #5
Source File: schemas.py From amaxa with BSD 3-Clause "New" or "Revised" License | 6 votes |
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}", )
Example #6
Source File: schema_v3.py From molecule with MIT License | 6 votes |
def validate(c): """Perform schema validation.""" schema = base_schema # Dependency if c["dependency"]["name"] == "shell": schema = util.merge_dicts(schema, dependency_command_nullable_schema) # Driver if c["driver"]["name"] == "docker": schema = util.merge_dicts(schema, platforms_docker_schema) elif c["driver"]["name"] == "podman": schema = util.merge_dicts(schema, platforms_podman_schema) # Verifier schema = util.merge_dicts(schema, api.verifiers()[c["verifier"]["name"]].schema()) v = Validator(allow_unknown=True) v.validate(c, schema) return v.errors
Example #7
Source File: test_customization.py From pipenv with MIT License | 6 votes |
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)
Example #8
Source File: test_customization.py From pipenv with MIT License | 6 votes |
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
Example #9
Source File: utils.py From RVD with GNU General Public License v3.0 | 6 votes |
def validate_document(document): """ Validate document passed as parameter and returns feedback on it. :return (valid, dict) where: - valid is a boolean that expresses the result of the operation - dict is a dictionary containing the errors """ validated = False # reflect whether the overall process suceeded v = Validator(SCHEMA, allow_unknown=True) # allow unknown values if document: if not v.validate(document, SCHEMA): # print(v.errors) for key in v.errors.keys(): print("\t" + str(key) + ": ", end='') red("not valid", end='') print(': ' + str(v.errors[key])) else: green("Validated successfully!") validated = True return (validated, v.errors)
Example #10
Source File: test_customization.py From pipenv with MIT License | 6 votes |
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'})
Example #11
Source File: test_normalization.py From pipenv with MIT License | 6 votes |
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}, )
Example #12
Source File: config_generator.py From rift-python with Apache License 2.0 | 6 votes |
def parse_meta_configuration(file_name): try: with open(file_name, 'r') as stream: try: config = yaml.safe_load(stream) except yaml.YAMLError as exception: raise exception except IOError: fatal_error('Could not open input meta-configuration file "{}"'.format(file_name)) validator = cerberus.Validator(SCHEMA) if not validator.validate(config, SCHEMA): pretty_printer = pprint.PrettyPrinter() pretty_printer.pprint(validator.errors) exit(1) return validator.normalized(config)
Example #13
Source File: test_validation.py From pipenv with MIT License | 6 votes |
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')
Example #14
Source File: test_validation.py From pipenv with MIT License | 6 votes |
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']}
Example #15
Source File: test_validation.py From pipenv with MIT License | 6 votes |
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']}
Example #16
Source File: test_errors.py From pipenv with MIT License | 6 votes |
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 )
Example #17
Source File: test_errors.py From pipenv with MIT License | 6 votes |
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
Example #18
Source File: test_validation.py From pipenv with MIT License | 6 votes |
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)
Example #19
Source File: test_validation.py From pipenv with MIT License | 6 votes |
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)
Example #20
Source File: test_schema.py From pipenv with MIT License | 6 votes |
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 )
Example #21
Source File: test_validation.py From pipenv with MIT License | 5 votes |
def test_require_all_simple(): schema = {'foo': {'type': 'string'}} validator = Validator(require_all=True) assert_fail( {}, schema, validator, error=('foo', '__require_all__', errors.REQUIRED_FIELD, True), ) assert_success({'foo': 'bar'}, schema, validator) validator.require_all = False assert_success({}, schema, validator) assert_success({'foo': 'bar'}, schema, validator)
Example #22
Source File: manager.py From dephell with MIT License | 5 votes |
def validate(self) -> bool: self._data = {k: v for k, v in self._data.items() if k not in self._skip} validator = Validator(SCHEME) result = validator.validate(self._data) self.errors = validator.errors return result
Example #23
Source File: schema_v3.py From molecule with MIT License | 5 votes |
def pre_validate(stream, env, keep_string): """Pre-validate stream.""" data = util.safe_load(stream) v = Validator(allow_unknown=True) v.validate(data, pre_validate_base_schema(env, keep_string)) return v.errors, data
Example #24
Source File: schema_v3.py From molecule with MIT License | 5 votes |
def __init__(self, *args, **kwargs): """Construct Validator.""" super(Validator, self).__init__(*args, **kwargs)
Example #25
Source File: test_validation.py From pipenv with MIT License | 5 votes |
def test_self_root_document(): """ Make sure self.root_document is always the root document. See: * https://github.com/pyeve/cerberus/pull/42 * https://github.com/pyeve/eve/issues/295 """ class MyValidator(Validator): def _validate_root_doc(self, root_doc, field, value): """ {'type': 'boolean'} """ if 'sub' not in self.root_document or len(self.root_document['sub']) != 2: self._error(field, 'self.context is not the root doc!') schema = { 'sub': { 'type': 'list', 'root_doc': True, 'schema': { 'type': 'dict', 'schema': {'foo': {'type': 'string', 'root_doc': True}}, }, } } assert_success( {'sub': [{'foo': 'bar'}, {'foo': 'baz'}]}, validator=MyValidator(schema) )
Example #26
Source File: test_validation.py From pipenv with MIT License | 5 votes |
def test_issue_107(validator): schema = { 'info': { 'type': 'dict', 'schema': {'name': {'type': 'string', 'required': True}}, } } document = {'info': {'name': 'my name'}} assert_success(document, schema, validator=validator) v = Validator(schema) assert_success(document, schema, v) # it once was observed that this behaves other than the previous line assert v.validate(document)
Example #27
Source File: test_validation.py From pipenv with MIT License | 5 votes |
def test_contains(constraint): validator = Validator({'actors': {'contains': constraint}}) document = {'actors': ('Graham Chapman', 'Eric Idle', 'Terry Gilliam')} assert validator(document) document = {'actors': ('Eric idle', 'Terry Jones', 'John Cleese', 'Michael Palin')} assert not validator(document) assert errors.MISSING_MEMBERS in validator.document_error_tree['actors'] missing_actors = validator.document_error_tree['actors'][ errors.MISSING_MEMBERS ].info[0] assert any(x in missing_actors for x in ('Eric Idle', 'Terry Gilliam'))
Example #28
Source File: test_cerberus.py From pydantic with MIT License | 5 votes |
def __init__(self, allow_extra): schema = { 'id': {'type': 'integer', 'required': True}, 'client_name': {'type': 'string', 'maxlength': 255, 'required': True}, 'sort_index': {'type': 'float', 'required': True}, 'client_phone': {'type': 'string', 'maxlength': 255, 'nullable': True}, 'location': { 'type': 'dict', 'schema': {'latitude': {'type': 'float'}, 'longitude': {'type': 'float'}}, 'nullable': True, }, 'contractor': {'type': 'integer', 'min': 0, 'nullable': True, 'coerce': int}, 'upstream_http_referrer': {'type': 'string', 'maxlength': 1023, 'nullable': True}, 'grecaptcha_response': {'type': 'string', 'minlength': 20, 'maxlength': 1000, 'required': True}, 'last_updated': {'type': 'datetime', 'nullable': True, 'coerce': datetime_parse}, 'skills': { 'type': 'list', 'default': [], 'schema': { 'type': 'dict', 'schema': { 'subject': {'type': 'string', 'required': True}, 'subject_id': {'type': 'integer', 'required': True}, 'category': {'type': 'string', 'required': True}, 'qual_level': {'type': 'string', 'required': True}, 'qual_level_id': {'type': 'integer', 'required': True}, 'qual_level_ranking': {'type': 'float', 'default': 0, 'required': True}, }, }, }, } self.v = Validator(schema) self.v.allow_unknown = allow_extra
Example #29
Source File: schema.py From flask_jsondash with MIT License | 5 votes |
def validate(conf): """Validate a json conf.""" v = cerberus.Validator(DASHBOARD_SCHEMA, allow_unknown=True) valid = v.validate(conf) if not valid: return v.errors
Example #30
Source File: __init__.py From datmo with MIT License | 5 votes |
def validate(schema_name, values): try: v = Validator(schemas.get(schema_name)) response = v.validate(values) if response == False: raise ValidationFailed(v.errors) return True except SchemaError: raise ValidationSchemaMissing(schema_name)