コード例 #1
0
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
コード例 #2
0
def test__error_2():
    v = Validator(schema={'foo': {'keysrules': {'type': 'integer'}}})
    v.document = {'foo': {'0': 'bar'}}
    v._error('foo', errors.KEYSRULES, ())
    error = v._errors[0]
    assert error.document_path == ('foo', )
    assert error.schema_path == ('foo', 'keysrules')
    assert error.code == 0x83
    assert error.rule == 'keysrules'
    assert error.constraint == {'type': 'integer'}
    assert error.value == {'0': 'bar'}
    assert error.info == ((), )
    assert error.is_group_error
    assert not error.is_logic_error
コード例 #3
0
def test__error_1():
    v = Validator(schema={'foo': {'type': 'string'}})
    v.document = {'foo': 42}
    v._error('foo', errors.BAD_TYPE, 'string')
    error = v._errors[0]
    assert error.document_path == ('foo', )
    assert error.schema_path == ('foo', 'type')
    assert error.code == 0x24
    assert error.rule == 'type'
    assert error.constraint == 'string'
    assert error.value == 42
    assert error.info == ('string', )
    assert not error.is_group_error
    assert not error.is_logic_error
コード例 #4
0
def test_dynamic_types():
    decimal_type = TypeDefinition("decimal", (Decimal, ), ())
    document = {"measurement": Decimal(0)}
    schema = {"measurement": {"type": "decimal"}}

    validator = Validator()
    validator.types_mapping["decimal"] = decimal_type
    assert_success(document, schema, validator)

    class MyValidator(Validator):
        types_mapping = Validator.types_mapping.copy()
        types_mapping["decimal"] = decimal_type

    validator = MyValidator()
    assert_success(document, schema, validator)
コード例 #5
0
def assert_success(document, schema=None, validator=None, update=False):
    """Tests whether a validation succeeds."""
    if validator is None:
        validator = Validator(sample_schema)
    result = validator(document, schema, update)
    assert isinstance(result, bool)
    if not result:
        raise AssertionError(validator.errors)
コード例 #6
0
def test_issue_147_nested_dict():
    schema = {'thing': {'type': 'dict', 'schema': {'amount': {'coerce': int}}}}
    ref_obj = '2'
    document = {'thing': {'amount': ref_obj}}
    normalized = Validator(schema).normalized(document)
    assert document is not normalized
    assert normalized['thing']['amount'] == 2
    assert ref_obj == '2'
    assert document['thing']['amount'] is ref_obj
コード例 #7
0
def test_coerce_in_listitems():
    schema = {'things': {'type': 'list', 'items': [{'coerce': int}, {'coerce': str}]}}
    document = {'things': ['1', 2]}
    expected = {'things': [1, '2']}
    assert_normalized(document, expected, schema)

    validator = Validator(schema)
    document['things'].append(3)
    assert not validator(document)
    assert validator.document['things'] == document['things']
コード例 #8
0
def test_purge_readonly():
    schema = {
        'description': {'type': 'string', 'maxlength': 500},
        'last_updated': {'readonly': True},
    }
    validator = Validator(schema=schema, purge_readonly=True)
    document = {'description': 'it is a thing'}
    expected = deepcopy(document)
    document['last_updated'] = 'future'
    assert_normalized(document, expected, validator=validator)
コード例 #9
0
def test_issue_147_complex():
    schema = {'revision': {'coerce': int}}
    document = {'revision': '5', 'file': NamedTemporaryFile(mode='w+')}
    document['file'].write(r'foobar')
    document['file'].seek(0)
    normalized = Validator(schema, allow_unknown=True).normalized(document)
    assert normalized['revision'] == 5
    assert normalized['file'].read() == 'foobar'
    document['file'].close()
    normalized['file'].close()
コード例 #10
0
ファイル: test_schema.py プロジェクト: wwjiang007/pipenv
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 = 163
    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
    )
コード例 #11
0
def test_allow_unknown_with_purge_unknown_subdocument():
    validator = Validator(purge_unknown=True)
    schema = {
        'foo': {
            'type': 'dict',
            'schema': {'bar': {'type': 'string'}},
            'allow_unknown': True,
        }
    }
    document = {'foo': {'bar': 'baz', 'corge': False}, 'thud': 'xyzzy'}
    expected = {'foo': {'bar': 'baz', 'corge': False}}
    assert_normalized(document, expected, schema, validator)
コード例 #12
0
ファイル: test_schema.py プロジェクト: wwjiang007/pipenv
def test_anyof_check_with():
    def foo(field, value, error):
        pass

    def bar(field, value, error):
        pass

    schema = {'field': {'anyof_check_with': [foo, bar]}}
    validator = Validator(schema)

    assert validator.schema == {
        'field': {'anyof': [{'check_with': foo}, {'check_with': bar}]}
    }
コード例 #13
0
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},
    )
コード例 #14
0
def test_defaults_in_allow_unknown_schema():
    schema = {'meta': {'type': 'dict'}, 'version': {'type': 'string'}}
    allow_unknown = {
        'type': 'dict',
        'schema': {
            'cfg_path': {'type': 'string', 'default': 'cfg.yaml'},
            'package': {'type': 'string'},
        },
    }
    validator = Validator(schema=schema, allow_unknown=allow_unknown)

    document = {'version': '1.2.3', 'plugin_foo': {'package': 'foo'}}
    expected = {
        'version': '1.2.3',
        'plugin_foo': {'package': 'foo', 'cfg_path': 'cfg.yaml'},
    }
    assert_normalized(document, expected, schema, validator)
コード例 #15
0
def assert_exception(exception,
                     document={},
                     schema=None,
                     validator=None,
                     msg=None):
    """
    Tests whether a specific exception is raised. Optionally also tests whether the
    exception message is as expected.
    """
    if validator is None:
        validator = Validator()
    if msg is None:
        with pytest.raises(exception):
            validator(document, schema)
    else:
        with pytest.raises(exception, match=re.escape(msg)):
            validator(document, schema)
コード例 #16
0
ファイル: test_schema.py プロジェクト: wwjiang007/pipenv
def test_deprecated_rule_names_in_valueschema():
    def check_with(field, value, error):
        pass

    schema = {
        "field_1": {
            "type": "dict",
            "valueschema": {
                "type": "dict",
                "keyschema": {"type": "string"},
                "valueschema": {"type": "string"},
            },
        },
        "field_2": {
            "type": "list",
            "items": [
                {"keyschema": {}},
                {"validator": check_with},
                {"valueschema": {}},
            ],
        },
    }

    validator = Validator(schema)

    assert validator.schema == {
        "field_1": {
            "type": "dict",
            "valuesrules": {
                "type": "dict",
                "keysrules": {"type": "string"},
                "valuesrules": {"type": "string"},
            },
        },
        "field_2": {
            "type": "list",
            "items": [
                {"keysrules": {}},
                {"check_with": check_with},
                {"valuesrules": {}},
            ],
        },
    }
コード例 #17
0
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)
コード例 #18
0
def assert_fail(
    document,
    schema=None,
    validator=None,
    update=False,
    error=None,
    errors=None,
    child_errors=None,
):
    """Tests whether a validation fails."""
    if validator is None:
        validator = Validator(sample_schema)
    result = validator(document, schema, update)
    assert isinstance(result, bool)
    assert not result

    actual_errors = validator._errors

    assert not (error is not None and errors is not None)
    assert not (errors is not None and child_errors is not None), (
        'child_errors can only be tested in '
        'conjunction with the error parameter')
    assert not (child_errors is not None and error is None)
    if error is not None:
        assert len(actual_errors) == 1
        assert_has_error(actual_errors, *error)

        if child_errors is not None:
            assert len(actual_errors[0].child_errors) == len(child_errors)
            assert_has_errors(actual_errors[0].child_errors, child_errors)

    elif errors is not None:
        assert len(actual_errors) == len(errors)
        assert_has_errors(actual_errors, errors)

    return actual_errors
コード例 #19
0
ファイル: test_schema.py プロジェクト: wwjiang007/pipenv
def test_empty_schema():
    validator = Validator()
    with pytest.raises(SchemaError, match=errors.SCHEMA_ERROR_MISSING):
        validator({}, schema=None)
コード例 #20
0
def init_validator():
    return Validator(product_schema, purge_unknown=True)
コード例 #21
0
def validator():
    return Validator(sample_schema)
コード例 #22
0
def test_coerce_not_destructive():
    schema = {'amount': {'coerce': int}}
    v = Validator(schema)
    doc = {'amount': '1'}
    v.validate(doc)
    assert v.document is not doc
コード例 #23
0
def test_rename_handler():
    validator = Validator(allow_unknown={'rename_handler': int})
    schema = {}
    document = {'0': 'foo'}
    expected = {0: 'foo'}
    assert_normalized(document, expected, schema, validator)
コード例 #24
0
ファイル: test_schema.py プロジェクト: wwjiang007/pipenv
def test_rulename_space_is_normalized():
    Validator(schema={"field": {"default setter": lambda x: x, "type": "string"}})
コード例 #25
0
def test_allow_unknown_with_purge_unknown():
    validator = Validator(purge_unknown=True)
    schema = {'foo': {'type': 'dict', 'allow_unknown': True}}
    document = {'foo': {'bar': True}, 'bar': 'foo'}
    expected = {'foo': {'bar': True}}
    assert_normalized(document, expected, schema, validator)
コード例 #26
0
def test_allow_unknown_wo_schema():
    # https://github.com/pyeve/cerberus/issues/302
    v = Validator({'a': {'type': 'dict', 'allow_unknown': True}})
    v({'a': {}})
コード例 #27
0
ファイル: test_schema.py プロジェクト: wwjiang007/pipenv
def test_expansion_in_nested_schema():
    schema = {'detroit': {'schema': {'anyof_regex': ['^Aladdin', 'Sane$']}}}
    v = Validator(schema)
    assert v.schema['detroit']['schema'] == {
        'anyof': [{'regex': '^Aladdin'}, {'regex': 'Sane$'}]
    }
コード例 #28
0
ファイル: test_schema.py プロジェクト: wwjiang007/pipenv
def test_repr():
    v = Validator({'foo': {'type': 'string'}})
    assert repr(v.schema) == "{'foo': {'type': 'string'}}"
コード例 #29
0
ファイル: test_registries.py プロジェクト: wwjiang007/pipenv
def test_recursion():
    rules_set_registry.add('self', {'type': 'dict', 'allow_unknown': 'self'})
    v = Validator(allow_unknown='self')
    assert_success({0: {1: {2: {}}}}, {}, v)
コード例 #30
0
def test_purge_unknown():
    validator = Validator(purge_unknown=True)
    schema = {'foo': {'type': 'string'}}
    document = {'bar': 'foo'}
    expected = {}
    assert_normalized(document, expected, schema, validator)