Package konval :: Module sizeval
[hide private]
[frames] | no frames]

Source Code for Module konval.sizeval

  1  """ 
  2  Validators that check value magnitude. 
  3   
  4  """ 
  5   
  6  __docformat__ = "restructuredtext en" 
  7   
  8   
  9  ### IMPORTS 
 10   
 11  from basevalidator import BaseValidator 
 12   
 13   
 14  ### CONSTANTS & DEFINES 
 15   
 16  ### IMPLEMENTATION ### 
 17   
18 -class IsInRange (BaseValidator):
19 """ 20 Only allow values between certain inclusive bounds. 21 """
22 - def __init__ (self, min=None, max=None):
23 self.min = min 24 self.max = max
25
26 - def validate_value (self, value):
27 if self.min is not None: 28 assert self.min <= value, "%s is lower than %s" % (value, self.min) 29 if self.max is not None: 30 assert value <= self.max, "%s is higher than %s" % (value, self.max) 31 return True
32
33 - def make_validation_error_msg (self, bad_val, err):
34 """ 35 Generate an meaningful error message for a range problem. 36 """ 37 if err: 38 return str (err) 39 else: 40 return BaseValidator.make_validation_error_msg (self, bad_val, err)
41 42 Range = IsInRange 43 44
45 -class IsEqualOrMore (IsInRange):
46 - def __init__ (self, min):
47 IsInRange.__init__ (self, min=min, max=None)
48 49 MinValue = IsEqualOrMore 50 51
52 -class IsEqualOrLess (IsInRange):
53 - def __init__ (self, max):
54 IsInRange.__init__ (self, min=None, max=max)
55 56 MaxValue = IsEqualOrLess 57 58
59 -class IsBetween (IsInRange):
60 """ 61 Only allow values between certain exclusive bounds. 62 """
63 - def __init__ (self, min=None, max=None):
64 IsInRange.__init__ (min=min, max=max)
65
66 - def validate_value (self, value):
67 if self.min is not None: 68 assert self.min < value, "%s is lower or equal to %s" % (value, self.min) 69 if self.max is not None: 70 assert value < self.max, "%s is higher or equal to %s" % (value, self.max) 71 return True
72 73 ExclusiveRange = IsBetween 74 75
76 -class Length (BaseValidator):
77 """ 78 Only allow values of a certain sizes. 79 80 Length limitations are expressed as (inclusive) minimum and maximum sizes. 81 This is most useful for strings, but could be used for lists. 82 """
83 - def __init__ (self, min=None, max=None):
84 self.min = min 85 self.max = max
86
87 - def make_validation_error_msg (self, bad_val, err):
88 """ 89 Generate an meaningful error message for a length problem. 90 """ 91 if err: 92 return str (err) 93 else: 94 return BaseValidator.make_validation_error_msg (self, bad_val, err)
95 96
97 - def validate_value (self, value):
98 if self.min is not None: 99 assert self.min <= len (value), "%s is shorter than %s" % (value, self.min) 100 if self.max is not None: 101 assert len (value) <= self.max, "%s is longer than %s" % (value, self.max) 102 return True
103 104 105 106 ## DEBUG & TEST ### 107 108 if __name__ == "__main__": 109 import doctest 110 doctest.testmod() 111 112 113 114 ### END ####################################################################### 115