This repository was archived by the owner on Dec 25, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathschemas.hbs
More file actions
2472 lines (2202 loc) · 84 KB
/
schemas.hbs
File metadata and controls
2472 lines (2202 loc) · 84 KB
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
# coding: utf-8
{{> _helper_header }}
import collections
import datetime
import functools
import decimal
import io
import re
import types
import typing
import uuid
from dateutil import parser
from dateutil.parser.isoparser import _takes_ascii
import frozendict
from {{packageName}} import exceptions
from {{packageName}}.configurations import schema_configuration
class Unset(object):
"""
An instance of this class is set as the default value for object type(dict) properties that are optional
When a property has an unset value, that property will not be assigned in the dict
"""
pass
unset = Unset()
none_type_ = type(None)
class FileIO(io.FileIO):
"""
A class for storing files
Note: this class is not immutable
"""
def __new__(cls, arg_: typing.Union[io.FileIO, io.BufferedReader]):
if isinstance(arg_, (io.FileIO, io.BufferedReader)):
if arg_.closed:
raise exceptions.ApiValueError('Invalid file state; file is closed and must be open')
arg_.close()
inst = super(FileIO, cls).__new__(cls, arg_.name)
super(FileIO, inst).__init__(arg_.name)
return inst
raise exceptions.ApiValueError('FileIO must be passed arg_ which contains the open file')
def __init__(self, arg_: typing.Union[io.FileIO, io.BufferedReader]):
pass
def update(d: dict, u: dict):
"""
Adds u to d
Where each dict is collections.defaultdict(set)
"""
if not u:
return d
for k, v in u.items():
if k not in d:
d[k] = v
else:
d[k] = d[k] | v
class ValidationMetadata(frozendict.frozendict):
"""
A class storing metadata that is needed to validate OpenApi Schema payloads
"""
def __new__(
cls,
path_to_item: typing.Tuple[typing.Union[str, int], ...],
configuration: schema_configuration.SchemaConfiguration,
seen_classes: typing.FrozenSet[typing.Type] = frozenset(),
validated_path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Type]] = frozendict.frozendict()
):
"""
Args:
path_to_item: the path to the current data being instantiated.
For {'a': [1]} if the code is handling, 1, then the path is ('args[0]', 'a', 0)
This changes from location to location
configuration: the schema_configuration.SchemaConfiguration instance to use
This is needed because in schema_configuration.SchemaConfiguration:
- one can disable validation checking
This does not change from location to location
seen_classes: when deserializing data that matches multiple schemas, this is used to store
the schemas that have been traversed. This is used to stop processing when a cycle is seen.
This changes from location to location
validated_path_to_schemas: stores the already validated schema classes for a given path location
This does not change from location to location
"""
return super().__new__(
cls,
path_to_item=path_to_item,
configuration=configuration,
seen_classes=seen_classes,
validated_path_to_schemas=validated_path_to_schemas
)
def validation_ran_earlier(self, cls: type) -> bool:
validated_schemas = self.validated_path_to_schemas.get(self.path_to_item, set())
validation_ran_earlier = validated_schemas and cls in validated_schemas
if validation_ran_earlier:
return True
if cls in self.seen_classes:
return True
return False
@property
def path_to_item(self) -> typing.Tuple[typing.Union[str, int], ...]:
return self['path_to_item']
@property
def configuration(self) -> schema_configuration.SchemaConfiguration:
return self['configuration']
@property
def seen_classes(self) -> typing.FrozenSet[typing.Type]:
return self['seen_classes']
@property
def validated_path_to_schemas(self) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Type]]:
return self['validated_path_to_schemas']
def add_deeper_validated_schemas(validation_metadata: ValidationMetadata, path_to_schemas: dict):
# this is called if validation_ran_earlier and current and deeper locations need to be added
current_path_to_item = validation_metadata.path_to_item
other_path_to_schemas = {}
for path_to_item, schemas in validation_metadata.validated_path_to_schemas.items():
if len(path_to_item) < len(current_path_to_item):
continue
path_begins_with_current_path = path_to_item[:len(current_path_to_item)] == current_path_to_item
if path_begins_with_current_path:
other_path_to_schemas[path_to_item] = schemas
update(path_to_schemas, other_path_to_schemas)
class Singleton:
"""
Enums and singletons are the same
The same instance is returned for a given key of (cls, arg_)
"""
_instances = {}
def __new__(cls, arg_: typing.Any, **kwargs):
"""
cls base classes: BoolClass, NoneClass, str, decimal.Decimal
The 3rd key is used in the tuple below for a corner case where an enum contains integer 1
However 1.0 can also be ingested into that enum schema because 1.0 == 1 and
Decimal('1.0') == Decimal('1')
But if we omitted the 3rd value in the key, then Decimal('1.0') would be stored as Decimal('1')
and json serializing that instance would be '1' rather than the expected '1.0'
Adding the 3rd value, the str of arg_ ensures that 1.0 -> Decimal('1.0') which is serialized as 1.0
"""
key = (cls, arg_, str(arg_))
if key not in cls._instances:
if isinstance(arg_, (none_type_, bool, BoolClass, NoneClass)):
inst = super().__new__(cls)
cls._instances[key] = inst
else:
cls._instances[key] = super().__new__(cls, arg_)
return cls._instances[key]
def __repr__(self):
if isinstance(self, NoneClass):
return f'<{self.__class__.__name__}: None>'
elif isinstance(self, BoolClass):
if bool(self):
return f'<{self.__class__.__name__}: True>'
return f'<{self.__class__.__name__}: False>'
return f'<{self.__class__.__name__}: {super().__repr__()}>'
class classproperty:
def __init__(self, fget):
self.fget = fget
def __get__(self, owner_self, owner_cls):
return self.fget(owner_cls)
class NoneClass(Singleton):
@classproperty
def NONE(cls):
return cls(None)
def __bool__(self) -> bool:
return False
class BoolClass(Singleton):
@classproperty
def TRUE(cls):
return cls(True)
@classproperty
def FALSE(cls):
return cls(False)
@functools.lru_cache()
def __bool__(self) -> bool:
for key, instance in self._instances.items():
if self is instance:
return bool(key[1])
raise ValueError('Unable to find the boolean value of this instance')
class SchemaTyped:
types: typing.Optional[typing.Set[typing.Type]]
exclusive_maximum: typing.Union[int, float]
inclusive_maximum: typing.Union[int, float]
exclusive_minimum: typing.Union[int, float]
inclusive_minimum: typing.Union[int, float]
max_items: int
min_items: int
discriminator: typing.Dict[str, typing.Dict[str, typing.Type['Schema']]]
class Properties:
# to hold object properties
pass
additionalProperties: typing.Optional[typing.Type['Schema']]
max_properties: int
min_properties: int
AllOf: typing.List[typing.Type['Schema']]
OneOf: typing.List[typing.Type['Schema']]
AnyOf: typing.List[typing.Type['Schema']]
_not: typing.Type['Schema']
max_length: int
min_length: int
items: typing.Type['Schema']
PathToSchemasType = typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict.frozendict, tuple]]]
def __get_valid_classes_phrase(input_classes):
"""Returns a string phrase describing what types are allowed"""
all_classes = list(input_classes)
all_classes = sorted(all_classes, key=lambda cls: cls.__name__)
all_class_names = [cls.__name__ for cls in all_classes]
if len(all_class_names) == 1:
return "is {0}".format(all_class_names[0])
return "is one of [{0}]".format(", ".join(all_class_names))
def __type_error_message(
var_value=None, var_name=None, valid_classes=None, key_type=None
):
"""
Keyword Args:
var_value (any): the variable which has the type_error
var_name (str): the name of the variable which has the typ error
valid_classes (tuple): the accepted classes for current_item's
value
key_type (bool): False if our value is a value in a dict
True if it is a key in a dict
False if our item is an item in a tuple
"""
key_or_value = "value"
if key_type:
key_or_value = "key"
valid_classes_phrase = __get_valid_classes_phrase(valid_classes)
msg = "Invalid type. Required {1} type {2} and " "passed type was {3}".format(
var_name,
key_or_value,
valid_classes_phrase,
type(var_value).__name__,
)
return msg
def __get_type_error(var_value, path_to_item, valid_classes, key_type=False):
error_msg = __type_error_message(
var_name=path_to_item[-1],
var_value=var_value,
valid_classes=valid_classes,
key_type=key_type,
)
return exceptions.ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=valid_classes,
key_type=key_type,
)
def validate_types(
arg: typing.Any,
allowed_types: typing.Set[typing.Type],
cls: typing.Type,
validation_metadata: ValidationMetadata,
{{#if nonCompliantUseDiscriminatorIfCompositionFails}}
**kwargs
{{/if}}
) -> None:
if type(arg) not in allowed_types:
raise __get_type_error(
arg,
validation_metadata.path_to_item,
allowed_types,
key_type=False,
)
return None
def validate_enum(
arg: typing.Any,
enum_value_to_name: typing.Dict[typing.Any, str],
cls: typing.Type,
validation_metadata: ValidationMetadata,
{{#if nonCompliantUseDiscriminatorIfCompositionFails}}
**kwargs
{{/if}}
) -> None:
if arg not in enum_value_to_name:
raise exceptions.ApiValueError("Invalid value {} passed in to {}, allowed_values={}".format(arg, cls, enum_value_to_name.keys()))
return None
def _raise_validation_error_message(value, constraint_msg, constraint_value, path_to_item, additional_txt=""):
raise exceptions.ApiValueError(
"Invalid value `{value}`, {constraint_msg} `{constraint_value}`{additional_txt} at {path_to_item}".format(
value=value,
constraint_msg=constraint_msg,
constraint_value=constraint_value,
additional_txt=additional_txt,
path_to_item=path_to_item,
)
)
def validate_unique_items(
arg: typing.Any,
unique_items_value: bool,
cls: typing.Type,
validation_metadata: ValidationMetadata,
{{#if nonCompliantUseDiscriminatorIfCompositionFails}}
**kwargs
{{/if}}
) -> None:
if not unique_items_value or not isinstance(arg, tuple):
return None
if len(arg) > len(set(arg)):
_raise_validation_error_message(
value=arg,
constraint_msg="duplicate items were found, and the tuple must not contain duplicates because",
constraint_value='unique_items==True',
path_to_item=validation_metadata.path_to_item
)
return None
def validate_min_items(
arg: typing.Any,
min_items: int,
cls: typing.Type,
validation_metadata: ValidationMetadata,
{{#if nonCompliantUseDiscriminatorIfCompositionFails}}
**kwargs
{{/if}}
) -> None:
if not isinstance(arg, tuple):
return None
if len(arg) < min_items:
_raise_validation_error_message(
value=arg,
constraint_msg="number of items must be greater than or equal to",
constraint_value=min_items,
path_to_item=validation_metadata.path_to_item
)
return None
def validate_max_items(
arg: typing.Any,
max_items: int,
cls: typing.Type,
validation_metadata: ValidationMetadata,
{{#if nonCompliantUseDiscriminatorIfCompositionFails}}
**kwargs
{{/if}}
) -> None:
if not isinstance(arg, tuple):
return None
if len(arg) > max_items:
_raise_validation_error_message(
value=arg,
constraint_msg="number of items must be less than or equal to",
constraint_value=max_items,
path_to_item=validation_metadata.path_to_item
)
return None
def validate_min_properties(
arg: typing.Any,
min_properties: int,
cls: typing.Type,
validation_metadata: ValidationMetadata,
{{#if nonCompliantUseDiscriminatorIfCompositionFails}}
**kwargs
{{/if}}
) -> None:
if not isinstance(arg, frozendict.frozendict):
return None
if len(arg) < min_properties:
_raise_validation_error_message(
value=arg,
constraint_msg="number of properties must be greater than or equal to",
constraint_value=min_properties,
path_to_item=validation_metadata.path_to_item
)
return None
def validate_max_properties(
arg: typing.Any,
max_properties: int,
cls: typing.Type,
validation_metadata: ValidationMetadata,
{{#if nonCompliantUseDiscriminatorIfCompositionFails}}
**kwargs
{{/if}}
) -> None:
if not isinstance(arg, frozendict.frozendict):
return None
if len(arg) > max_properties:
_raise_validation_error_message(
value=arg,
constraint_msg="number of properties must be less than or equal to",
constraint_value=max_properties,
path_to_item=validation_metadata.path_to_item
)
return None
def validate_min_length(
arg: typing.Any,
min_length: int,
cls: typing.Type,
validation_metadata: ValidationMetadata,
{{#if nonCompliantUseDiscriminatorIfCompositionFails}}
**kwargs
{{/if}}
) -> None:
if not isinstance(arg, str):
return None
if len(arg) < min_length:
_raise_validation_error_message(
value=arg,
constraint_msg="length must be greater than or equal to",
constraint_value=min_length,
path_to_item=validation_metadata.path_to_item
)
return None
def validate_max_length(
arg: typing.Any,
max_length: int,
cls: typing.Type,
validation_metadata: ValidationMetadata,
{{#if nonCompliantUseDiscriminatorIfCompositionFails}}
**kwargs
{{/if}}
) -> None:
if not isinstance(arg, str):
return None
if len(arg) > max_length:
_raise_validation_error_message(
value=arg,
constraint_msg="length must be less than or equal to",
constraint_value=max_length,
path_to_item=validation_metadata.path_to_item
)
return None
def validate_inclusive_minimum(
arg: typing.Any,
inclusive_minimum: typing.Union[int, float],
cls: typing.Type,
validation_metadata: ValidationMetadata,
{{#if nonCompliantUseDiscriminatorIfCompositionFails}}
**kwargs
{{/if}}
) -> None:
if not isinstance(arg, decimal.Decimal):
return None
if arg < inclusive_minimum:
_raise_validation_error_message(
value=arg,
constraint_msg="must be a value greater than or equal to",
constraint_value=inclusive_minimum,
path_to_item=validation_metadata.path_to_item
)
return None
def validate_exclusive_minimum(
arg: typing.Any,
exclusive_minimum: typing.Union[int, float],
cls: typing.Type,
validation_metadata: ValidationMetadata,
{{#if nonCompliantUseDiscriminatorIfCompositionFails}}
**kwargs
{{/if}}
) -> None:
if not isinstance(arg, decimal.Decimal):
return None
if arg <= exclusive_minimum:
_raise_validation_error_message(
value=arg,
constraint_msg="must be a value greater than",
constraint_value=exclusive_minimum,
path_to_item=validation_metadata.path_to_item
)
return None
def validate_inclusive_maximum(
arg: typing.Any,
inclusive_maximum: typing.Union[int, float],
cls: typing.Type,
validation_metadata: ValidationMetadata,
{{#if nonCompliantUseDiscriminatorIfCompositionFails}}
**kwargs
{{/if}}
) -> None:
if not isinstance(arg, decimal.Decimal):
return None
if arg > inclusive_maximum:
_raise_validation_error_message(
value=arg,
constraint_msg="must be a value less than or equal to",
constraint_value=inclusive_maximum,
path_to_item=validation_metadata.path_to_item
)
return None
def validate_exclusive_maximum(
arg: typing.Any,
exclusive_maximum: typing.Union[int, float],
cls: typing.Type,
validation_metadata: ValidationMetadata,
{{#if nonCompliantUseDiscriminatorIfCompositionFails}}
**kwargs
{{/if}}
) -> None:
if not isinstance(arg, decimal.Decimal):
return None
if arg >= exclusive_maximum:
_raise_validation_error_message(
value=arg,
constraint_msg="must be a value less than",
constraint_value=exclusive_maximum,
path_to_item=validation_metadata.path_to_item
)
return None
def validate_multiple_of(
arg: typing.Any,
multiple_of: typing.Union[int, float],
cls: typing.Type,
validation_metadata: ValidationMetadata,
{{#if nonCompliantUseDiscriminatorIfCompositionFails}}
**kwargs
{{/if}}
) -> None:
if not isinstance(arg, decimal.Decimal):
return None
if (not (float(arg) / multiple_of).is_integer()):
# Note 'multipleOf' will be as good as the floating point arithmetic.
_raise_validation_error_message(
value=arg,
constraint_msg="value must be a multiple of",
constraint_value=multiple_of,
path_to_item=validation_metadata.path_to_item
)
return None
def validate_regex(
arg: typing.Any,
regex_dict: typing.Dict,
cls: typing.Type,
validation_metadata: ValidationMetadata,
{{#if nonCompliantUseDiscriminatorIfCompositionFails}}
**kwargs
{{/if}}
) -> None:
if not isinstance(arg, str):
return None
flags = regex_dict.get('flags', 0)
if not re.search(regex_dict['pattern'], arg, flags=flags):
if flags != 0:
# Don't print the regex flags if the flags are not
# specified in the OAS document.
_raise_validation_error_message(
value=arg,
constraint_msg="must match regular expression",
constraint_value=regex_dict['pattern'],
path_to_item=validation_metadata.path_to_item,
additional_txt=" with flags=`{}`".format(flags)
)
_raise_validation_error_message(
value=arg,
constraint_msg="must match regular expression",
constraint_value=regex_dict['pattern'],
path_to_item=validation_metadata.path_to_item
)
return None
__int32_inclusive_minimum = decimal.Decimal(-2147483648)
__int32_inclusive_maximum = decimal.Decimal(2147483647)
__int64_inclusive_minimum = decimal.Decimal(-9223372036854775808)
__int64_inclusive_maximum = decimal.Decimal(9223372036854775807)
__float_inclusive_minimum = decimal.Decimal(-3.4028234663852886e+38)
__float_inclusive_maximum = decimal.Decimal(3.4028234663852886e+38)
__double_inclusive_minimum = decimal.Decimal(-1.7976931348623157E+308)
__double_inclusive_maximum = decimal.Decimal(1.7976931348623157E+308)
def __validate_numeric_format(
arg: decimal.Decimal,
format: str,
validation_metadata: ValidationMetadata
) -> None:
if format[:3] == 'int':
# there is a json schema test where 1.0 validates as an integer
if arg != int(arg):
raise exceptions.ApiValueError(
"Invalid non-integer value '{}' for type {} at {}".format(
arg, format, validation_metadata.path_to_item
)
)
if format == 'int32':
if not __int32_inclusive_minimum <= arg <= __int32_inclusive_maximum:
raise exceptions.ApiValueError(
"Invalid value '{}' for type int32 at {}".format(arg, validation_metadata.path_to_item)
)
return None
elif format == 'int64':
if not __int64_inclusive_minimum <= arg <= __int64_inclusive_maximum:
raise exceptions.ApiValueError(
"Invalid value '{}' for type int64 at {}".format(arg, validation_metadata.path_to_item)
)
return None
return None
elif format in {'float', 'double'}:
if format == 'float':
if not __float_inclusive_minimum <= arg <= __float_inclusive_maximum:
raise exceptions.ApiValueError(
"Invalid value '{}' for type float at {}".format(arg, validation_metadata.path_to_item)
)
return None
# double
if not __double_inclusive_minimum <= arg <= __double_inclusive_maximum:
raise exceptions.ApiValueError(
"Invalid value '{}' for type double at {}".format(arg, validation_metadata.path_to_item)
)
return None
return None
class CustomIsoparser(parser.isoparser):
@_takes_ascii
def parse_isodatetime(self, dt_str):
components, pos = self._parse_isodate(dt_str)
if len(dt_str) > pos:
if self._sep is None or dt_str[pos:pos + 1] == self._sep:
components += self._parse_isotime(dt_str[pos + 1:])
else:
raise ValueError('String contains unknown ISO components')
if len(components) > 3 and components[3] == 24:
components[3] = 0
return datetime.datetime(*components) + datetime.timedelta(days=1)
if len(components) <= 3:
raise ValueError('Value is not a datetime')
return datetime.datetime(*components)
@_takes_ascii
def parse_isodate(self, datestr):
components, pos = self._parse_isodate(datestr)
if len(datestr) > pos:
raise ValueError('String contains invalid time components')
if len(components) > 3:
raise ValueError('String contains invalid time components')
return datetime.date(*components)
DEFAULT_ISOPARSER = CustomIsoparser()
def __validate_string_format(
arg: str,
format: str,
validation_metadata: ValidationMetadata
) -> None:
if format == 'uuid':
try:
uuid.UUID(arg)
return None
except ValueError:
raise exceptions.ApiValueError(
"Invalid value '{}' for type UUID at {}".format(arg, validation_metadata.path_to_item)
)
elif format == 'number':
try:
decimal.Decimal(arg)
return None
except decimal.InvalidOperation:
raise exceptions.ApiValueError(
"Value cannot be converted to a decimal. "
"Invalid value '{}' for type decimal at {}".format(arg, validation_metadata.path_to_item)
)
elif format == 'date':
try:
DEFAULT_ISOPARSER.parse_isodate(arg)
return None
except ValueError:
raise exceptions.ApiValueError(
"Value does not conform to the required ISO-8601 date format. "
"Invalid value '{}' for type date at {}".format(arg, validation_metadata.path_to_item)
)
elif format == 'date-time':
try:
DEFAULT_ISOPARSER.parse_isodatetime(arg)
return None
except ValueError:
raise exceptions.ApiValueError(
"Value does not conform to the required ISO-8601 datetime format. "
"Invalid value '{}' for type datetime at {}".format(arg, validation_metadata.path_to_item)
)
return None
def validate_format(
arg: typing.Any,
format: str,
cls: typing.Type,
validation_metadata: ValidationMetadata,
{{#if nonCompliantUseDiscriminatorIfCompositionFails}}
**kwargs
{{/if}}
) -> None:
# formats work for strings + numbers
if isinstance(arg, decimal.Decimal):
return __validate_numeric_format(
arg,
format,
validation_metadata
)
elif isinstance(arg, str):
return __validate_string_format(
arg,
format,
validation_metadata
)
return None
def validate_required(
arg: typing.Any,
required: typing.Set[str],
cls: typing.Type,
validation_metadata: ValidationMetadata,
{{#if nonCompliantUseDiscriminatorIfCompositionFails}}
**kwargs
{{/if}}
) -> None:
if not isinstance(arg, frozendict.frozendict):
return None
missing_required_arguments = required - arg.keys()
if missing_required_arguments:
missing_required_arguments = list(missing_required_arguments)
missing_required_arguments.sort()
raise exceptions.ApiTypeError(
"{} is missing {} required argument{}: {}".format(
cls.__name__,
len(missing_required_arguments),
"s" if len(missing_required_arguments) > 1 else "",
missing_required_arguments
)
)
return None
def _get_class(item_cls: typing.Union[types.FunctionType, staticmethod, typing.Type['Schema']]) -> typing.Type['Schema']:
if isinstance(item_cls, types.FunctionType):
# referenced schema
return item_cls()
elif isinstance(item_cls, staticmethod):
# referenced schema
return item_cls.__func__()
return item_cls
def validate_items(
arg: typing.Any,
item_cls: typing.Type,
cls: typing.Type,
validation_metadata: ValidationMetadata,
{{#if nonCompliantUseDiscriminatorIfCompositionFails}}
**kwargs
{{/if}}
) -> PathToSchemasType:
if not isinstance(arg, tuple):
return None
item_cls = _get_class(item_cls)
path_to_schemas = {}
for i, value in enumerate(arg):
item_validation_metadata = ValidationMetadata(
path_to_item=validation_metadata.path_to_item+(i,),
configuration=validation_metadata.configuration,
validated_path_to_schemas=validation_metadata.validated_path_to_schemas
)
if item_validation_metadata.validation_ran_earlier(item_cls):
add_deeper_validated_schemas(item_validation_metadata, path_to_schemas)
continue
other_path_to_schemas = item_cls._validate(
value, validation_metadata=item_validation_metadata)
update(path_to_schemas, other_path_to_schemas)
return path_to_schemas
def validate_properties(
arg: typing.Any,
properties: typing.Type,
cls: typing.Type,
validation_metadata: ValidationMetadata,
{{#if nonCompliantUseDiscriminatorIfCompositionFails}}
**kwargs
{{/if}}
) -> typing.Optional[PathToSchemasType]:
if not isinstance(arg, frozendict.frozendict):
return None
path_to_schemas = {}
present_properties = {k: v for k, v, in arg.items() if k in properties.__annotations__}
for property_name, value in present_properties.items():
path_to_item = validation_metadata.path_to_item + (property_name,)
schema = properties.__annotations__[property_name]
schema = _get_class(schema)
arg_validation_metadata = ValidationMetadata(
path_to_item=path_to_item,
configuration=validation_metadata.configuration,
validated_path_to_schemas=validation_metadata.validated_path_to_schemas
)
if arg_validation_metadata.validation_ran_earlier(schema):
add_deeper_validated_schemas(arg_validation_metadata, path_to_schemas)
continue
other_path_to_schemas = schema._validate(value, validation_metadata=arg_validation_metadata)
update(path_to_schemas, other_path_to_schemas)
return path_to_schemas
def validate_additional_properties(
arg: typing.Any,
additional_properties_schema: typing.Type,
cls: typing.Type,
validation_metadata: ValidationMetadata,
{{#if nonCompliantUseDiscriminatorIfCompositionFails}}
**kwargs
{{/if}}
) -> typing.Optional[PathToSchemasType]:
if not isinstance(arg, frozendict.frozendict):
return None
schema = _get_class(additional_properties_schema)
path_to_schemas = {}
properties_annotations = cls.Schema_.Properties.__annotations__ if hasattr(cls.Schema_, 'Properties') else {}
present_additional_properties = {k: v for k, v, in arg.items() if k not in properties_annotations}
for property_name, value in present_additional_properties.items():
path_to_item = validation_metadata.path_to_item + (property_name,)
arg_validation_metadata = ValidationMetadata(
path_to_item=path_to_item,
configuration=validation_metadata.configuration,
validated_path_to_schemas=validation_metadata.validated_path_to_schemas
)
if arg_validation_metadata.validation_ran_earlier(schema):
add_deeper_validated_schemas(arg_validation_metadata, path_to_schemas)
continue
other_path_to_schemas = schema._validate(value, validation_metadata=arg_validation_metadata)
update(path_to_schemas, other_path_to_schemas)
return path_to_schemas
def validate_one_of(
arg: typing.Any,
one_of_container_cls: typing.Type,
cls: 'Schema',
validation_metadata: ValidationMetadata,
{{#if nonCompliantUseDiscriminatorIfCompositionFails}}
discriminated_cls: typing.Optional['Schema'],
**kwargs
{{/if}}
) -> PathToSchemasType:
oneof_classes = []
path_to_schemas = collections.defaultdict(set)
for one_of_cls in one_of_container_cls.classes:
schema = _get_class(one_of_cls)
if schema in path_to_schemas[validation_metadata.path_to_item]:
oneof_classes.append(schema)
continue
if schema is cls:
"""
optimistically assume that cls schema will pass validation
do not invoke _validate on it because that is recursive
"""
oneof_classes.append(schema)
continue
if validation_metadata.validation_ran_earlier(schema):
oneof_classes.append(schema)
add_deeper_validated_schemas(validation_metadata, path_to_schemas)
continue
try:
path_to_schemas = schema._validate(arg, validation_metadata=validation_metadata)
except (exceptions.ApiValueError, exceptions.ApiTypeError) as ex:
# silence exceptions because the code needs to accumulate oneof_classes
continue
oneof_classes.append(schema)
if not oneof_classes:
{{#if nonCompliantUseDiscriminatorIfCompositionFails}}
if discriminated_cls:
"""
return without exception because code was generated with
nonCompliantUseDiscriminatorIfCompositionFails=true
"""
return {}
{{/if}}
raise exceptions.ApiValueError(
"Invalid inputs given to generate an instance of {}. None "
"of the oneOf schemas matched the input data.".format(cls)
)
elif len(oneof_classes) > 1:
{{#if nonCompliantUseDiscriminatorIfCompositionFails}}
if discriminated_cls:
"""
return without exception because code was generated with
nonCompliantUseDiscriminatorIfCompositionFails=true
"""
return {}
{{/if}}
raise exceptions.ApiValueError(
"Invalid inputs given to generate an instance of {}. Multiple "
"oneOf schemas {} matched the inputs, but a max of one is allowed.".format(cls, oneof_classes)
)
# exactly one class matches
return path_to_schemas
def validate_any_of(
arg: typing.Any,
any_of_container_cls: typing.Type,
cls: 'Schema',
validation_metadata: ValidationMetadata,
{{#if nonCompliantUseDiscriminatorIfCompositionFails}}
discriminated_cls: typing.Optional['Schema'],
**kwargs
{{/if}}
) -> PathToSchemasType:
anyof_classes = []
path_to_schemas = collections.defaultdict(set)
for any_of_cls in any_of_container_cls.classes:
schema = _get_class(any_of_cls)
if schema is cls:
"""
optimistically assume that cls schema will pass validation
do not invoke _validate on it because that is recursive
"""
anyof_classes.append(schema)
continue
if validation_metadata.validation_ran_earlier(schema):
anyof_classes.append(schema)
add_deeper_validated_schemas(validation_metadata, path_to_schemas)
continue
try:
other_path_to_schemas = schema._validate(arg, validation_metadata=validation_metadata)
except (exceptions.ApiValueError, exceptions.ApiTypeError) as ex:
# silence exceptions because the code needs to accumulate anyof_classes
continue
anyof_classes.append(schema)
update(path_to_schemas, other_path_to_schemas)
if not anyof_classes:
{{#if nonCompliantUseDiscriminatorIfCompositionFails}}
if discriminated_cls:
"""
return without exception because code was generated with