File: test_customization.py

package info (click to toggle)
python-cerberus 1.3.7-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 7,532 kB
  • sloc: python: 5,239; makefile: 130
file content (120 lines) | stat: -rw-r--r-- 3,911 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# -*- coding: utf-8 -*-

import pytest

import cerberus
from cerberus.tests import assert_fail, assert_success
from cerberus.tests.conftest import sample_schema


def test_contextual_data_preservation():
    with pytest.deprecated_call():

        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)


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
@pytest.mark.parametrize('rule', ('check_with', 'validator'))
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")

    if rule == "validator":
        with pytest.deprecated_call():
            v = MyValidator(schema={'amount': {rule: 'oddity'}})
    else:
        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
@pytest.mark.parametrize('rule', ('check_with', 'validator'))
def test_validator_method(rule):
    class MyValidator(cerberus.Validator):
        def _validator_oddity(self, field, value):
            if not value & 1:
                self._error(field, "Must not be an odd number")

    if rule == "validator":
        with pytest.deprecated_call():
            v = MyValidator(schema={'amount': {rule: 'oddity'}})
    else:
        v = MyValidator(schema={'amount': {rule: 'oddity'}})

    with pytest.deprecated_call():
        assert_success(document={'amount': 1}, validator=v)
        assert_fail(
            document={'amount': 2},
            validator=v,
            error=(
                'amount',
                (),
                cerberus.errors.CUSTOM,
                None,
                ('Must not be an odd number',),
            ),
        )


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'})