forked from pydantic/pydantic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_edge_cases.py
2828 lines (2243 loc) · 84.4 KB
/
test_edge_cases.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
import functools
import importlib.util
import re
import sys
from abc import ABC, abstractmethod
from collections.abc import Hashable
from decimal import Decimal
from enum import Enum, auto
from typing import (
Any,
Dict,
ForwardRef,
FrozenSet,
Generic,
List,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
)
import pytest
from dirty_equals import HasRepr, IsStr
from pydantic_core import ErrorDetails, InitErrorDetails, PydanticSerializationError, core_schema
from typing_extensions import Annotated, Literal, TypedDict, get_args
from pydantic import (
BaseModel,
ConfigDict,
GetCoreSchemaHandler,
PydanticDeprecatedSince20,
PydanticSchemaGenerationError,
RootModel,
TypeAdapter,
ValidationError,
constr,
errors,
field_validator,
model_validator,
root_validator,
validator,
)
from pydantic._internal._model_construction import ModelMetaclass
from pydantic.fields import Field, computed_field
from pydantic.functional_serializers import (
field_serializer,
model_serializer,
)
def test_str_bytes():
class Model(BaseModel):
v: Union[str, bytes]
m = Model(v='s')
assert m.v == 's'
assert repr(m.model_fields['v']) == 'FieldInfo(annotation=Union[str, bytes], required=True)'
m = Model(v=b'b')
assert m.v == b'b'
with pytest.raises(ValidationError) as exc_info:
Model(v=None)
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{'type': 'string_type', 'loc': ('v', 'str'), 'msg': 'Input should be a valid string', 'input': None},
{'type': 'bytes_type', 'loc': ('v', 'bytes'), 'msg': 'Input should be a valid bytes', 'input': None},
]
def test_str_bytes_none():
class Model(BaseModel):
v: Union[None, str, bytes] = ...
m = Model(v='s')
assert m.v == 's'
m = Model(v=b'b')
assert m.v == b'b'
m = Model(v=None)
assert m.v is None
def test_union_int_str():
class Model(BaseModel):
v: Union[int, str] = ...
m = Model(v=123)
assert m.v == 123
m = Model(v='123')
assert m.v == '123'
m = Model(v=b'foobar')
assert m.v == 'foobar'
m = Model(v=12.0)
assert m.v == 12
with pytest.raises(ValidationError) as exc_info:
Model(v=None)
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{'type': 'int_type', 'loc': ('v', 'int'), 'msg': 'Input should be a valid integer', 'input': None},
{
'type': 'string_type',
'loc': ('v', 'str'),
'msg': 'Input should be a valid string',
'input': None,
},
]
def test_union_int_any():
class Model(BaseModel):
v: Union[int, Any]
m = Model(v=123)
assert m.v == 123
m = Model(v='123')
assert m.v == '123'
m = Model(v='foobar')
assert m.v == 'foobar'
m = Model(v=None)
assert m.v is None
def test_typed_list():
class Model(BaseModel):
v: List[int] = ...
m = Model(v=[1, 2, '3'])
assert m.v == [1, 2, 3]
with pytest.raises(ValidationError) as exc_info:
Model(v=[1, 'x', 'y'])
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{
'type': 'int_parsing',
'loc': ('v', 1),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'x',
},
{
'type': 'int_parsing',
'loc': ('v', 2),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'y',
},
]
with pytest.raises(ValidationError) as exc_info:
Model(v=1)
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{'type': 'list_type', 'loc': ('v',), 'msg': 'Input should be a valid list', 'input': 1}
]
def test_typed_set():
class Model(BaseModel):
v: Set[int] = ...
assert Model(v={1, 2, '3'}).v == {1, 2, 3}
assert Model(v=[1, 2, '3']).v == {1, 2, 3}
with pytest.raises(ValidationError) as exc_info:
Model(v=[1, 'x'])
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{
'type': 'int_parsing',
'loc': ('v', 1),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'x',
}
]
def test_dict_dict():
class Model(BaseModel):
v: Dict[str, int] = ...
assert Model(v={'foo': 1}).model_dump() == {'v': {'foo': 1}}
def test_none_list():
class Model(BaseModel):
v: List[None] = [None]
assert Model.model_json_schema() == {
'title': 'Model',
'type': 'object',
'properties': {'v': {'title': 'V', 'default': [None], 'type': 'array', 'items': {'type': 'null'}}},
}
@pytest.mark.parametrize(
'value,result',
[
({'a': 2, 'b': 4}, {'a': 2, 'b': 4}),
({b'a': '2', 'b': 4}, {'a': 2, 'b': 4}),
# ([('a', 2), ('b', 4)], {'a': 2, 'b': 4}),
],
)
def test_typed_dict(value, result):
class Model(BaseModel):
v: Dict[str, int] = ...
assert Model(v=value).v == result
@pytest.mark.parametrize(
'value,errors',
[
(1, [{'type': 'dict_type', 'loc': ('v',), 'msg': 'Input should be a valid dictionary', 'input': 1}]),
(
{'a': 'b'},
[
{
'type': 'int_parsing',
'loc': ('v', 'a'),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'b',
}
],
),
(
[1, 2, 3],
[{'type': 'dict_type', 'loc': ('v',), 'msg': 'Input should be a valid dictionary', 'input': [1, 2, 3]}],
),
],
)
def test_typed_dict_error(value, errors):
class Model(BaseModel):
v: Dict[str, int] = ...
with pytest.raises(ValidationError) as exc_info:
Model(v=value)
assert exc_info.value.errors(include_url=False) == errors
def test_dict_key_error():
class Model(BaseModel):
v: Dict[int, int] = ...
assert Model(v={1: 2, '3': '4'}).v == {1: 2, 3: 4}
with pytest.raises(ValidationError) as exc_info:
Model(v={'foo': 2, '3': '4'})
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{
'type': 'int_parsing',
'loc': ('v', 'foo', '[key]'),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'foo',
}
]
def test_tuple():
class Model(BaseModel):
v: Tuple[int, float, bool]
m = Model(v=['1.0', '2.2', 'true'])
assert m.v == (1, 2.2, True)
def test_tuple_more():
class Model(BaseModel):
empty_tuple: Tuple[()]
simple_tuple: tuple = None
tuple_of_different_types: Tuple[int, float, str, bool] = None
tuple_of_single_tuples: Tuple[Tuple[int], ...] = ()
m = Model(
empty_tuple=[],
simple_tuple=[1, 2, 3, 4],
tuple_of_different_types=[4, 3.1, 'str', 1],
tuple_of_single_tuples=(('1',), (2,)),
)
assert m.model_dump() == {
'empty_tuple': (),
'simple_tuple': (1, 2, 3, 4),
'tuple_of_different_types': (4, 3.1, 'str', True),
'tuple_of_single_tuples': ((1,), (2,)),
}
@pytest.mark.parametrize(
'dict_cls,frozenset_cls,list_cls,set_cls,tuple_cls,type_cls',
[
(Dict, FrozenSet, List, Set, Tuple, Type),
(dict, frozenset, list, set, tuple, type),
],
)
def test_pep585_generic_types(dict_cls, frozenset_cls, list_cls, set_cls, tuple_cls, type_cls):
class Type1:
pass
class Type2:
pass
class Model(BaseModel, arbitrary_types_allowed=True):
a: dict_cls
a1: 'dict_cls[str, int]'
b: frozenset_cls
b1: 'frozenset_cls[int]'
c: list_cls
c1: 'list_cls[int]'
d: set_cls
d1: 'set_cls[int]'
e: tuple_cls
e1: 'tuple_cls[int]'
e2: 'tuple_cls[int, ...]'
e3: 'tuple_cls[()]'
f: type_cls
f1: 'type_cls[Type1]'
default_model_kwargs = dict(
a={},
a1={'a': '1'},
b=[],
b1=('1',),
c=[],
c1=('1',),
d=[],
d1=['1'],
e=[],
e1=['1'],
e2=['1', '2'],
e3=[],
f=Type1,
f1=Type1,
)
m = Model(**default_model_kwargs)
assert m.a == {}
assert m.a1 == {'a': 1}
assert m.b == frozenset()
assert m.b1 == frozenset({1})
assert m.c == []
assert m.c1 == [1]
assert m.d == set()
assert m.d1 == {1}
assert m.e == ()
assert m.e1 == (1,)
assert m.e2 == (1, 2)
assert m.e3 == ()
assert m.f == Type1
assert m.f1 == Type1
with pytest.raises(ValidationError) as exc_info:
Model(**{**default_model_kwargs, 'e3': (1,)})
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{
'type': 'too_long',
'loc': ('e3',),
'msg': 'Tuple should have at most 0 items after validation, not 1',
'input': (1,),
'ctx': {'field_type': 'Tuple', 'max_length': 0, 'actual_length': 1},
}
]
Model(**{**default_model_kwargs, 'f': Type2})
with pytest.raises(ValidationError) as exc_info:
Model(**{**default_model_kwargs, 'f1': Type2})
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{
'type': 'is_subclass_of',
'loc': ('f1',),
'msg': 'Input should be a subclass of test_pep585_generic_types.<locals>.Type1',
'input': HasRepr(IsStr(regex=r".+\.Type2'>")),
'ctx': {'class': 'test_pep585_generic_types.<locals>.Type1'},
}
]
def test_tuple_length_error():
class Model(BaseModel):
v: Tuple[int, float, bool]
w: Tuple[()]
with pytest.raises(ValidationError) as exc_info:
Model(v=[1, 2], w=[1])
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{'type': 'missing', 'loc': ('v', 2), 'msg': 'Field required', 'input': [1, 2]},
{
'type': 'too_long',
'loc': ('w',),
'msg': 'Tuple should have at most 0 items after validation, not 1',
'input': [1],
'ctx': {'field_type': 'Tuple', 'max_length': 0, 'actual_length': 1},
},
]
def test_tuple_invalid():
class Model(BaseModel):
v: Tuple[int, float, bool]
with pytest.raises(ValidationError) as exc_info:
Model(v='xxx')
assert exc_info.value.errors(include_url=False) == [
{'type': 'tuple_type', 'loc': ('v',), 'msg': 'Input should be a valid tuple', 'input': 'xxx'}
]
def test_tuple_value_error():
class Model(BaseModel):
v: Tuple[int, float, Decimal]
with pytest.raises(ValidationError) as exc_info:
Model(v=['x', 'y', 'x'])
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{
'type': 'int_parsing',
'loc': ('v', 0),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'x',
},
{
'type': 'float_parsing',
'loc': ('v', 1),
'msg': 'Input should be a valid number, unable to parse string as a number',
'input': 'y',
},
{
'type': 'decimal_parsing',
'loc': ('v', 2),
'msg': 'Input should be a valid decimal',
'input': 'x',
},
]
def test_recursive_list():
class SubModel(BaseModel):
name: str = ...
count: int = None
class Model(BaseModel):
v: List[SubModel] = []
m = Model(v=[])
assert m.v == []
m = Model(v=[{'name': 'testing', 'count': 4}])
assert repr(m) == "Model(v=[SubModel(name='testing', count=4)])"
assert m.v[0].name == 'testing'
assert m.v[0].count == 4
assert m.model_dump() == {'v': [{'count': 4, 'name': 'testing'}]}
with pytest.raises(ValidationError) as exc_info:
Model(v=['x'])
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{
'type': 'model_type',
'loc': ('v', 0),
'msg': 'Input should be a valid dictionary or instance of SubModel',
'input': 'x',
'ctx': {'class_name': 'SubModel'},
}
]
def test_recursive_list_error():
class SubModel(BaseModel):
name: str = ...
count: int = None
class Model(BaseModel):
v: List[SubModel] = []
with pytest.raises(ValidationError) as exc_info:
Model(v=[{}])
assert exc_info.value.errors(include_url=False) == [
{'input': {}, 'loc': ('v', 0, 'name'), 'msg': 'Field required', 'type': 'missing'}
]
def test_list_unions():
class Model(BaseModel):
v: List[Union[int, str]]
assert Model(v=[123, '456', 'foobar']).v == [123, '456', 'foobar']
with pytest.raises(ValidationError) as exc_info:
Model(v=[1, 2, None])
# the reason that we need to do an unordered list comparison here is that previous tests use Union[str, int]
# and Python's cache makes it such that the above Model has `v` associated with a List[Union[str, int]] instead
# of the expected List[Union[int, str]]
# for more info, see https://github.com/python/cpython/issues/103749 and
# https://github.com/pydantic/pydantic/pull/10244#issuecomment-2312796647
errors = exc_info.value.errors(include_url=False)
expected_errors = [
{'input': None, 'loc': ('v', 2, 'int'), 'msg': 'Input should be a valid integer', 'type': 'int_type'},
{'input': None, 'loc': ('v', 2, 'str'), 'msg': 'Input should be a valid string', 'type': 'string_type'},
]
assert sorted(errors, key=str) == sorted(expected_errors, key=str)
def test_recursive_lists():
class Model(BaseModel):
v: List[List[Union[int, float]]] = ...
assert Model(v=[[1, 2], [3, '4', '4.1']]).v == [[1, 2], [3, 4, 4.1]]
assert Model.model_fields['v'].annotation == List[List[Union[int, float]]]
assert Model.model_fields['v'].is_required()
class StrEnum(str, Enum):
a = 'a10'
b = 'b10'
def test_str_enum():
class Model(BaseModel):
v: StrEnum = ...
assert Model(v='a10').v is StrEnum.a
with pytest.raises(ValidationError):
Model(v='different')
def test_any_dict():
class Model(BaseModel):
v: Dict[int, Any] = ...
assert Model(v={1: 'foobar'}).model_dump() == {'v': {1: 'foobar'}}
assert Model(v={123: 456}).model_dump() == {'v': {123: 456}}
assert Model(v={2: [1, 2, 3]}).model_dump() == {'v': {2: [1, 2, 3]}}
def test_success_values_include():
class Model(BaseModel):
a: int = 1
b: int = 2
c: int = 3
m = Model()
assert m.model_dump() == {'a': 1, 'b': 2, 'c': 3}
assert m.model_dump(include={'a'}) == {'a': 1}
assert m.model_dump(exclude={'a'}) == {'b': 2, 'c': 3}
assert m.model_dump(include={'a', 'b'}, exclude={'a'}) == {'b': 2}
def test_include_exclude_unset():
class Model(BaseModel):
a: int
b: int
c: int = 3
d: int = 4
e: int = 5
f: int = 6
m = Model(a=1, b=2, e=5, f=7)
assert m.model_dump() == {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 7}
assert m.model_fields_set == {'a', 'b', 'e', 'f'}
assert m.model_dump(exclude_unset=True) == {'a': 1, 'b': 2, 'e': 5, 'f': 7}
assert m.model_dump(include={'a'}, exclude_unset=True) == {'a': 1}
assert m.model_dump(include={'c'}, exclude_unset=True) == {}
assert m.model_dump(exclude={'a'}, exclude_unset=True) == {'b': 2, 'e': 5, 'f': 7}
assert m.model_dump(exclude={'c'}, exclude_unset=True) == {'a': 1, 'b': 2, 'e': 5, 'f': 7}
assert m.model_dump(include={'a', 'b', 'c'}, exclude={'b'}, exclude_unset=True) == {'a': 1}
assert m.model_dump(include={'a', 'b', 'c'}, exclude={'a', 'c'}, exclude_unset=True) == {'b': 2}
def test_include_exclude_defaults():
class Model(BaseModel):
a: int
b: int
c: int = 3
d: int = 4
e: int = 5
f: int = 6
m = Model(a=1, b=2, e=5, f=7)
assert m.model_dump() == {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 7}
assert m.model_fields_set == {'a', 'b', 'e', 'f'}
assert m.model_dump(exclude_defaults=True) == {'a': 1, 'b': 2, 'f': 7}
assert m.model_dump(include={'a'}, exclude_defaults=True) == {'a': 1}
assert m.model_dump(include={'c'}, exclude_defaults=True) == {}
assert m.model_dump(exclude={'a'}, exclude_defaults=True) == {'b': 2, 'f': 7}
assert m.model_dump(exclude={'c'}, exclude_defaults=True) == {'a': 1, 'b': 2, 'f': 7}
assert m.model_dump(include={'a', 'b', 'c'}, exclude={'b'}, exclude_defaults=True) == {'a': 1}
assert m.model_dump(include={'a', 'b', 'c'}, exclude={'a', 'c'}, exclude_defaults=True) == {'b': 2}
assert m.model_dump(include={'a': 1}.keys()) == {'a': 1}
assert m.model_dump(exclude={'a': 1}.keys()) == {'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 7}
assert m.model_dump(include={'a': 1}.keys(), exclude_unset=True) == {'a': 1}
assert m.model_dump(exclude={'a': 1}.keys(), exclude_unset=True) == {'b': 2, 'e': 5, 'f': 7}
assert m.model_dump(include=['a']) == {'a': 1}
assert m.model_dump(exclude=['a']) == {'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 7}
assert m.model_dump(include=['a'], exclude_unset=True) == {'a': 1}
assert m.model_dump(exclude=['a'], exclude_unset=True) == {'b': 2, 'e': 5, 'f': 7}
def test_advanced_exclude():
class SubSubModel(BaseModel):
a: str
b: str
class SubModel(BaseModel):
c: str
d: List[SubSubModel]
class Model(BaseModel):
e: str
f: SubModel
m = Model(e='e', f=SubModel(c='foo', d=[SubSubModel(a='a', b='b'), SubSubModel(a='c', b='e')]))
assert m.model_dump(exclude={'f': {'c': ..., 'd': {-1: {'a'}}}}) == {
'e': 'e',
'f': {'d': [{'a': 'a', 'b': 'b'}, {'b': 'e'}]},
}
assert m.model_dump(exclude={'e': ..., 'f': {'d'}}) == {'f': {'c': 'foo'}}
def test_advanced_exclude_by_alias():
class SubSubModel(BaseModel):
a: str
aliased_b: str = Field(..., alias='b_alias')
class SubModel(BaseModel):
aliased_c: str = Field(..., alias='c_alias')
aliased_d: List[SubSubModel] = Field(..., alias='d_alias')
class Model(BaseModel):
aliased_e: str = Field(..., alias='e_alias')
aliased_f: SubModel = Field(..., alias='f_alias')
m = Model(
e_alias='e',
f_alias=SubModel(c_alias='foo', d_alias=[SubSubModel(a='a', b_alias='b'), SubSubModel(a='c', b_alias='e')]),
)
excludes = {'aliased_f': {'aliased_c': ..., 'aliased_d': {-1: {'a'}}}}
assert m.model_dump(exclude=excludes, by_alias=True) == {
'e_alias': 'e',
'f_alias': {'d_alias': [{'a': 'a', 'b_alias': 'b'}, {'b_alias': 'e'}]},
}
excludes = {'aliased_e': ..., 'aliased_f': {'aliased_d'}}
assert m.model_dump(exclude=excludes, by_alias=True) == {'f_alias': {'c_alias': 'foo'}}
def test_advanced_value_include():
class SubSubModel(BaseModel):
a: str
b: str
class SubModel(BaseModel):
c: str
d: List[SubSubModel]
class Model(BaseModel):
e: str
f: SubModel
m = Model(e='e', f=SubModel(c='foo', d=[SubSubModel(a='a', b='b'), SubSubModel(a='c', b='e')]))
assert m.model_dump(include={'f'}) == {'f': {'c': 'foo', 'd': [{'a': 'a', 'b': 'b'}, {'a': 'c', 'b': 'e'}]}}
assert m.model_dump(include={'e'}) == {'e': 'e'}
assert m.model_dump(include={'f': {'d': {0: ..., -1: {'b'}}}}) == {'f': {'d': [{'a': 'a', 'b': 'b'}, {'b': 'e'}]}}
def test_advanced_value_exclude_include():
class SubSubModel(BaseModel):
a: str
b: str
class SubModel(BaseModel):
c: str
d: List[SubSubModel]
class Model(BaseModel):
e: str
f: SubModel
m = Model(e='e', f=SubModel(c='foo', d=[SubSubModel(a='a', b='b'), SubSubModel(a='c', b='e')]))
assert m.model_dump(exclude={'f': {'c': ..., 'd': {-1: {'a'}}}}, include={'f'}) == {
'f': {'d': [{'a': 'a', 'b': 'b'}, {'b': 'e'}]}
}
assert m.model_dump(exclude={'e': ..., 'f': {'d'}}, include={'e', 'f'}) == {'f': {'c': 'foo'}}
assert m.model_dump(exclude={'f': {'d': {-1: {'a'}}}}, include={'f': {'d'}}) == {
'f': {'d': [{'a': 'a', 'b': 'b'}, {'b': 'e'}]}
}
@pytest.mark.parametrize(
'exclude,expected',
[
pytest.param(
{'subs': {'__all__': {'subsubs': {'__all__': {'i'}}}}},
{'subs': [{'k': 1, 'subsubs': [{'j': 1}, {'j': 2}]}, {'k': 2, 'subsubs': [{'j': 3}]}]},
id='Normal nested __all__',
),
pytest.param(
{'subs': {'__all__': {'subsubs': {'__all__': {'i'}}}, 0: {'subsubs': {'__all__': {'j'}}}}},
{'subs': [{'k': 1, 'subsubs': [{}, {}]}, {'k': 2, 'subsubs': [{'j': 3}]}]},
id='Merge sub dicts 1',
),
pytest.param(
{'subs': {'__all__': {'subsubs': ...}, 0: {'subsubs': {'__all__': {'j'}}}}},
{'subs': [{'k': 1, 'subsubs': [{'i': 1}, {'i': 2}]}, {'k': 2}]},
# {'subs': [{'k': 1 }, {'k': 2}]}
id='Merge sub sets 2',
),
pytest.param(
{'subs': {'__all__': {'subsubs': {'__all__': {'j'}}}, 0: {'subsubs': ...}}},
{'subs': [{'k': 1}, {'k': 2, 'subsubs': [{'i': 3}]}]},
id='Merge sub sets 3',
),
pytest.param(
{'subs': {'__all__': {'subsubs': {0}}, 0: {'subsubs': {1}}}},
{'subs': [{'k': 1, 'subsubs': []}, {'k': 2, 'subsubs': []}]},
id='Merge sub sets 1',
),
pytest.param(
{'subs': {'__all__': {'subsubs': {0: {'i'}}}, 0: {'subsubs': {1}}}},
{'subs': [{'k': 1, 'subsubs': [{'j': 1}]}, {'k': 2, 'subsubs': [{'j': 3}]}]},
id='Merge sub dict-set',
),
pytest.param({'subs': {'__all__': {'subsubs'}, 0: {'k'}}}, {'subs': [{}, {'k': 2}]}, id='Different keys 1'),
pytest.param(
{'subs': {'__all__': {'subsubs': ...}, 0: {'k'}}}, {'subs': [{}, {'k': 2}]}, id='Different keys 2'
),
pytest.param(
{'subs': {'__all__': {'subsubs'}, 0: {'k': ...}}}, {'subs': [{}, {'k': 2}]}, id='Different keys 3'
),
pytest.param(
{'subs': {'__all__': {'subsubs': {'__all__': {'i'}, 0: {'j'}}}}},
{'subs': [{'k': 1, 'subsubs': [{}, {'j': 2}]}, {'k': 2, 'subsubs': [{}]}]},
id='Nested different keys 1',
),
pytest.param(
{'subs': {'__all__': {'subsubs': {'__all__': {'i': ...}, 0: {'j'}}}}},
{'subs': [{'k': 1, 'subsubs': [{}, {'j': 2}]}, {'k': 2, 'subsubs': [{}]}]},
id='Nested different keys 2',
),
pytest.param(
{'subs': {'__all__': {'subsubs': {'__all__': {'i'}, 0: {'j': ...}}}}},
{'subs': [{'k': 1, 'subsubs': [{}, {'j': 2}]}, {'k': 2, 'subsubs': [{}]}]},
id='Nested different keys 3',
),
pytest.param(
{'subs': {'__all__': {'subsubs'}, 0: {'subsubs': {'__all__': {'j'}}}}},
{'subs': [{'k': 1, 'subsubs': [{'i': 1}, {'i': 2}]}, {'k': 2}]},
id='Ignore __all__ for index with defined exclude 1',
),
pytest.param(
{'subs': {'__all__': {'subsubs': {'__all__': {'j'}}}, 0: ...}},
{'subs': [{'k': 2, 'subsubs': [{'i': 3}]}]},
id='Ignore __all__ for index with defined exclude 2',
),
pytest.param(
{'subs': {'__all__': ..., 0: {'subsubs'}}},
{'subs': [{'k': 1}]},
id='Ignore __all__ for index with defined exclude 3',
),
],
)
def test_advanced_exclude_nested_lists(exclude, expected):
class SubSubModel(BaseModel):
i: int
j: int
class SubModel(BaseModel):
k: int
subsubs: List[SubSubModel]
class Model(BaseModel):
subs: List[SubModel]
m = Model(subs=[dict(k=1, subsubs=[dict(i=1, j=1), dict(i=2, j=2)]), dict(k=2, subsubs=[dict(i=3, j=3)])])
assert m.model_dump(exclude=exclude) == expected
@pytest.mark.parametrize(
'include,expected',
[
pytest.param(
{'subs': {'__all__': {'subsubs': {'__all__': {'i'}}}}},
{'subs': [{'subsubs': [{'i': 1}, {'i': 2}]}, {'subsubs': [{'i': 3}]}]},
id='Normal nested __all__',
),
pytest.param(
{'subs': {'__all__': {'subsubs': {'__all__': {'i'}}}, 0: {'subsubs': {'__all__': {'j'}}}}},
{'subs': [{'subsubs': [{'i': 1, 'j': 1}, {'i': 2, 'j': 2}]}, {'subsubs': [{'i': 3}]}]},
id='Merge sub dicts 1',
),
pytest.param(
{'subs': {'__all__': {'subsubs': ...}, 0: {'subsubs': {'__all__': {'j'}}}}},
{'subs': [{'subsubs': [{'j': 1}, {'j': 2}]}, {'subsubs': [{'i': 3, 'j': 3}]}]},
id='Merge sub dicts 2',
),
pytest.param(
{'subs': {'__all__': {'subsubs': {'__all__': {'j'}}}, 0: {'subsubs': ...}}},
{'subs': [{'subsubs': [{'i': 1, 'j': 1}, {'i': 2, 'j': 2}]}, {'subsubs': [{'j': 3}]}]},
id='Merge sub dicts 3',
),
pytest.param(
{'subs': {'__all__': {'subsubs': {0}}, 0: {'subsubs': {1}}}},
{'subs': [{'subsubs': [{'i': 1, 'j': 1}, {'i': 2, 'j': 2}]}, {'subsubs': [{'i': 3, 'j': 3}]}]},
id='Merge sub sets',
),
pytest.param(
{'subs': {'__all__': {'subsubs': {0: {'i'}}}, 0: {'subsubs': {1}}}},
{'subs': [{'subsubs': [{'i': 1}, {'i': 2, 'j': 2}]}, {'subsubs': [{'i': 3}]}]},
id='Merge sub dict-set',
),
pytest.param(
{'subs': {'__all__': {'subsubs'}, 0: {'k'}}},
{'subs': [{'k': 1, 'subsubs': [{'i': 1, 'j': 1}, {'i': 2, 'j': 2}]}, {'subsubs': [{'i': 3, 'j': 3}]}]},
id='Nested different keys 1',
),
pytest.param(
{'subs': {'__all__': {'subsubs': ...}, 0: {'k'}}},
{'subs': [{'k': 1, 'subsubs': [{'i': 1, 'j': 1}, {'i': 2, 'j': 2}]}, {'subsubs': [{'i': 3, 'j': 3}]}]},
id='Nested different keys 2',
),
pytest.param(
{'subs': {'__all__': {'subsubs'}, 0: {'k': ...}}},
{'subs': [{'k': 1, 'subsubs': [{'i': 1, 'j': 1}, {'i': 2, 'j': 2}]}, {'subsubs': [{'i': 3, 'j': 3}]}]},
id='Nested different keys 3',
),
pytest.param(
{'subs': {'__all__': {'subsubs': {'__all__': {'i'}, 0: {'j'}}}}},
{'subs': [{'subsubs': [{'i': 1, 'j': 1}, {'i': 2}]}, {'subsubs': [{'i': 3, 'j': 3}]}]},
id='Nested different keys 1',
),
pytest.param(
{'subs': {'__all__': {'subsubs': {'__all__': {'i': ...}, 0: {'j'}}}}},
{'subs': [{'subsubs': [{'i': 1, 'j': 1}, {'i': 2}]}, {'subsubs': [{'i': 3, 'j': 3}]}]},
id='Nested different keys 2',
),
pytest.param(
{'subs': {'__all__': {'subsubs': {'__all__': {'i'}, 0: {'j': ...}}}}},
{'subs': [{'subsubs': [{'i': 1, 'j': 1}, {'i': 2}]}, {'subsubs': [{'i': 3, 'j': 3}]}]},
id='Nested different keys 3',
),
pytest.param(
{'subs': {'__all__': {'subsubs'}, 0: {'subsubs': {'__all__': {'j'}}}}},
{'subs': [{'subsubs': [{'j': 1}, {'j': 2}]}, {'subsubs': [{'i': 3, 'j': 3}]}]},
id='Ignore __all__ for index with defined include 1',
),
pytest.param(
{'subs': {'__all__': {'subsubs': {'__all__': {'j'}}}, 0: ...}},
{'subs': [{'k': 1, 'subsubs': [{'i': 1, 'j': 1}, {'i': 2, 'j': 2}]}, {'subsubs': [{'j': 3}]}]},
id='Ignore __all__ for index with defined include 2',
),
pytest.param(
{'subs': {'__all__': ..., 0: {'subsubs'}}},
{'subs': [{'subsubs': [{'i': 1, 'j': 1}, {'i': 2, 'j': 2}]}, {'k': 2, 'subsubs': [{'i': 3, 'j': 3}]}]},
id='Ignore __all__ for index with defined include 3',
),
],
)
def test_advanced_include_nested_lists(include, expected):
class SubSubModel(BaseModel):
i: int
j: int
class SubModel(BaseModel):
k: int
subsubs: List[SubSubModel]
class Model(BaseModel):
subs: List[SubModel]
m = Model(subs=[dict(k=1, subsubs=[dict(i=1, j=1), dict(i=2, j=2)]), dict(k=2, subsubs=[dict(i=3, j=3)])])
assert m.model_dump(include=include) == expected
def test_field_set_ignore_extra():
class Model(BaseModel):
model_config = ConfigDict(extra='ignore')
a: int
b: int
c: int = 3
m = Model(a=1, b=2)
assert m.model_dump() == {'a': 1, 'b': 2, 'c': 3}
assert m.model_fields_set == {'a', 'b'}
assert m.model_dump(exclude_unset=True) == {'a': 1, 'b': 2}
m2 = Model(a=1, b=2, d=4)
assert m2.model_dump() == {'a': 1, 'b': 2, 'c': 3}
assert m2.model_fields_set == {'a', 'b'}
assert m2.model_dump(exclude_unset=True) == {'a': 1, 'b': 2}
def test_field_set_allow_extra():
class Model(BaseModel):
model_config = ConfigDict(extra='allow')
a: int
b: int
c: int = 3
m = Model(a=1, b=2)
assert m.model_dump() == {'a': 1, 'b': 2, 'c': 3}
assert m.model_fields_set == {'a', 'b'}
assert m.model_dump(exclude_unset=True) == {'a': 1, 'b': 2}
m2 = Model(a=1, b=2, d=4)
assert m2.model_dump() == {'a': 1, 'b': 2, 'c': 3, 'd': 4}
assert m2.model_fields_set == {'a', 'b', 'd'}
assert m2.model_dump(exclude_unset=True) == {'a': 1, 'b': 2, 'd': 4}
def test_field_set_field_name():
class Model(BaseModel):
a: int
field_set: int
b: int = 3
assert Model(a=1, field_set=2).model_dump() == {'a': 1, 'field_set': 2, 'b': 3}
assert Model(a=1, field_set=2).model_dump(exclude_unset=True) == {'a': 1, 'field_set': 2}
assert Model.model_construct(a=1, field_set=3).model_dump() == {'a': 1, 'field_set': 3, 'b': 3}
def test_values_order():
class Model(BaseModel):
a: int = 1
b: int = 2
c: int = 3
m = Model(c=30, b=20, a=10)
assert list(m) == [('a', 10), ('b', 20), ('c', 30)]
def test_inheritance():
class Foo(BaseModel):
a: float = ...
with pytest.raises(
TypeError,
match=(
"Field 'a' defined on a base class was overridden by a non-annotated attribute. "
'All field definitions, including overrides, require a type annotation.'
),
):
class Bar(Foo):
x: float = 12.3
a = 123.0
class Bar2(Foo):
x: float = 12.3
a: float = 123.0
assert Bar2().model_dump() == {'x': 12.3, 'a': 123.0}
class Bar3(Foo):
x: float = 12.3
a: float = Field(default=123.0)
assert Bar3().model_dump() == {'x': 12.3, 'a': 123.0}
def test_inheritance_subclass_default():
class MyStr(str):
pass
# Confirm hint supports a subclass default
class Simple(BaseModel):
x: str = MyStr('test')