summaryrefslogtreecommitdiff
path: root/jsonschema/_types.py
blob: 50bcf99c98c3fa5af7f995b82b00fec6e4b92f85 (plain)
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
import numbers

from pyrsistent import pmap
import attr

from jsonschema.exceptions import UndefinedTypeCheck


def is_array(checker, instance):
    return isinstance(instance, list)


def is_bool(checker, instance):
    return isinstance(instance, bool)


def is_integer(checker, instance):
    # bool inherits from int, so ensure bools aren't reported as ints
    if isinstance(instance, bool):
        return False
    return isinstance(instance, int)


def is_null(checker, instance):
    return instance is None


def is_number(checker, instance):
    # bool inherits from int, so ensure bools aren't reported as ints
    if isinstance(instance, bool):
        return False
    return isinstance(instance, numbers.Number)


def is_object(checker, instance):
    return isinstance(instance, dict)


def is_string(checker, instance):
    return isinstance(instance, str)


def is_any(checker, instance):
    return True


@attr.s(frozen=True)
class TypeChecker(object):
    """
    A ``type`` property checker.

    A `TypeChecker` performs type checking for an `IValidator`. Type
    checks to perform are updated using `TypeChecker.redefine` or
    `TypeChecker.redefine_many` and removed via `TypeChecker.remove`.
    Each of these return a new `TypeChecker` object.

    Arguments:

        type_checkers (dict):

            The initial mapping of types to their checking functions.
    """
    _type_checkers = attr.ib(default=pmap(), converter=pmap)

    def is_type(self, instance, type):
        """
        Check if the instance is of the appropriate type.

        Arguments:

            instance (object):

                The instance to check

            type (str):

                The name of the type that is expected.

        Returns:

            bool: Whether it conformed.


        Raises:

            `jsonschema.exceptions.UndefinedTypeCheck`:
                if type is unknown to this object.
        """
        try:
            fn = self._type_checkers[type]
        except KeyError:
            raise UndefinedTypeCheck(type)

        return fn(self, instance)

    def redefine(self, type, fn):
        """
        Produce a new checker with the given type redefined.

        Arguments:

            type (str):

                The name of the type to check.

            fn (collections.abc.Callable):

                A function taking exactly two parameters - the type
                checker calling the function and the instance to check.
                The function should return true if instance is of this
                type and false otherwise.

        Returns:

            A new `TypeChecker` instance.
        """
        return self.redefine_many({type: fn})

    def redefine_many(self, definitions=()):
        """
        Produce a new checker with the given types redefined.

        Arguments:

            definitions (dict):

                A dictionary mapping types to their checking functions.

        Returns:

            A new `TypeChecker` instance.
        """
        return attr.evolve(
            self, type_checkers=self._type_checkers.update(definitions),
        )

    def remove(self, *types):
        """
        Produce a new checker with the given types forgotten.

        Arguments:

            types (~collections.abc.Iterable):

                the names of the types to remove.

        Returns:

            A new `TypeChecker` instance

        Raises:

            `jsonschema.exceptions.UndefinedTypeCheck`:

                if any given type is unknown to this object
        """

        checkers = self._type_checkers
        for each in types:
            try:
                checkers = checkers.remove(each)
            except KeyError:
                raise UndefinedTypeCheck(each)
        return attr.evolve(self, type_checkers=checkers)


draft3_type_checker = TypeChecker(
    {
        u"any": is_any,
        u"array": is_array,
        u"boolean": is_bool,
        u"integer": is_integer,
        u"object": is_object,
        u"null": is_null,
        u"number": is_number,
        u"string": is_string,
    },
)
draft4_type_checker = draft3_type_checker.remove(u"any")
draft6_type_checker = draft4_type_checker.redefine(
    u"integer",
    lambda checker, instance: (
        is_integer(checker, instance) or
        isinstance(instance, float) and instance.is_integer()
    ),
)
draft7_type_checker = draft6_type_checker