forked from pydantic/pydantic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_validators.py
1407 lines (1041 loc) · 38.9 KB
/
test_validators.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
from collections import deque
from datetime import datetime
from enum import Enum
from itertools import product
from typing import Dict, List, Optional, Tuple, Union
import pytest
from typing_extensions import Literal
from pydantic import BaseModel, ConfigDict, Extra, Field, PydanticUserError, ValidationError, errors, validator
from pydantic.decorators import root_validator
@pytest.mark.xfail(reason='working on V2')
def test_simple():
class Model(BaseModel):
a: str
@validator('a')
def check_a(cls, v):
if 'foobar' not in v:
raise ValueError('"foobar" not found in a')
return v
assert Model(a='this is foobar good').a == 'this is foobar good'
with pytest.raises(ValidationError) as exc_info:
Model(a='snap')
assert exc_info.value.errors() == [{'loc': ('a',), 'msg': '"foobar" not found in a', 'type': 'value_error'}]
@pytest.mark.xfail(reason='working on V2')
def test_int_validation():
class Model(BaseModel):
a: int
with pytest.raises(ValidationError) as exc_info:
Model(a='snap')
assert exc_info.value.errors() == [
{'loc': ('a',), 'msg': 'value is not a valid integer', 'type': 'type_error.integer'}
]
assert Model(a=3).a == 3
assert Model(a=True).a == 1
assert Model(a=False).a == 0
assert Model(a=4.5).a == 4
@pytest.mark.xfail(reason='working on V2')
@pytest.mark.parametrize('value', [2.2250738585072011e308, float('nan'), float('inf')])
def test_int_overflow_validation(value):
class Model(BaseModel):
a: int
with pytest.raises(ValidationError) as exc_info:
Model(a=value)
assert exc_info.value.errors() == [
{'loc': ('a',), 'msg': 'value is not a valid integer', 'type': 'type_error.integer'}
]
@pytest.mark.xfail(reason='working on V2')
def test_frozenset_validation():
class Model(BaseModel):
a: frozenset
with pytest.raises(ValidationError) as exc_info:
Model(a='snap')
assert exc_info.value.errors() == [
{'loc': ('a',), 'msg': 'value is not a valid frozenset', 'type': 'type_error.frozenset'}
]
assert Model(a={1, 2, 3}).a == frozenset({1, 2, 3})
assert Model(a=frozenset({1, 2, 3})).a == frozenset({1, 2, 3})
assert Model(a=[4, 5]).a == frozenset({4, 5})
assert Model(a=(6,)).a == frozenset({6})
@pytest.mark.xfail(reason='working on V2')
def test_deque_validation():
class Model(BaseModel):
a: deque
with pytest.raises(ValidationError) as exc_info:
Model(a='snap')
assert exc_info.value.errors() == [{'loc': ('a',), 'msg': 'value is not a valid deque', 'type': 'type_error.deque'}]
assert Model(a={1, 2, 3}).a == deque([1, 2, 3])
assert Model(a=deque({1, 2, 3})).a == deque([1, 2, 3])
assert Model(a=[4, 5]).a == deque([4, 5])
assert Model(a=(6,)).a == deque([6])
@pytest.mark.xfail(reason='working on V2')
def test_validate_whole():
class Model(BaseModel):
a: List[int]
@validator('a', pre=True)
def check_a1(cls, v):
v.append('123')
return v
@validator('a')
def check_a2(cls, v):
v.append(456)
return v
assert Model(a=[1, 2]).a == [1, 2, 123, 456]
@pytest.mark.xfail(reason='working on V2')
def test_validate_kwargs():
class Model(BaseModel):
b: int
a: List[int]
@validator('a', each_item=True)
def check_a1(cls, v, values, **kwargs):
return v + values['b']
assert Model(a=[1, 2], b=6).a == [7, 8]
@pytest.mark.xfail(reason='working on V2')
def test_validate_pre_error():
calls = []
class Model(BaseModel):
a: List[int]
@validator('a', pre=True)
def check_a1(cls, v):
calls.append(f'check_a1 {v}')
if 1 in v:
raise ValueError('a1 broken')
v[0] += 1
return v
@validator('a')
def check_a2(cls, v):
calls.append(f'check_a2 {v}')
if 10 in v:
raise ValueError('a2 broken')
return v
assert Model(a=[3, 8]).a == [4, 8]
assert calls == ['check_a1 [3, 8]', 'check_a2 [4, 8]']
calls = []
with pytest.raises(ValidationError) as exc_info:
Model(a=[1, 3])
assert exc_info.value.errors() == [{'loc': ('a',), 'msg': 'a1 broken', 'type': 'value_error'}]
assert calls == ['check_a1 [1, 3]']
calls = []
with pytest.raises(ValidationError) as exc_info:
Model(a=[5, 10])
assert exc_info.value.errors() == [{'loc': ('a',), 'msg': 'a2 broken', 'type': 'value_error'}]
assert calls == ['check_a1 [5, 10]', 'check_a2 [6, 10]']
@pytest.fixture(scope='session', name='ValidateAssignmentModel')
def validate_assignment_model_fixture():
class ValidateAssignmentModel(BaseModel):
a: int = 4
b: str = ...
c: int = 0
@validator('b')
def b_length(cls, v, values, **kwargs):
if 'a' in values and len(v) < values['a']:
raise ValueError('b too short')
return v
@validator('c')
def double_c(cls, v):
return v * 2
model_config = ConfigDict(validate_assignment=True, extra=Extra.allow)
return ValidateAssignmentModel
@pytest.mark.xfail(reason='working on V2')
def test_validating_assignment_ok(ValidateAssignmentModel):
p = ValidateAssignmentModel(b='hello')
assert p.b == 'hello'
@pytest.mark.xfail(reason='working on V2')
def test_validating_assignment_fail(ValidateAssignmentModel):
with pytest.raises(ValidationError):
ValidateAssignmentModel(a=10, b='hello')
p = ValidateAssignmentModel(b='hello')
with pytest.raises(ValidationError):
p.b = 'x'
@pytest.mark.xfail(reason='working on V2')
def test_validating_assignment_value_change(ValidateAssignmentModel):
p = ValidateAssignmentModel(b='hello', c=2)
assert p.c == 4
p = ValidateAssignmentModel(b='hello')
assert p.c == 0
p.c = 3
assert p.c == 6
@pytest.mark.xfail(reason='working on V2')
def test_validating_assignment_extra(ValidateAssignmentModel):
p = ValidateAssignmentModel(b='hello', extra_field=1.23)
assert p.extra_field == 1.23
p = ValidateAssignmentModel(b='hello')
p.extra_field = 1.23
assert p.extra_field == 1.23
p.extra_field = 'bye'
assert p.extra_field == 'bye'
@pytest.mark.xfail(reason='working on V2')
def test_validating_assignment_dict(ValidateAssignmentModel):
with pytest.raises(ValidationError) as exc_info:
ValidateAssignmentModel(a='x', b='xx')
assert exc_info.value.errors() == [
{'loc': ('a',), 'msg': 'value is not a valid integer', 'type': 'type_error.integer'}
]
@pytest.mark.xfail(reason='working on V2')
def test_validating_assignment_values_dict():
class ModelOne(BaseModel):
a: int
class ModelTwo(BaseModel):
m: ModelOne
b: int
@validator('b')
def validate_b(cls, b, values):
if 'm' in values:
return b + values['m'].a # this fails if values['m'] is a dict
else:
return b
model_config = ConfigDict(validate_assignment=True)
model = ModelTwo(m=ModelOne(a=1), b=2)
assert model.b == 3
model.b = 3
assert model.b == 4
@pytest.mark.xfail(reason='working on V2')
def test_validate_multiple():
# also test TypeError
class Model(BaseModel):
a: str
b: str
@validator('a', 'b')
def check_a_and_b(cls, v, field, **kwargs):
if len(v) < 4:
raise TypeError(f'{field.alias} is too short')
return v + 'x'
assert Model(a='1234', b='5678').model_dump() == {'a': '1234x', 'b': '5678x'}
with pytest.raises(ValidationError) as exc_info:
Model(a='x', b='x')
assert exc_info.value.errors() == [
{'loc': ('a',), 'msg': 'a is too short', 'type': 'type_error'},
{'loc': ('b',), 'msg': 'b is too short', 'type': 'type_error'},
]
@pytest.mark.xfail(reason='working on V2')
def test_classmethod():
class Model(BaseModel):
a: str
@validator('a')
def check_a(cls, v):
assert cls is Model
return v
m = Model(a='this is foobar good')
assert m.a == 'this is foobar good'
m.check_a('x')
@pytest.mark.xfail(reason='working on V2')
def test_duplicates():
with pytest.raises(errors.PydanticUserError) as exc_info:
class Model(BaseModel):
a: str
b: str
@validator('a')
def duplicate_name(cls, v):
return v
@validator('b')
def duplicate_name(cls, v): # noqa
return v
assert str(exc_info.value) == (
'duplicate validator function '
'"tests.test_validators.test_duplicates.<locals>.Model.duplicate_name"; '
'if this is intended, set `allow_reuse=True`'
)
def test_use_bare():
with pytest.raises(errors.PydanticUserError) as exc_info:
class Model(BaseModel):
a: str
@validator
def checker(cls, v):
return v
assert 'validators should be used with fields' in str(exc_info.value)
def test_use_no_fields():
with pytest.raises(errors.PydanticUserError) as exc_info:
class Model(BaseModel):
a: str
@validator()
def checker(cls, v):
return v
assert 'validator with no fields specified' in str(exc_info.value)
@pytest.mark.xfail(reason='working on V2')
def test_validate_always():
check_calls = 0
class Model(BaseModel):
a: str = None
@validator('a', pre=True, always=True)
def check_a(cls, v):
nonlocal check_calls
check_calls += 1
return v or 'xxx'
assert Model().a == 'xxx'
assert check_calls == 1
assert Model(a='y').a == 'y'
assert check_calls == 2
@pytest.mark.xfail(reason='working on V2')
def test_validate_always_on_inheritance():
check_calls = 0
class ParentModel(BaseModel):
a: str = None
class Model(ParentModel):
@validator('a', pre=True, always=True)
def check_a(cls, v):
nonlocal check_calls
check_calls += 1
return v or 'xxx'
assert Model().a == 'xxx'
assert check_calls == 1
assert Model(a='y').a == 'y'
assert check_calls == 2
@pytest.mark.xfail(reason='working on V2')
def test_validate_not_always():
check_calls = 0
class Model(BaseModel):
a: str = None
@validator('a', pre=True)
def check_a(cls, v):
nonlocal check_calls
check_calls += 1
return v or 'xxx'
assert Model().a is None
assert check_calls == 0
assert Model(a='y').a == 'y'
assert check_calls == 1
@pytest.mark.xfail(reason='working on V2')
def test_wildcard_validators():
calls = []
class Model(BaseModel):
a: str
b: int
@validator('a')
def check_a(cls, v, field, **kwargs):
calls.append(('check_a', v, field.name))
return v
@validator('*')
def check_all(cls, v, field, **kwargs):
calls.append(('check_all', v, field.name))
return v
assert Model(a='abc', b='123').model_dump() == dict(a='abc', b=123)
assert calls == [('check_a', 'abc', 'a'), ('check_all', 'abc', 'a'), ('check_all', 123, 'b')]
@pytest.mark.xfail(reason='working on V2')
def test_wildcard_validator_error():
class Model(BaseModel):
a: str
b: str
@validator('*')
def check_all(cls, v, field, **kwargs):
if 'foobar' not in v:
raise ValueError('"foobar" not found in a')
return v
assert Model(a='foobar a', b='foobar b').b == 'foobar b'
with pytest.raises(ValidationError) as exc_info:
Model(a='snap')
assert exc_info.value.errors() == [
{'loc': ('a',), 'msg': '"foobar" not found in a', 'type': 'value_error'},
{'loc': ('b',), 'msg': 'field required', 'type': 'value_error.missing'},
]
@pytest.mark.xfail(reason='working on V2')
def test_invalid_field():
with pytest.raises(errors.PydanticUserError) as exc_info:
class Model(BaseModel):
a: str
@validator('b')
def check_b(cls, v):
return v
assert str(exc_info.value) == (
"Validators defined with incorrect fields: check_b "
"(use check_fields=False if you're inheriting from the model and intended this)"
)
@pytest.mark.xfail(reason='working on V2')
def test_validate_child():
class Parent(BaseModel):
a: str
class Child(Parent):
@validator('a')
def check_a(cls, v):
if 'foobar' not in v:
raise ValueError('"foobar" not found in a')
return v
assert Parent(a='this is not a child').a == 'this is not a child'
assert Child(a='this is foobar good').a == 'this is foobar good'
with pytest.raises(ValidationError):
Child(a='snap')
@pytest.mark.xfail(reason='working on V2')
def test_validate_child_extra():
class Parent(BaseModel):
a: str
@validator('a')
def check_a_one(cls, v):
if 'foobar' not in v:
raise ValueError('"foobar" not found in a')
return v
class Child(Parent):
@validator('a')
def check_a_two(cls, v):
return v.upper()
assert Parent(a='this is foobar good').a == 'this is foobar good'
assert Child(a='this is foobar good').a == 'THIS IS FOOBAR GOOD'
with pytest.raises(ValidationError):
Child(a='snap')
@pytest.mark.xfail(reason='working on V2')
def test_validate_child_all():
class Parent(BaseModel):
a: str
class Child(Parent):
@validator('*')
def check_a(cls, v):
if 'foobar' not in v:
raise ValueError('"foobar" not found in a')
return v
assert Parent(a='this is not a child').a == 'this is not a child'
assert Child(a='this is foobar good').a == 'this is foobar good'
with pytest.raises(ValidationError):
Child(a='snap')
@pytest.mark.xfail(reason='working on V2')
def test_validate_parent():
class Parent(BaseModel):
a: str
@validator('a')
def check_a(cls, v):
if 'foobar' not in v:
raise ValueError('"foobar" not found in a')
return v
class Child(Parent):
pass
assert Parent(a='this is foobar good').a == 'this is foobar good'
assert Child(a='this is foobar good').a == 'this is foobar good'
with pytest.raises(ValidationError):
Parent(a='snap')
with pytest.raises(ValidationError):
Child(a='snap')
@pytest.mark.xfail(reason='working on V2')
def test_validate_parent_all():
class Parent(BaseModel):
a: str
@validator('*')
def check_a(cls, v):
if 'foobar' not in v:
raise ValueError('"foobar" not found in a')
return v
class Child(Parent):
pass
assert Parent(a='this is foobar good').a == 'this is foobar good'
assert Child(a='this is foobar good').a == 'this is foobar good'
with pytest.raises(ValidationError):
Parent(a='snap')
with pytest.raises(ValidationError):
Child(a='snap')
@pytest.mark.xfail(reason='working on V2')
def test_inheritance_keep():
class Parent(BaseModel):
a: int
@validator('a')
def add_to_a(cls, v):
return v + 1
class Child(Parent):
pass
assert Child(a=0).a == 1
@pytest.mark.xfail(reason='working on V2')
def test_inheritance_replace():
class Parent(BaseModel):
a: int
@validator('a')
def add_to_a(cls, v):
return v + 1
class Child(Parent):
@validator('a')
def add_to_a(cls, v):
return v + 5
assert Child(a=0).a == 5
@pytest.mark.xfail(reason='working on V2')
def test_inheritance_new():
class Parent(BaseModel):
a: int
@validator('a')
def add_one_to_a(cls, v):
return v + 1
class Child(Parent):
@validator('a')
def add_five_to_a(cls, v):
return v + 5
assert Child(a=0).a == 6
@pytest.mark.xfail(reason='working on V2')
def test_validation_each_item():
class Model(BaseModel):
foobar: Dict[int, int]
@validator('foobar', each_item=True)
def check_foobar(cls, v):
return v + 1
assert Model(foobar={1: 1}).foobar == {1: 2}
@pytest.mark.xfail(reason='working on V2')
def test_validation_each_item_one_sublevel():
class Model(BaseModel):
foobar: List[Tuple[int, int]]
@validator('foobar', each_item=True)
def check_foobar(cls, v: Tuple[int, int]) -> Tuple[int, int]:
v1, v2 = v
assert v1 == v2
return v
assert Model(foobar=[(1, 1), (2, 2)]).foobar == [(1, 1), (2, 2)]
@pytest.mark.xfail(reason='working on V2')
def test_key_validation():
class Model(BaseModel):
foobar: Dict[int, int]
@validator('foobar')
def check_foobar(cls, value):
return {k + 1: v + 1 for k, v in value.items()}
assert Model(foobar={1: 1}).foobar == {2: 2}
@pytest.mark.xfail(reason='working on V2')
def test_validator_always_optional():
check_calls = 0
class Model(BaseModel):
a: Optional[str] = None
@validator('a', pre=True, always=True)
def check_a(cls, v):
nonlocal check_calls
check_calls += 1
return v or 'default value'
assert Model(a='y').a == 'y'
assert check_calls == 1
assert Model().a == 'default value'
assert check_calls == 2
@pytest.mark.xfail(reason='working on V2')
def test_validator_always_pre():
check_calls = 0
class Model(BaseModel):
a: str = None
@validator('a', always=True, pre=True)
def check_a(cls, v):
nonlocal check_calls
check_calls += 1
return v or 'default value'
assert Model(a='y').a == 'y'
assert Model().a == 'default value'
assert check_calls == 2
@pytest.mark.xfail(reason='working on V2')
def test_validator_always_post():
class Model(BaseModel):
a: str = None
@validator('a', always=True)
def check_a(cls, v):
return v or 'default value'
assert Model(a='y').a == 'y'
assert Model().a == 'default value'
@pytest.mark.xfail(reason='working on V2')
def test_validator_always_post_optional():
class Model(BaseModel):
a: Optional[str] = None
@validator('a', always=True, pre=True)
def check_a(cls, v):
return v or 'default value'
assert Model(a='y').a == 'y'
assert Model().a == 'default value'
def test_validator_bad_fields_throws_configerror():
"""
Attempts to create a validator with fields set as a list of strings,
rather than just multiple string args. Expects PydanticUserError to be raised.
"""
with pytest.raises(PydanticUserError, match='validator fields should be passed as separate string args.'):
class Model(BaseModel):
a: str
b: str
@validator(['a', 'b'])
def check_fields(cls, v):
return v
@pytest.mark.xfail(reason='working on V2')
def test_datetime_validator():
check_calls = 0
class Model(BaseModel):
d: datetime = None
@validator('d', pre=True, always=True)
def check_d(cls, v):
nonlocal check_calls
check_calls += 1
return v or datetime(2032, 1, 1)
assert Model(d='2023-01-01T00:00:00').d == datetime(2023, 1, 1)
assert check_calls == 1
assert Model().d == datetime(2032, 1, 1)
assert check_calls == 2
assert Model(d=datetime(2023, 1, 1)).d == datetime(2023, 1, 1)
assert check_calls == 3
@pytest.mark.xfail(reason='working on V2')
def test_pre_called_once():
check_calls = 0
class Model(BaseModel):
a: Tuple[int, int, int]
@validator('a', pre=True)
def check_a(cls, v):
nonlocal check_calls
check_calls += 1
return v
assert Model(a=['1', '2', '3']).a == (1, 2, 3)
assert check_calls == 1
@pytest.mark.xfail(reason='working on V2')
def test_assert_raises_validation_error():
class Model(BaseModel):
a: str
@validator('a')
def check_a(cls, v):
assert v == 'a', 'invalid a'
return v
Model(a='a')
with pytest.raises(ValidationError) as exc_info:
Model(a='snap')
injected_by_pytest = "\nassert 'snap' == 'a'\n - a\n + snap"
assert exc_info.value.errors() == [
{'loc': ('a',), 'msg': f'invalid a{injected_by_pytest}', 'type': 'assertion_error'}
]
@pytest.mark.xfail(reason='working on V2')
def test_whole():
with pytest.warns(DeprecationWarning, match='The "whole" keyword argument is deprecated'):
class Model(BaseModel):
x: List[int]
@validator('x', whole=True)
def check_something(cls, v):
return v
@pytest.mark.xfail(reason='working on V2')
def test_root_validator():
root_val_values = []
class Model(BaseModel):
a: int = 1
b: str
c: str
@validator('b')
def repeat_b(cls, v):
return v * 2
@root_validator
def example_root_validator(cls, values):
root_val_values.append(values)
if 'snap' in values.get('b', ''):
raise ValueError('foobar')
return dict(values, b='changed')
@root_validator
def example_root_validator2(cls, values):
root_val_values.append(values)
if 'snap' in values.get('c', ''):
raise ValueError('foobar2')
return dict(values, c='changed')
assert Model(a='123', b='bar', c='baz').model_dump() == {'a': 123, 'b': 'changed', 'c': 'changed'}
with pytest.raises(ValidationError) as exc_info:
Model(b='snap dragon', c='snap dragon2')
assert exc_info.value.errors() == [
{'loc': ('__root__',), 'msg': 'foobar', 'type': 'value_error'},
{'loc': ('__root__',), 'msg': 'foobar2', 'type': 'value_error'},
]
with pytest.raises(ValidationError) as exc_info:
Model(a='broken', b='bar', c='baz')
assert exc_info.value.errors() == [
{'loc': ('a',), 'msg': 'value is not a valid integer', 'type': 'type_error.integer'}
]
assert root_val_values == [
{'a': 123, 'b': 'barbar', 'c': 'baz'},
{'a': 123, 'b': 'changed', 'c': 'baz'},
{'a': 1, 'b': 'snap dragonsnap dragon', 'c': 'snap dragon2'},
{'a': 1, 'b': 'snap dragonsnap dragon', 'c': 'snap dragon2'},
{'b': 'barbar', 'c': 'baz'},
{'b': 'changed', 'c': 'baz'},
]
@pytest.mark.xfail(reason='working on V2')
def test_root_validator_pre():
root_val_values = []
class Model(BaseModel):
a: int = 1
b: str
@validator('b')
def repeat_b(cls, v):
return v * 2
@root_validator(pre=True)
def root_validator(cls, values):
root_val_values.append(values)
if 'snap' in values.get('b', ''):
raise ValueError('foobar')
return {'a': 42, 'b': 'changed'}
assert Model(a='123', b='bar').model_dump() == {'a': 42, 'b': 'changedchanged'}
with pytest.raises(ValidationError) as exc_info:
Model(b='snap dragon')
assert root_val_values == [{'a': '123', 'b': 'bar'}, {'b': 'snap dragon'}]
assert exc_info.value.errors() == [{'loc': ('__root__',), 'msg': 'foobar', 'type': 'value_error'}]
@pytest.mark.xfail(reason='working on V2')
def test_root_validator_repeat():
with pytest.raises(errors.PydanticUserError, match='duplicate validator function'):
class Model(BaseModel):
a: int = 1
@root_validator
def root_validator_repeated(cls, values):
return values
@root_validator
def root_validator_repeated(cls, values): # noqa: F811
return values
@pytest.mark.xfail(reason='working on V2')
def test_root_validator_repeat2():
with pytest.raises(errors.PydanticUserError, match='duplicate validator function'):
class Model(BaseModel):
a: int = 1
@validator('a')
def repeat_validator(cls, v):
return v
@root_validator(pre=True)
def repeat_validator(cls, values): # noqa: F811
return values
@pytest.mark.xfail(reason='working on V2')
def test_root_validator_self():
with pytest.raises(
errors.PydanticUserError, match=r'Invalid signature for root validator root_validator: \(self, values\)'
):
class Model(BaseModel):
a: int = 1
@root_validator
def root_validator(self, values):
return values
@pytest.mark.xfail(reason='working on V2')
def test_root_validator_extra():
with pytest.raises(errors.PydanticUserError) as exc_info:
class Model(BaseModel):
a: int = 1
@root_validator
def root_validator(cls, values, another):
return values
assert str(exc_info.value) == (
'Invalid signature for root validator root_validator: (cls, values, another), should be: (cls, values).'
)
@pytest.mark.xfail(reason='working on V2')
def test_root_validator_types():
root_val_values = None
class Model(BaseModel):
a: int = 1
b: str
@root_validator
def root_validator(cls, values):
nonlocal root_val_values
root_val_values = cls, values
return values
model_config = ConfigDict(extra=Extra.allow)
assert Model(b='bar', c='wobble').model_dump() == {'a': 1, 'b': 'bar', 'c': 'wobble'}
assert root_val_values == (Model, {'a': 1, 'b': 'bar', 'c': 'wobble'})
@pytest.mark.xfail(reason='working on V2')
def test_root_validator_inheritance():
calls = []
class Parent(BaseModel):
pass
@root_validator
def root_validator_parent(cls, values):
calls.append(f'parent validator: {values}')
return {'extra1': 1, **values}
class Child(Parent):
a: int
@root_validator
def root_validator_child(cls, values):
calls.append(f'child validator: {values}')
return {'extra2': 2, **values}
assert len(Child.__post_root_validators__) == 2
assert len(Child.__pre_root_validators__) == 0
assert Child(a=123).model_dump() == {'extra2': 2, 'extra1': 1, 'a': 123}
assert calls == ["parent validator: {'a': 123}", "child validator: {'extra1': 1, 'a': 123}"]
@pytest.mark.xfail(reason='working on V2')
def test_root_validator_returns_none_exception():
class Model(BaseModel):
a: int = 1
@root_validator
def root_validator_repeated(cls, values):
return None
with pytest.raises(TypeError, match='Model values must be a dict'):
Model()
@pytest.mark.xfail(reason='working on V2')