Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/tutorius/constraints.py
blob: ffb646df764dbb01e60b14f82a2ee86ad3ad68fb (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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
# Copyright (C) 2009, Tutorius.org
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
"""
Constraints

Defines a set of constraints with their related errors. These constraints are
made to be used inside TutoriusProperties in order to limit the values that
they might take. They can also be used to enforce a particular format or type
for some properties.
"""

# For the File Constraint
import os
# For the Resource Constraint
import re

class ConstraintException(Exception):
    """
    Parent class for all constraint exceptions
    """
    pass

class Constraint():
    """
    Basic block for defining constraints on a TutoriusProperty. Every class
    inheriting from Constraint will have a validate function that will be
    executed when the property's value is to be changed.
    """
    def validate(self, value):
        """
        This function receives the value that is proposed as a new value for
        the property. It needs to raise an Error in the case where the value
        does not respect this constraint.
        """
        raise NotImplementedError("Unable to validate a base Constraint")
    
class TypeConstraintError(ConstraintException):
    pass

class TypeConstraint(Constraint):
    """
    Base class for ensuring that all the values have a specific Python type.
    """
    def __init__(self, expected_type):
        """
        Creates a new type constraint to restrict accepted values to a certain type.
        @param expected_type A string describing the name of the type to
                             enforce, or a full-blown type object. If a type
                             object is used, all objects that inherit from this
                             type will pass.
        """
        self._expected_type = expected_type

    def validate(self, value):
        if type(self._expected_type) == str:
            if self._expected_type == type(value).__name__:
                return value
        else:
            if isinstance(value, self._expected_type):
                return value
        raise TypeConstraintError("Wrong type for value %s, got type %s; expected %s" % \
                    (str(value),
                     type(value).__name__,
                     self._expected_type)) 

class IntTypeConstraint(TypeConstraint):
    """
    Forces the value to be a Python int.
    """
    def __init__(self):
        TypeConstraint.__init__(self, 'int')

class FloatTypeConstraint(TypeConstraint):
    """
    Forces the value to be a Python float.
    """
    def __init__(self):
        TypeConstraint.__init__(self, 'float')

class StringTypeConstraint(TypeConstraint):
    """
    Forces the value to be a Python string.
    """
    def __init__(self):
        TypeConstraint.__init__(self, 'str')

class TupleTypeConstraint(TypeConstraint):
    """
    Forces the value to be a Python tuple.
    """
    def __init__(self):
        TypeConstraint.__init__(self, 'tuple')

class ListTypeConstraint(TypeConstraint):
    """
    Forces the value to be a Python list.
    """
    def __init__(self):
        TypeConstraint.__init__(self, 'list')

class BoolTypeConstraint(TypeConstraint):
    def __init__(self):
        TypeConstraint.__init__(self, 'bool')

class MultiTypeConstraint(Constraint):
    """
    Base class for ensuring that all the values have a specific Python type.
    """
    def __init__(self, expected_types_list):
        """
        Creates a new type constraint to restrict accepted values to a certain type.
        @param expected_types_list A list of strings describing the possible names 
                                   of the types to enforce, or a list of type
                                   objects. If there are type objects, then
                                   value inheriting from this type will be
                                   validated.
        """
        self._expected_types_list = expected_types_list
        
    def validate(self, value):
        for expected_type in self._expected_types_list:
            if type(expected_type).__name__ == 'str':
                if expected_type == type(value).__name__:
                    return value
            else:
                if isinstance(value, expected_type):
                    return value
        raise TypeConstraintError("Wrong type for value %s, got type %s; expected one in %s" % \
                    (str(value),
                     type(value).__name__,
                     str(self._expected_types_list)))

class ArrayTypeConstraint(MultiTypeConstraint):
    """ Forces the value to either be a list or a tuple."""
    def __init__(self):
        MultiTypeConstraint.__init__(self, ['list', 'tuple'])

class SequenceTypeConstraint(MultiTypeConstraint):
    def __init__(self):
        MultiTypeConstraint.__init__(self, ['list', 'tuple', 'str'])

class ValueConstraint(Constraint):
    """
    A value constraint contains a _limit member that can be used in a children
    class as a basic value. See UpperLimitConstraint for an exemple.
    """
    def __init__(self, limit):
        self.limit = limit

class UpperLimitConstraintError(ConstraintException):
    pass

class UpperLimitConstraint(ValueConstraint):
    def validate(self, value):
        """
        Evaluates whether the given value is smaller than the limit.
        
        @raise UpperLimitConstraintError When the value is strictly higher than
        the limit.
        """
        if self.limit is not None:
            if self.limit >= value:
                return
            raise UpperLimitConstraintError()
        return

class LowerLimitConstraintError(ConstraintException):
    pass

class LowerLimitConstraint(ValueConstraint):
    def validate(self, value):
        """
        If the value is lower than the limit, this function raises an error.
        
        @raise LowerLimitConstraintError When the value is strictly smaller
        than the limit.
        """
        if self.limit is not None:
            if value >= self.limit:
                return
            raise LowerLimitConstraintError()
        return

class MaxSizeConstraintError(ConstraintException):
    pass
    
class MaxSizeConstraint(ValueConstraint):
    def validate(self, value):
        """
        Evaluate whether a given object is smaller than the given size when
        run through len(). Great for string, lists and the like. ;)
        
        @raise SizeConstraintError If the length of the value is strictly
        bigger than the limit.
        """
        if self.limit is not None:
            if self.limit >= len(value):
                return
            raise MaxSizeConstraintError("Setter : trying to set value of length %d while limit is %d"%(len(value), self.limit))
        return

class MinSizeConstraintError(ConstraintException):
    pass
    
class MinSizeConstraint(ValueConstraint):
    def validate(self, value):
        """
        Evaluate whether a given object is smaller than the given size when
        run through len(). Great for string, lists and the like. ;)
        
        @raise SizeConstraintError If the length of the value is strictly
        bigger than the limit.
        """
        if self.limit is not None:
            if self.limit <= len(value):
                return
            raise MinSizeConstraintError("Setter : trying to set value of length %d while limit is %d"%(len(value), self.limit))
        return

class ColorConstraintError(ConstraintException):
    pass

class ColorArraySizeError(ColorConstraintError):
    pass
    
class ColorTypeError(ColorConstraintError):
    pass

class ColorValueError(ColorConstraintError):
    pass

class ColorConstraint(Constraint):
    """
    Validates that the value is an array of size 3 with three numbers between 
    0 and 255 (inclusively) in it.
    
    """
    def validate(self, value):
        if len(value) != 3:
            raise ColorArraySizeError("The value is not an array of size 3")
        
        if not (type(value[0]) == type(22) and type(value[1]) ==  type(22) and type(value[2]) == type(22)):
            raise ColorTypeError("Not all the elements of the array are integers")
        
        if value[0] > 255 or value[0] <0:
            raise ColorValueError("Red value is not between 0 and 255")

        if value[1] > 255 or value[1] <0:
            raise ColorValueError("Green value is not between 0 and 255")
        
        if value[2] > 255 or value[2] <0:
            raise ColorValueError("Blue value is not between 0 and 255")
        
        return
    
class BooleanConstraintError(ConstraintException):
    pass

class BooleanConstraint(Constraint):
    """
    Validates that the value is either True or False.
    """
    def validate(self, value):
        if value == True or value == False:
            return
        raise BooleanConstraintError("Value is not True or False")
    
class EnumConstraintError(ConstraintException):
    pass

class EnumConstraint(Constraint):
    """
    Validates that the value is part of a set of well-defined values.
    """
    def __init__(self, accepted_values):
        """
        Creates the constraint and stores the list of accepted values.
        
        @param correct_values A list that contains all the values that will
        be declared as satisfying the constraint
        """
        self._accepted_values = accepted_values
        
    def validate(self, value):
        """
        Ensures that the value that is passed is part of the list of accepted 
        values.
        """
        if not value in self._accepted_values:
            raise EnumConstraintError("Value is not part of the enumeration")
        return
    
class FileConstraintError(ConstraintException):
    pass
    
class FileConstraint(Constraint):
    """
    Ensures that the string given corresponds to an existing file on disk.
    """
    def validate(self, value):
        # TODO : Decide on the architecture for file retrieval on disk
        # Relative paths? From where? Support macros?
        # FIXME This is a hack to make cases where a default file is not valid
        # work. It allows None values to be validated, though
        if value is None:
            return
        if not os.path.isfile(value):
            raise FileConstraintError("Non-existing file : %s"%value)
        return
    
class ResourceConstraintError(ConstraintException):
    pass

class ResourceConstraint(Constraint):
    """
    Ensures that the value is looking like a resource name, like
    <filename>_<GUID>[.<extension>]. We are not validating that this is a
    valid resource for the reason that the property does not have any notion
    of tutorial guid.

    TODO : Find a way to properly validate resources by looking them up in the
            Vault.
    """
    
    # Regular expression to parse a resource-like name
    resource_regexp_text = "(.+)_([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})(\..*)?$"
    resource_regexp = re.compile(resource_regexp_text)
    
    def validate(self, value):
        # TODO : Validate that we will not use an empty resource or if we can
        # have transitory resource names
        if value is None:
            raise ResourceConstraintError("Resource not allowed to have a null value!")

        # Special case : We allow the empty resource name for now
        if value == "":
            return value

        # Attempt to see if the value has a resource name inside it
        match = self.resource_regexp.search(value)

        # If there was no match on the reg exp
        if not match:
            raise ResourceConstraintError("Resource name does not seem to be valid : %s" % value)

        # If the name matched, then the value is _PROBABLY_ good
        return value