~ubuntu-branches/ubuntu/precise/checkbox/precise

« back to all changes in this revision

Viewing changes to checkbox/schema.py

  • Committer: Bazaar Package Importer
  • Author(s): Marc Tardif
  • Date: 2009-01-20 16:46:15 UTC
  • Revision ID: james.westby@ubuntu.com-20090120164615-7iz6nmlef41h4vx2
Tags: 0.4
* Setup bzr-builddeb in native mode.
* Removed LGPL notice from the copyright file.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#
 
2
# Copyright (c) 2008 Canonical
 
3
#
 
4
# Written by Marc Tardif <marc@interunion.ca>
 
5
#
 
6
# This file is part of Checkbox.
 
7
#
 
8
# Checkbox is free software: you can redistribute it and/or modify
 
9
# it under the terms of the GNU General Public License as published by
 
10
# the Free Software Foundation, either version 3 of the License, or
 
11
# (at your option) any later version.
 
12
#
 
13
# Checkbox is distributed in the hope that it will be useful,
 
14
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
15
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
16
# GNU General Public License for more details.
 
17
#
 
18
# You should have received a copy of the GNU General Public License
 
19
# along with Checkbox.  If not, see <http://www.gnu.org/licenses/>.
 
20
#
 
21
class InvalidError(Exception):
 
22
    """Raised when invalid input is received."""
 
23
    pass
 
24
 
 
25
 
 
26
class Constant(object):
 
27
    """Something that must be equal to a constant value."""
 
28
    def __init__(self, value):
 
29
        self.value = value
 
30
 
 
31
    def coerce(self, value):
 
32
        if value != self.value:
 
33
            raise InvalidError("%r != %r" % (value, self.value))
 
34
        return value
 
35
 
 
36
 
 
37
class Any(object):
 
38
    """Something which must apply to any of a number of different schemas."""
 
39
    def __init__(self, *schemas):
 
40
        """
 
41
        @param schemas: Any number of other schema objects.
 
42
        """
 
43
        self.schemas = schemas
 
44
 
 
45
    def coerce(self, value):
 
46
        """
 
47
        The result of the first schema which doesn't raise
 
48
        L{InvalidError} from its C{coerce} method will be returned.
 
49
        """
 
50
        for schema in self.schemas:
 
51
            try:
 
52
                return schema.coerce(value)
 
53
            except InvalidError:
 
54
                pass
 
55
        raise InvalidError("%r did not match any schema in %s"
 
56
                           % (value, self.schemas))
 
57
 
 
58
class Bool(object):
 
59
    """Something that must be a C{bool}."""
 
60
    def coerce(self, value):
 
61
        if not isinstance(value, bool):
 
62
            raise InvalidError("%r is not a bool" % (value,))
 
63
        return value
 
64
 
 
65
 
 
66
class Int(object):
 
67
    """Something that must be an C{int} or C{long}."""
 
68
    def coerce(self, value):
 
69
        if not isinstance(value, (int, long)):
 
70
            raise InvalidError("%r isn't an int or long" % (value,))
 
71
        return value
 
72
 
 
73
 
 
74
class Float(object):
 
75
    """Something that must be an C{int}, C{long}, or C{float}."""
 
76
    def coerce(self, value):
 
77
        if not isinstance(value, (int, long, float)):
 
78
            raise InvalidError("%r isn't a float" % (value,))
 
79
        return value
 
80
 
 
81
 
 
82
class String(object):
 
83
    """Something that must be a C{str}."""
 
84
    def coerce(self, value):
 
85
        if not isinstance(value, str):
 
86
            raise InvalidError("%r isn't a str" % (value,))
 
87
        return value
 
88
 
 
89
 
 
90
class Unicode(object):
 
91
    """Something that must be a C{unicode}."""
 
92
    def coerce(self, value):
 
93
        if not isinstance(value, unicode):
 
94
            raise InvalidError("%r isn't a unicode" % (value,))
 
95
        return value
 
96
 
 
97
 
 
98
class UnicodeOrString(object):
 
99
    """Something that must be a C{unicode} or {str}.
 
100
 
 
101
    If the value is a C{str}, it will automatically be decoded.
 
102
    """
 
103
 
 
104
    def __init__(self, encoding):
 
105
        """
 
106
        @param encoding: The encoding to automatically decode C{str}s with.
 
107
        """
 
108
        self.encoding = encoding
 
109
 
 
110
    def coerce(self, value):
 
111
        if isinstance(value, str):
 
112
            try:
 
113
                value = value.decode(self.encoding)
 
114
            except UnicodeDecodeError, e:
 
115
                raise InvalidError("%r can't be decoded: %s" % (value, str(e)))
 
116
        if not isinstance(value, unicode):
 
117
            raise InvalidError("%r isn't a unicode" % (value,))
 
118
        return value
 
119
 
 
120
 
 
121
class List(object):
 
122
    """Something which must be a C{list}."""
 
123
    def __init__(self, schema):
 
124
        """
 
125
        @param schema: The schema that all values of the list must match.
 
126
        """
 
127
        self.schema = schema
 
128
 
 
129
    def coerce(self, value):
 
130
        if not isinstance(value, list):
 
131
            raise InvalidError("%r is not a list" % (value,))
 
132
        new_list = list(value)
 
133
        for i, subvalue in enumerate(value):
 
134
            try:
 
135
                new_list[i] = self.schema.coerce(subvalue)
 
136
            except InvalidError, e:
 
137
                raise InvalidError(
 
138
                    "%r could not coerce with %s: %s"
 
139
                    % (subvalue, self.schema, e))
 
140
        return new_list
 
141
 
 
142
 
 
143
class Tuple(object):
 
144
    """Something which must be a fixed-length tuple."""
 
145
    def __init__(self, *schema):
 
146
        """
 
147
        @param schema: A sequence of schemas, which will be applied to
 
148
            each value in the tuple respectively.
 
149
        """
 
150
        self.schema = schema
 
151
 
 
152
    def coerce(self, value):
 
153
        if not isinstance(value, tuple):
 
154
            raise InvalidError("%r is not a tuple" % (value,))
 
155
        if len(value) != len(self.schema):
 
156
            raise InvalidError("Need %s items, got %s in %r"
 
157
                               % (len(self.schema), len(value), value))
 
158
        new_value = []
 
159
        for schema, value in zip(self.schema, value):
 
160
            new_value.append(schema.coerce(value))
 
161
        return tuple(new_value)
 
162
 
 
163
 
 
164
class KeyDict(object):
 
165
    """Something which must be a C{dict} with defined keys.
 
166
 
 
167
    The keys must be constant and the values must match a per-key schema.
 
168
    """
 
169
    def __init__(self, schema, optional=None):
 
170
        """
 
171
        @param schema: A dict mapping keys to schemas that the values
 
172
            of those keys must match.
 
173
        """
 
174
        if optional is None:
 
175
            optional = []
 
176
        self.optional = set(optional)
 
177
        self.schema = schema
 
178
 
 
179
    def coerce(self, value):
 
180
        new_dict = {}
 
181
        if not isinstance(value, dict):
 
182
            raise InvalidError("%r is not a dict." % (value,))
 
183
        for k, v in value.iteritems():
 
184
            if k not in self.schema:
 
185
                raise InvalidError("%r is not a valid key as per %r"
 
186
                                   % (k, self.schema))
 
187
            try:
 
188
                new_dict[k] = self.schema[k].coerce(v)
 
189
            except InvalidError, e:
 
190
                raise InvalidError(
 
191
                    "Value of %r key of dict %r could not coerce with %s: %s"
 
192
                    % (k, value, self.schema[k], e))
 
193
        new_keys = set(new_dict.keys())
 
194
        required_keys = set(self.schema.keys()) - self.optional
 
195
        missing = required_keys - new_keys
 
196
        if missing:
 
197
            raise InvalidError("Missing keys %s" % (missing,))
 
198
        return new_dict
 
199
 
 
200
 
 
201
class Dict(object):
 
202
    """Something which must be a C{dict} with arbitrary keys."""
 
203
 
 
204
    def __init__(self, key_schema, value_schema):
 
205
        """
 
206
        @param key_schema: The schema that keys must match.
 
207
        @param value_schema: The schema that values must match.
 
208
        """
 
209
        self.key_schema = key_schema
 
210
        self.value_schema = value_schema
 
211
 
 
212
    def coerce(self, value):
 
213
        if not isinstance(value, dict):
 
214
            raise InvalidError("%r is not a dict." % (value,))
 
215
        new_dict = {}
 
216
        for k, v in value.items():
 
217
            new_dict[self.key_schema.coerce(k)] = self.value_schema.coerce(v)
 
218
        return new_dict