-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathvalidation.py
executable file
·1560 lines (1179 loc) · 46.7 KB
/
validation.py
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#
# Copyright 2007 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Validation tools for generic object structures.
This library is used for defining classes with constrained attributes.
Attributes are defined on the class which contains them using validators.
Although validators can be defined by any client of this library, a number
of standard validators are provided here.
Validators can be any callable that takes a single parameter which checks
the new value before it is assigned to the attribute. Validators are
permitted to modify a received value so that it is appropriate for the
attribute definition. For example, using int as a validator will cast
a correctly formatted string to a number, or raise an exception if it
can not. This is not recommended, however. The correct way to use a
validator that ensures the correct type is to use the `Type` validator.
This validation library is mainly intended for use with the YAML object
builder. See the `yaml_object` module.
"""
import re
import google
from ruamel import yaml
import six
class SortedDict(dict):
"""Represents a dict with a particular key order for yaml representing."""
def __init__(self, keys, data):
super(SortedDict, self).__init__()
self.keys = keys
self.update(data)
def ordered_items(self):
result = []
for key in self.keys:
if self.get(key) is not None:
result.append((key, self.get(key)))
return result
class ItemDumper(yaml.SafeDumper):
"""For dumping `validation.Items`. Respects `SortedDict` key ordering."""
def represent_mapping(self, tag, mapping, flow_style=None):
if hasattr(mapping, 'ordered_items'):
return super(ItemDumper, self).represent_mapping(
tag, mapping.ordered_items(), flow_style=flow_style)
return super(ItemDumper, self).represent_mapping(
tag, mapping, flow_style=flow_style)
ItemDumper.add_representer(
SortedDict, ItemDumper.represent_dict)
class Error(Exception):
"""Base class for all package errors."""
class AttributeDefinitionError(Error):
"""An error occurred in the definition of class attributes."""
class ValidationError(Error):
"""Base class for raising exceptions during validation."""
def __init__(self, message, cause=None):
"""Initialize exception."""
if hasattr(cause, 'args') and cause.args:
Error.__init__(self, message, *cause.args)
else:
Error.__init__(self, message)
self.message = message
self.cause = cause
def __str__(self):
return str(self.message)
class MissingAttribute(ValidationError):
"""Raised when a required attribute is missing from object."""
def __init__(self, key):
msg = 'Missing required value [{}].'.format(key)
super(MissingAttribute, self).__init__(msg)
def AsValidator(validator):
"""Wrap various types as instances of a validator.
Used to allow shorthand for common validator types. It
converts the following types to the following Validators:
* strings -> Regex
* type -> Type
* collection -> Options
* Validator -> Itself
Args:
validator: Object to wrap in a validator.
Returns:
Validator instance that wraps the given value.
Raises:
AttributeDefinitionError: If `validator` is not one of the above described
types.
"""
if (_IsPy2Basestring(validator)
or validator == six.string_types):
return StringValidator()
if isinstance(validator, (str, six.text_type)):
return Regex(validator, type(validator))
if isinstance(validator, type):
return Type(validator)
if isinstance(validator, (list, tuple, set)):
return Options(*tuple(validator))
if isinstance(validator, Validator):
return validator
else:
raise AttributeDefinitionError('%s is not a valid validator' %
str(validator))
def _SimplifiedValue(validator, value):
"""Convert any value to simplified collections and basic types.
Args:
validator: An instance of `Validator` that corresponds with 'value'.
May also be 'str' or 'int' if those were used instead of a full
Validator.
value: Value to convert to simplified collections.
Returns:
The value as a dictionary if it is a `ValidatedBase` object. A list of
items converted to simplified collections if value is a list
or a tuple. Otherwise, just the value.
"""
if isinstance(value, ValidatedBase):
return value.ToDict()
elif isinstance(value, (list, tuple)):
return [_SimplifiedValue(validator, item) for item in value]
elif isinstance(validator, Validator):
return validator.ToValue(value)
return value
class ValidatedBase(object):
"""Base class for all validated objects."""
@classmethod
def GetValidator(cls, key):
"""Safely get the Validator corresponding to the given key.
This function should be overridden by subclasses
Args:
key: The attribute or item to get a validator for.
Returns:
Validator associated with key or attribute.
Raises:
ValidationError: If the requested key is illegal.
"""
raise NotImplementedError('Subclasses of ValidatedBase must '
'override GetValidator.')
def SetMultiple(self, attributes):
"""Set multiple values on Validated instance.
All attributes will be validated before being set.
Args:
attributes: A dict of attributes/items to set.
Raises:
ValidationError: When no validated attribute exists on class.
"""
for key, value in attributes.items():
self.Set(key, value)
def Set(self, key, value):
"""Set a single value on Validated instance.
This method should be overridded by sub-classes.
This method can only be used to assign validated attributes/items.
Args:
key: The name of the attributes
value: The value to set
Raises:
ValidationError: When no validated attribute exists on class.
"""
raise NotImplementedError('Subclasses of ValidatedBase must override Set.')
def CheckInitialized(self):
"""Checks for missing or conflicting attributes.
Subclasses should override this function and raise an exception for
any errors. Always run this method when all assignments are complete.
Raises:
ValidationError: When there are missing or conflicting attributes.
"""
def ToDict(self):
"""Convert `ValidatedBase` object to a dictionary.
Recursively traverses all of its elements and converts everything to
simplified collections.
Subclasses should override this method.
Returns:
A dictionary mapping all attributes to simple values or collections.
"""
raise NotImplementedError('Subclasses of ValidatedBase must '
'override ToDict.')
def ToYAML(self):
"""Print validated object as simplified YAML.
Returns:
Object as a simplified YAML string compatible with parsing using the
`SafeLoader`.
"""
return yaml.dump(self.ToDict(),
default_flow_style=False,
Dumper=ItemDumper)
def GetWarnings(self):
"""Return all the warnings we've got, along with their associated fields.
Returns:
A list of tuples of (dotted_field, warning), both strings.
"""
raise NotImplementedError('Subclasses of ValidatedBase must '
'override GetWarnings')
class Validated(ValidatedBase):
"""Base class for classes that require validation.
A class which intends to use validated fields should sub-class itself from
this class. Each class should define an 'ATTRIBUTES' class variable which
should be a map from attribute name to its validator. For example:
```
class Story(Validated):
ATTRIBUTES = {'title': Type(str),
'authors': Repeated(Type(str)),
'isbn': Optional(Type(str)),
'pages': Type(int),
}
```
Attributes that are not listed under `ATTRIBUTES` work like normal and are
not validated upon assignment.
"""
ATTRIBUTES = None
def __init__(self, **attributes):
"""Constructor for Validated classes.
This constructor can optionally assign values to the class via its
keyword arguments.
Raises:
AttributeDefinitionError: When class instance is missing `ATTRIBUTE`
definition or when `ATTRIBUTE` is of the wrong type.
"""
super(Validated, self).__init__()
if not isinstance(self.ATTRIBUTES, dict):
raise AttributeDefinitionError(
'The class %s does not define an ATTRIBUTE variable.'
% self.__class__)
for key in self.ATTRIBUTES.keys():
object.__setattr__(self, key, self.GetValidator(key).default)
self.SetMultiple(attributes)
@classmethod
def GetValidator(cls, key):
"""Safely get the underlying attribute definition as a `Validator`.
Args:
key: Name of attribute to get.
Returns:
Validator associated with key or attribute value wrapped in a
validator.
Raises:
ValidationError: if no such attribute exists.
"""
if key not in cls.ATTRIBUTES:
raise ValidationError(
'Unexpected attribute \'%s\' for object of type %s.' %
(key, cls.__name__))
return AsValidator(cls.ATTRIBUTES[key])
def GetWarnings(self):
ret = []
for key in self.ATTRIBUTES.keys():
ret.extend(self.GetValidator(key).GetWarnings(
self.GetUnnormalized(key), key, self))
return ret
def Set(self, key, value):
"""Set a single value on `Validated` instance.
This method can only be used to assign validated attributes.
Args:
key: The name of the attributes
value: The value to set
Raises:
`ValidationError` when no validated attribute exists on class.
"""
setattr(self, key, value)
def GetUnnormalized(self, key):
"""Get a single value on the `Validated` instance, without normalizing."""
validator = self.GetValidator(key)
try:
return super(Validated, self).__getattribute__(key)
except AttributeError:
return validator.default
def Get(self, key):
"""Get a single value on Validated instance.
This method can only be used to retrieve validated attributes.
Args:
key: The name of the attributes
Raises:
`ValidationError` when no validated attribute exists on class.
"""
self.GetValidator(key)
return getattr(self, key)
def __getattribute__(self, key):
ret = super(Validated, self).__getattribute__(key)
if key in ['ATTRIBUTES', 'GetValidator', '__name__', '__class__']:
return ret
try:
validator = self.GetValidator(key)
except ValidationError:
return ret
if isinstance(validator, Normalized):
return validator.Get(ret, key, self)
return ret
def CheckInitialized(self):
for key in self.ATTRIBUTES.keys():
value = self.GetUnnormalized(key)
self.GetValidator(key).CheckFieldInitialized(value, key, self)
def __setattr__(self, key, value):
"""Set attribute.
Setting a value on an object of this type will only work for attributes
defined in `ATTRIBUTES`. To make other assignments possible it is necessary
to override this method in subclasses.
It is important that assignment is restricted in this way because
this validation is used as validation for parsing. Absent this restriction
it would be possible for method names to be overwritten.
Args:
key: Name of attribute to set.
value: The attribute's new value or None to unset.
Raises:
ValidationError: When trying to assign to an attribute
that does not exist.
"""
if value is not None:
value = self.GetValidator(key)(value, key)
object.__setattr__(self, key, value)
def __str__(self):
"""Formatted view of validated object and nested values."""
return repr(self)
def __repr__(self):
"""Formatted view of validated object and nested values."""
values = [(attr, getattr(self, attr)) for attr in self.ATTRIBUTES.keys()]
dent = ' '
value_list = []
for attr, value in values:
value_list.append('\n%s%s=%s' % (dent, attr, value))
return "<%s %s\n%s>" % (self.__class__.__name__, ' '.join(value_list), dent)
def __eq__(self, other):
"""Equality operator.
Comparison is done by comparing all attribute values to those in the other
instance. Objects which are not of the same type are not equal.
Args:
other: Other object to compare against.
Returns:
`True` if validated objects are equal, else `False`.
"""
if type(self) != type(other):
return False
for key in self.ATTRIBUTES.keys():
if getattr(self, key) != getattr(other, key):
return False
return True
def __ne__(self, other):
"""Inequality operator."""
return not self.__eq__(other)
def __hash__(self):
"""Hash function for using Validated objects in sets and maps.
Hash is done by hashing all keys and values and xor'ing them together.
Returns:
Hash of validated object.
"""
result = 0
for key in self.ATTRIBUTES.keys():
value = getattr(self, key)
if isinstance(value, list):
value = tuple(value)
result = result ^ hash(key) ^ hash(value)
return result
def ToDict(self):
"""Convert Validated object to a dictionary.
Recursively traverses all of its elements and converts everything to
simplified collections.
Returns:
A dict of all attributes defined in this classes `ATTRIBUTES` mapped
to its value. This structure is recursive in that Validated objects
that are referenced by this object and in lists are also converted to
dicts.
"""
result = {}
for name, validator in self.ATTRIBUTES.items():
value = self.GetUnnormalized(name)
if not(isinstance(validator, Validator) and value == validator.default):
result[name] = _SimplifiedValue(validator, value)
return result
class ValidatedDict(ValidatedBase, dict):
"""Base class for validated dictionaries.
You can control the keys and values that are allowed in the dictionary
by setting `KEY_VALIDATOR` and `VALUE_VALIDATOR` to subclasses of `Validator`
(or things that can be interpreted as validators, see `AsValidator`).
For example if you wanted only capitalized keys that map to integers
you could do:
```
class CapitalizedIntegerDict(ValidatedDict):
KEY_VALIDATOR = Regex('[A-Z].*')
VALUE_VALIDATOR = int # this gets interpreted to Type(int)
```
The following code would result in an error:
```
my_dict = CapitalizedIntegerDict()
my_dict['lowercase'] = 5 # Throws a validation exception
```
You can freely nest Validated and `ValidatedDict` inside each other so:
```
class MasterObject(Validated):
ATTRIBUTES = {'paramdict': CapitalizedIntegerDict}
```
Could be used to parse the following YAML:
```
paramdict:
ArbitraryKey: 323
AnotherArbitraryKey: 9931
```
"""
KEY_VALIDATOR = None
VALUE_VALIDATOR = None
def __init__(self, **kwds):
"""Construct a validated dict by interpreting the key and value validators.
Args:
**kwds: keyword arguments will be validated and put into the dict.
"""
super(ValidatedDict, self).__init__()
self.update(kwds)
@classmethod
def GetValidator(cls, key):
"""Check the key for validity and return a corresponding value validator.
Args:
key: The key that will correspond to the validator we are returning.
"""
key = AsValidator(cls.KEY_VALIDATOR)(key, 'key in %s' % cls.__name__)
return AsValidator(cls.VALUE_VALIDATOR)
def __setitem__(self, key, value):
"""Set an item.
Only attributes accepted by `GetValidator` and values that validate
with the validator returned from `GetValidator` are allowed to be set
in this dictionary.
Args:
key: Name of item to set.
value: Items new value.
Raises:
ValidationError: When trying to assign to a value that does not exist.
"""
dict.__setitem__(self, key, self.GetValidator(key)(value, key))
def setdefault(self, key, value=None):
"""Trap setdefaultss to ensure all key/value pairs are valid.
See the documentation for setdefault on dict for usage details.
Raises:
ValidationError: if the specified key is illegal or the
value invalid.
"""
return dict.setdefault(self, key, self.GetValidator(key)(value, key))
def update(self, other, **kwds):
"""Trap updates to ensure all key/value pairs are valid.
See the documentation for update on dict for usage details.
Raises:
ValidationError: if any of the specified keys are illegal or
values invalid.
"""
if hasattr(other, 'keys') and callable(getattr(other, 'keys')):
newother = {}
for k in other:
newother[k] = self.GetValidator(k)(other[k], k)
else:
newother = [(k, self.GetValidator(k)(v, k)) for (k, v) in other]
newkwds = {}
for k in kwds:
newkwds[k] = self.GetValidator(k)(kwds[k], k)
dict.update(self, newother, **newkwds)
def Set(self, key, value):
"""Set a single value on `Validated` instance.
This method checks that a given key and value are valid and if so
puts the item into this dictionary.
Args:
key: The name of the attributes.
value: The value to set.
Raises:
ValidationError: When no validated attribute exists on class.
"""
self[key] = value
def GetWarnings(self):
ret = []
for name, value in self.items():
ret.extend(self.GetValidator(name).GetWarnings(value, name, self))
return ret
def ToDict(self):
"""Convert `ValidatedBase` object to a dictionary.
Recursively traverses all of its elements and converts everything to
simplified collections.
Subclasses should override this method.
Returns:
A dictionary mapping all attributes to simple values or collections.
"""
result = {}
for name, value in self.items():
validator = self.GetValidator(name)
result[name] = _SimplifiedValue(validator, value)
return result
class Validator(object):
"""Validator base class.
Though any callable can be used as a validator, this class encapsulates the
case when a specific validator needs to hold a particular state or
configuration.
To implement `Validator` sub-class, override the validate method.
This class is permitted to change the ultimate value that is set to the
attribute if there is a reasonable way to perform the conversion.
"""
expected_type = object
def __init__(self, default=None):
"""Constructor.
Args:
default: Default assignment is made during initialization and will
not pass through validation.
"""
self.default = default
def __call__(self, value, key='???'):
"""Main interface to validator is call mechanism."""
return self.Validate(value, key)
def Validate(self, value, key='???'):
"""Validate this field. Override to customize subclass behavior.
Args:
value: Value to validate.
key: Name of the field being validated.
Returns:
Value if value is valid, or a valid representation of value.
"""
return value
def CheckFieldInitialized(self, value, key, obj):
"""Check for missing fields or conflicts between fields.
Default behavior performs a simple `None`-check, but this can be overridden.
If the intent is to allow optional fields, then use the `Optional` validator
instead.
Args:
value: Value to validate.
key: Name of the field being validated.
obj: The object to validate against.
Raises:
ValidationError: When there are missing or conflicting fields.
"""
if value is None:
raise MissingAttribute(key)
def ToValue(self, value):
"""Convert `value` to a simplified collection or basic type.
Subclasses of `Validator` should override this method when the dumped
representation of `value` is not a simple `<type>(value)` (e.g., a regex).
Args:
value: An object of the same type that was returned from `Validate()`.
Returns:
An instance of a builtin type (e.g., int, str, dict, etc). By default
it returns `value` unmodified.
"""
return value
def GetWarnings(self, value, key, obj):
"""Return any warnings on this attribute.
Validates the value with an eye towards things that aren't fatal problems.
Args:
value: Value to validate.
key: Name of the field being validated.
obj: The object to validate against.
Returns:
A list of tuples (context, warning) where
- Context is the field (or dotted field path, if a sub-field)
- Warning is the string warning text
"""
del value, key, obj
return []
class StringValidator(Validator):
"""Verifies property is a valid text string.
- In python 2: inherits from basestring.
- In python 3: inherits from str.
"""
def Validate(self, value, key='???'):
if not isinstance(value, six.string_types):
raise ValidationError(
'Value %r for %s is not a valid text string.' % (
value, key))
return value
class Type(Validator):
"""Verifies property is of expected type.
Can optionally convert value if it is not of the expected type.
It is possible to specify a required field of a specific type in shorthand
by merely providing the type. This method is slightly less efficient than
providing an explicit type but is not significant unless parsing a large
amount of information:
```
class Person(Validated):
ATTRIBUTES = {'name': unicode,
'age': int,
}
```
However, in most instances it is best to use the type constants:
```
class Person(Validated):
ATTRIBUTES = {'name': TypeUnicode,
'age': TypeInt,
}
```
"""
def __init__(self, expected_type, convert=True, default=None):
"""Initialize Type validator.
Args:
expected_type: Type that attribute should validate against.
convert: Cause conversion if value is not the right type.
Conversion is done by calling the constructor of the type
with the value as its first parameter.
default: Default assignment is made during initialization and will
not pass through validation.
"""
super(Type, self).__init__(default)
self.expected_type = expected_type
self.convert = convert
def Validate(self, value, key):
"""Validate that `value` has the correct type.
Args:
value: Value to validate.
key: Name of the field being validated.
Returns:
`value` if value is of the correct type. `value` is coverted to the
correct type if the `Validator` is configured to do so.
Raises:
ValidationError: If `value` is not of the right type and the validator
is either configured not to convert or cannot convert.
"""
if isinstance(value, self.expected_type):
return value
if self.expected_type is str and isinstance(value, six.string_types):
return value
if not self.convert:
raise ValidationError('Value %r for %s is not of the expected type %s' %
(value, key, self.expected_type.__name__))
try:
return self.expected_type(value)
except ValueError as e:
raise ValidationError(
'Value %r for %s could not be converted to type %s.' %
(value, key, self.expected_type.__name__), e)
except TypeError as e:
raise ValidationError(
'Value %r for %s is not of the expected type %s' %
(value, key, self.expected_type.__name__), e)
def GetWarnings(self, value, key, obj):
del obj
if issubclass(self.expected_type, ValidatedBase):
return [('%s.%s' % (key, subkey), warning)
for subkey, warning in value.GetWarnings()]
return []
TYPE_BOOL = Type(bool)
TYPE_INT = Type(int)
TYPE_LONG = Type(int)
TYPE_STR = Type(str)
TYPE_UNICODE = Type(six.text_type)
TYPE_FLOAT = Type(float)
class Exec(Type):
"""Coerces the value to accommodate Docker `CMD/ENTRYPOINT` requirements.
Validates the value is a string, then tries to modify the string (if
necessary) so that the command represented will become `PID` 1 inside the
Docker container. See Docker documentation on `docker kill` for more
information: https://docs.docker.com/engine/reference/commandline/kill/.
If the command already starts with `exec` or appears to be in "exec form"
(starts with `[`), no further action is needed. Otherwise, prepend the
command with `exec` so that it will become `PID 1` on execution.
"""
def __init__(self, default=None):
"""Initialize parent, a converting type validator for `str`."""
super(Exec, self).__init__(str, convert=True, default=default)
def Validate(self, value, key):
"""Validate according to parent behavior and coerce to start with `exec`."""
value = super(Exec, self).Validate(value, key)
if value.startswith('[') or value.startswith('exec'):
return value
else:
return 'exec ' + value
class Options(Validator):
"""Limit field based on pre-determined values.
Options are used to make sure an enumerated set of values are the only
one permitted for assignment. It is possible to define aliases which
map multiple string values to a single original. An example of usage:
```
class ZooAnimal(validated.Class):
ATTRIBUTES = {
'name': str,
'kind': Options('platypus', # No aliases
('rhinoceros', ['rhino']), # One alias
('canine', ('dog', 'puppy')), # Two aliases
)
```
"""
def __init__(self, *options, **kw):
"""Initialize options.
Args:
options: List of allowed values.
"""
if 'default' in kw:
default = kw['default']
else:
default = None
alias_map = {}
def AddAlias(alias, original):
"""Set new alias on `alias_map`.
Raises:
AttributeDefinitionError: When option already exists or if alias is
not of type str.
"""
if not isinstance(alias, str):
raise AttributeDefinitionError(
'All option values must be of type str.')
elif alias in alias_map:
raise AttributeDefinitionError(
"Option '%s' already defined for options property." % alias)
alias_map[alias] = original
for option in options:
if isinstance(option, str):
AddAlias(option, option)
elif isinstance(option, (list, tuple)):
if len(option) != 2:
raise AttributeDefinitionError("Alias is defined as a list or tuple "
"with two items. The first is the "
"original option, while the second "
"is a list or tuple of str aliases.\n"
"\n Example:\n"
" ('original', ('alias1', "
"'alias2'")
original, aliases = option
AddAlias(original, original)
if not isinstance(aliases, (list, tuple)):
raise AttributeDefinitionError('Alias lists must be a list or tuple')
for alias in aliases:
AddAlias(alias, original)
else:
raise AttributeDefinitionError("All options must be of type str "
"or of the form (str, [str...]).")
super(Options, self).__init__(default)
self.options = alias_map
def Validate(self, value, key):
"""Validate options.
Returns:
Original value for provided alias.
Raises:
ValidationError: When the value is not one of predefined values.
"""
value = str(value)
if value not in self.options:
raise ValidationError('Value \'%s\' for %s not in %s.'
% (value, key, self.options))
return self.options[value]
class Optional(Validator):
"""Definition of optional attributes.
Optional values are attributes which can be set to `None` or left
unset. All values in a basic `Validated` class are set to `None`
at initialization. Failure to assign to non-optional values
will result in a validation error when calling `CheckInitialized`.
"""
def __init__(self, validator, default=None):
"""Initializer.
This constructor will make a few guesses about the value passed in
as the validator:
- If the validator argument is a type, it automatically creates a Type
validator around it.
- If the validator argument is a list or tuple, it automatically
creates an Options validator around it.
Args: