def test_rules_set_with_dict_field(): document = {'a_dict': {'foo': 1}} schema = {'a_dict': {'type': 'dict', 'schema': {'foo': 'rule'}}} # the schema's not yet added to the valid ones, so test the faulty first rules_set_registry.add('rule', {'tüpe': 'integer'}) assert_schema_error(document, schema) rules_set_registry.add('rule', {'type': 'integer'}) assert_success(document, schema)
def load_schemas(): # type: () -> dict """ Parse all schemas defined in current directory and return it as a map of validators :return: """ root = dirname(__file__) files = [f for f in listdir(root) if f.endswith('.yaml')] versions = 'versions.yaml' if versions not in files: raise RuntimeError('missing required config versions.yaml') files.remove(versions) # sort versions in asc order files = list(sorted(files)) for file in files: with open(join(root, file)) as f: conf = yaml.load(f, Loader=yaml.SafeLoader) conf_name, _ = splitext(basename(file)) for schema_name, desc in conf.get('schemas', {}).items(): schema_registry.add(f'{conf_name}.{schema_name}', desc) for rule_name, desc in conf.get('rules', {}).items(): rules_set_registry.add(f'{conf_name}.{rule_name}', desc) with open(join(root, versions)) as f: wconf = yaml.load(f, Loader=yaml.SafeLoader) if '_all' not in wconf: raise RuntimeError('invalid versions.yaml: missing _all section') if 'versions' not in wconf: raise RuntimeError('invalid versions.yaml: missing versions section') res = { 'default': OptionalValidator(wconf['_all'], allow_unknown=True) } for ver, desc in wconf['versions'].items(): desc.update(wconf['_all']) res[str(ver)] = OptionalValidator(desc) return res
def test_normalization_with_rules_set(): # https://github.com/pyeve/cerberus/issues/283 rules_set_registry.add('foo', {'default': 42}) assert_normalized({}, {'bar': 42}, {'bar': 'foo'}) rules_set_registry.add('foo', {'default_setter': lambda _: 42}) assert_normalized({}, {'bar': 42}, {'bar': 'foo'}) rules_set_registry.add('foo', {'type': 'integer', 'nullable': True}) assert_success({'bar': None}, {'bar': 'foo'})
def test_normalization_with_rules_set(): # https://github.com/pyeve/cerberus/issues/283 rules_set_registry.add('foo', {'default': 42}) assert_normalized({}, {'bar': 42}, {'bar': 'foo'}) rules_set_registry.add('foo', {'default_setter': lambda _: 42}) assert_normalized({}, {'bar': 42}, {'bar': 'foo'}) rules_set_registry.add('foo', {'type': 'integer', 'nullable': True}) assert_success({'bar': None}, {'bar': 'foo'})
def test_rules_registry_with_anyof_type(): rules_set_registry.add('string_or_integer', {'anyof_type': ['string', 'integer']}) schema = {'soi': 'string_or_integer'} assert_success({'soi': 'hello'}, schema)
def test_recursion(): rules_set_registry.add('self', {'type': 'dict', 'allow_unknown': 'self'}) v = Validator(allow_unknown='self') assert_success({0: {1: {2: {}}}}, {}, v)
def test_allow_unknown_as_reference(): rules_set_registry.add('foo', {'type': 'number'}) v = Validator(allow_unknown='foo') assert_success({0: 1}, {}, v) assert_fail({0: 'one'}, {}, v)
def test_rules_set_simple(): rules_set_registry.add('foo', {'type': 'integer'}) assert_success({'bar': 1}, {'bar': 'foo'}) assert_fail({'bar': 'one'}, {'bar': 'foo'})
def test_rules_registry_with_anyof_type(): rules_set_registry.add('string_or_integer', {'anyof_type': ['string', 'integer']}) schema = {'soi': 'string_or_integer'} assert_success({'soi': 'hello'}, schema)
def test_recursion(): rules_set_registry.add('self', {'type': 'dict', 'allow_unknown': 'self'}) v = Validator(allow_unknown='self') assert_success({0: {1: {2: {}}}}, {}, v)
def test_allow_unknown_as_reference(): rules_set_registry.add('foo', {'type': 'number'}) v = Validator(allow_unknown='foo') assert_success({0: 1}, {}, v) assert_fail({0: 'one'}, {}, v)
def test_rules_set_simple(): rules_set_registry.add('foo', {'type': 'integer'}) assert_success({'bar': 1}, {'bar': 'foo'}) assert_fail({'bar': 'one'}, {'bar': 'foo'})
def add_global_schemas(schema_data: Dict[str, dict]) -> None: """Add schema-type registrations, globally.""" for key, schema in schema_data.items(): LOG.debug("adding '%s' schema type", key) rules_set_registry.add(key, schema)
""" import json from collections import Counter from pathlib import Path from random import choice, randrange from typing import Callable, Dict, List, Mapping, Optional, Union from typing import Counter as CounterType from pytest import mark from cerberus import rules_set_registry, schema_registry, TypeDefinition, Validator from cerberus.benchmarks import DOCUMENTS_PATH rules_set_registry.add("path_rules", {"coerce": Path, "type": "path"}) schema_registry.add( "field_3_schema", { # an outer rule requires all fields' values to be a list "field_31": {"contains": 0, "empty": False}, "field_32": { "default": [None, None, None], "items": [ {"type": "integer"}, {"type": "string"}, {"type": ["integer", "string"]}, ], "itemsrules": {"nullable": True},
class ThrowErrorHandle(BasicErrorHandler): """エラー時にValidationErrorを投げるErrorHandler""" def end(self, validator): if validator.errors: raise ValidationError(validator.errors) validator = Validator(error_handler=ThrowErrorHandle) REX_UUID = r'(?i)^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' rules_set_registry.add('UUIDRequired', { 'type': 'string', 'regex': REX_UUID, }) rules_set_registry.add('UUIDNullable', { 'type': 'string', 'regex': REX_UUID, 'nullable': True, }) schema_registry.add( 'JSUser', { 'nickname': { 'type': 'string', }, 'discriminator': { 'type': 'string',