示例#1
0
def test_allow_unknown_with_of_rules():
    # https://github.com/pyeve/cerberus/issues/251
    schema = {
        'test': {
            'oneof': [
                {
                    'type': 'dict',
                    'allow_unknown': True,
                    'schema': {'known': {'type': 'string'}},
                },
                {'type': 'dict', 'schema': {'known': {'type': 'string'}}},
            ]
        }
    }
    # check regression and that allow unknown does not cause any different
    # than expected behaviour for one-of.
    document = {'test': {'known': 's'}}
    assert_fail(
        document,
        schema,
        error=('test', ('test', 'oneof'), errors.ONEOF, schema['test']['oneof']),
    )
    # check that allow_unknown is actually applied
    document = {'test': {'known': 's', 'unknown': 'asd'}}
    assert_success(document, schema)
示例#2
0
def test_error_tree_from_anyof(validator):
    schema = {'foo': {'anyof': [{'type': 'string'}, {'type': 'integer'}]}}
    document = {'foo': []}
    assert_fail(document, schema, validator=validator)
    d_error_tree = validator.document_error_tree
    s_error_tree = validator.schema_error_tree
    assert 'foo' in d_error_tree
    assert d_error_tree['foo'].errors[0].value == []
    assert 'foo' in s_error_tree
    assert 'anyof' in s_error_tree['foo']
    assert 0 in s_error_tree['foo']['anyof']
    assert 1 in s_error_tree['foo']['anyof']
    assert 'type' in s_error_tree['foo']['anyof'][0]
    assert s_error_tree['foo']['anyof'][0]['type'].errors[0].value == []
示例#3
0
def test_validator_method(rule):
    class MyValidator(cerberus.Validator):
        def _validator_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', )),
    )
示例#4
0
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', )),
    )
示例#5
0
def test_coerce_catches_TypeError():
    schema = {'name': {'coerce': str.lower}}
    _errors = assert_fail({'name': 1234}, schema)
    _errors[0].info = ()  # ignore exception message here
    assert_has_error(
        _errors, 'name', ('name', 'coerce'), errors.COERCION_FAILED, str.lower
    )
示例#6
0
def test_coerce_catches_ValueError():
    schema = {'amount': {'coerce': int}}
    _errors = assert_fail({'amount': 'not_a_number'}, schema)
    _errors[0].info = ()  # ignore exception message here
    assert_has_error(
        _errors, 'amount', ('amount', 'coerce'), errors.COERCION_FAILED, int
    )
示例#7
0
def test_issue_250_no_type_fail_on_dict():
    # https://github.com/pyeve/cerberus/issues/250
    schema = {
        'list': {'schema': {'allow_unknown': True, 'schema': {'a': {'type': 'string'}}}}
    }
    document = {'list': {'a': {'a': 'known'}}}
    assert_fail(
        document,
        schema,
        error=(
            'list',
            ('list', 'schema'),
            errors.BAD_TYPE_FOR_SCHEMA,
            schema['list']['schema'],
        ),
    )
示例#8
0
def test_issue_250():
    # https://github.com/pyeve/cerberus/issues/250
    schema = {
        'list': {
            'type': 'list',
            'schema': {
                'type': 'dict',
                'allow_unknown': True,
                'schema': {'a': {'type': 'string'}},
            },
        }
    }
    document = {'list': {'is_a': 'mapping'}}
    assert_fail(
        document,
        schema,
        error=('list', ('list', 'type'), errors.BAD_TYPE, schema['list']['type']),
    )
示例#9
0
def test_coerce_in_listitems_catches_ValueError():
    schema = {'things': {'type': 'list', 'items': [{'coerce': int}, {'coerce': str}]}}
    document = {'things': ['not_a_number', 2]}
    _errors = assert_fail(document, schema)
    _errors[0].info = ()  # ignore exception message here
    assert_has_error(
        _errors,
        ('things', 0),
        ('things', 'items', 'coerce'),
        errors.COERCION_FAILED,
        int,
    )
示例#10
0
def test_error_tree_from_subschema(validator):
    schema = {'foo': {'schema': {'bar': {'type': 'string'}}}}
    document = {'foo': {'bar': 0}}
    assert_fail(document, schema, validator=validator)
    d_error_tree = validator.document_error_tree
    s_error_tree = validator.schema_error_tree

    assert 'foo' in d_error_tree

    assert len(d_error_tree['foo'].errors) == 1, d_error_tree['foo']
    assert d_error_tree['foo'].errors[0].code == errors.MAPPING_SCHEMA.code
    assert 'bar' in d_error_tree['foo']
    assert d_error_tree['foo']['bar'].errors[0].value == 0
    assert d_error_tree.fetch_errors_from(('foo', 'bar'))[0].value == 0

    assert 'foo' in s_error_tree
    assert 'schema' in s_error_tree['foo']
    assert 'bar' in s_error_tree['foo']['schema']
    assert 'type' in s_error_tree['foo']['schema']['bar']
    assert s_error_tree['foo']['schema']['bar']['type'].errors[0].value == 0
    assert (s_error_tree.fetch_errors_from(
        ('foo', 'schema', 'bar', 'type'))[0].value == 0)
示例#11
0
def test_basic_error_of_errors(validator):
    schema = {'foo': {'oneof': [{'type': 'integer'}, {'type': 'string'}]}}
    document = {'foo': 23.42}
    error = ('foo', ('foo', 'oneof'), errors.ONEOF, schema['foo']['oneof'], ())
    child_errors = [
        (error[0], error[1] + (0, 'type'), errors.BAD_TYPE, 'integer'),
        (error[0], error[1] + (1, 'type'), errors.BAD_TYPE, 'string'),
    ]
    assert_fail(document,
                schema,
                validator=validator,
                error=error,
                child_errors=child_errors)
    assert validator.errors == {
        'foo': [
            errors.BasicErrorHandler.messages[0x92],
            {
                'oneof definition 0': ['must be of integer type'],
                'oneof definition 1': ['must be of string type'],
            },
        ]
    }
示例#12
0
def test_nested_error_paths(validator):
    # interpreters of the same version on some platforms showed different sort results
    # over various runs:
    def assert_has_all_errors(errors, *ref_errs):
        for ref_err in ref_errs:
            for error in errors:
                if error == ref_err:
                    break
            else:
                raise AssertionError

    schema = {
        'a_dict': {
            'keysrules': {
                'type': 'integer'
            },
            'valuesrules': {
                'regex': '[a-z]*'
            },
        },
        'a_list': {
            'schema': {
                'type': 'string',
                'oneof_regex': ['[a-z]*$', '[A-Z]*']
            }
        },
    }
    document = {
        'a_dict': {
            0: 'abc',
            'one': 'abc',
            2: 'aBc',
            'three': 'abC'
        },
        'a_list': [0, 'abc', 'abC'],
    }
    assert_fail(document, schema, validator=validator)

    det = validator.document_error_tree
    set = validator.schema_error_tree

    assert len(det.errors) == 0
    assert len(set.errors) == 0

    assert len(det['a_dict'].errors) == 2
    assert len(set['a_dict'].errors) == 0

    assert det['a_dict'][0] is None
    assert len(det['a_dict']['one'].errors) == 1
    assert len(det['a_dict'][2].errors) == 1
    assert len(det['a_dict']['three'].errors) == 2

    assert len(set['a_dict']['keysrules'].errors) == 1
    assert len(set['a_dict']['valuesrules'].errors) == 1

    assert len(set['a_dict']['keysrules']['type'].errors) == 2
    assert len(set['a_dict']['valuesrules']['regex'].errors) == 2

    ref_err1 = ValidationError(
        ('a_dict', 'one'),
        ('a_dict', 'keysrules', 'type'),
        errors.BAD_TYPE.code,
        'type',
        'integer',
        'one',
        (),
    )

    ref_err2 = ValidationError(
        ('a_dict', 2),
        ('a_dict', 'valuesrules', 'regex'),
        errors.REGEX_MISMATCH.code,
        'regex',
        '[a-z]*$',
        'aBc',
        (),
    )

    ref_err3 = ValidationError(
        ('a_dict', 'three'),
        ('a_dict', 'keysrules', 'type'),
        errors.BAD_TYPE.code,
        'type',
        'integer',
        'three',
        (),
    )
    ref_err4 = ValidationError(
        ('a_dict', 'three'),
        ('a_dict', 'valuesrules', 'regex'),
        errors.REGEX_MISMATCH.code,
        'regex',
        '[a-z]*$',
        'abC',
        (),
    )
    assert det['a_dict'][2].errors[0] == ref_err2
    assert det['a_dict']['one'].errors[0] == ref_err1
    assert_has_all_errors(det['a_dict']['three'].errors, ref_err3, ref_err4)
    assert_has_all_errors(set['a_dict']['keysrules']['type'].errors, ref_err1,
                          ref_err3)
    assert_has_all_errors(set['a_dict']['valuesrules']['regex'].errors,
                          ref_err2, ref_err4)

    assert len(det['a_list'].errors) == 1
    assert len(det['a_list'][0].errors) == 1
    assert det['a_list'][1] is None
    assert len(det['a_list'][2].errors) == 3
    assert len(set['a_list'].errors) == 0
    assert len(set['a_list']['schema'].errors) == 1
    assert len(set['a_list']['schema']['type'].errors) == 1
    assert len(set['a_list']['schema']['oneof'][0]['regex'].errors) == 1
    assert len(set['a_list']['schema']['oneof'][1]['regex'].errors) == 1

    ref_err5 = ValidationError(
        ('a_list', 0),
        ('a_list', 'schema', 'type'),
        errors.BAD_TYPE.code,
        'type',
        'string',
        0,
        (),
    )
    ref_err6 = ValidationError(
        ('a_list', 2),
        ('a_list', 'schema', 'oneof'),
        errors.ONEOF.code,
        'oneof',
        'irrelevant_at_this_point',
        'abC',
        (),
    )
    ref_err7 = ValidationError(
        ('a_list', 2),
        ('a_list', 'schema', 'oneof', 0, 'regex'),
        errors.REGEX_MISMATCH.code,
        'regex',
        '[a-z]*$',
        'abC',
        (),
    )
    ref_err8 = ValidationError(
        ('a_list', 2),
        ('a_list', 'schema', 'oneof', 1, 'regex'),
        errors.REGEX_MISMATCH.code,
        'regex',
        '[a-z]*$',
        'abC',
        (),
    )

    assert det['a_list'][0].errors[0] == ref_err5
    assert_has_all_errors(det['a_list'][2].errors, ref_err6, ref_err7,
                          ref_err8)
    assert set['a_list']['schema']['oneof'].errors[0] == ref_err6
    assert set['a_list']['schema']['oneof'][0]['regex'].errors[0] == ref_err7
    assert set['a_list']['schema']['oneof'][1]['regex'].errors[0] == ref_err8
    assert set['a_list']['schema']['type'].errors[0] == ref_err5
示例#13
0
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)
示例#14
0
def test_rules_set_simple():
    rules_set_registry.add('foo', {'type': 'integer'})
    assert_success({'bar': 1}, {'bar': 'foo'})
    assert_fail({'bar': 'one'}, {'bar': 'foo'})