forked from pydantic/pydantic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_discriminated_union.py
2174 lines (1805 loc) · 78.7 KB
/
test_discriminated_union.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 re
import sys
from dataclasses import dataclass
from enum import Enum, IntEnum
from types import SimpleNamespace
from typing import Any, Callable, Generic, List, Optional, Sequence, TypeVar, Union
import pytest
from dirty_equals import HasRepr, IsStr
from pydantic_core import SchemaValidator, core_schema
from typing_extensions import Annotated, Literal, TypedDict
from pydantic import (
BaseModel,
ConfigDict,
Discriminator,
Field,
PlainSerializer,
TypeAdapter,
ValidationError,
field_validator,
)
from pydantic._internal._discriminated_union import apply_discriminator
from pydantic.dataclasses import dataclass as pydantic_dataclass
from pydantic.errors import PydanticUserError
from pydantic.fields import FieldInfo
from pydantic.functional_validators import model_validator
from pydantic.json_schema import GenerateJsonSchema
from pydantic.types import Tag
def test_discriminated_union_type():
with pytest.raises(
TypeError, match="'str' is not a valid discriminated union variant; should be a `BaseModel` or `dataclass`"
):
class Model(BaseModel):
x: str = Field(..., discriminator='qwe')
@pytest.mark.parametrize('union', [True, False])
def test_discriminated_single_variant(union):
class InnerModel(BaseModel):
qwe: Literal['qwe']
y: int
class Model(BaseModel):
if union:
x: Union[InnerModel] = Field(..., discriminator='qwe')
else:
x: InnerModel = Field(..., discriminator='qwe')
assert Model(x={'qwe': 'qwe', 'y': 1}).x.qwe == 'qwe'
with pytest.raises(ValidationError) as exc_info:
Model(x={'qwe': 'asd', 'y': 'a'}) # note: incorrect type of "y" is not reported due to discriminator failure
assert exc_info.value.errors(include_url=False) == [
{
'ctx': {'discriminator': "'qwe'", 'expected_tags': "'qwe'", 'tag': 'asd'},
'input': {'qwe': 'asd', 'y': 'a'},
'loc': ('x',),
'msg': "Input tag 'asd' found using 'qwe' does not match any of the expected " "tags: 'qwe'",
'type': 'union_tag_invalid',
}
]
def test_discriminated_union_single_variant():
class InnerModel(BaseModel):
qwe: Literal['qwe']
class Model(BaseModel):
x: Union[InnerModel] = Field(..., discriminator='qwe')
assert Model(x={'qwe': 'qwe'}).x.qwe == 'qwe'
def test_discriminated_union_invalid_type():
with pytest.raises(
TypeError, match="'str' is not a valid discriminated union variant; should be a `BaseModel` or `dataclass`"
):
class Model(BaseModel):
x: Union[str, int] = Field(..., discriminator='qwe')
def test_discriminated_union_defined_discriminator():
class Cat(BaseModel):
c: str
class Dog(BaseModel):
pet_type: Literal['dog']
d: str
with pytest.raises(PydanticUserError, match="Model 'Cat' needs a discriminator field for key 'pet_type'"):
class Model(BaseModel):
pet: Union[Cat, Dog] = Field(..., discriminator='pet_type')
number: int
def test_discriminated_union_literal_discriminator():
class Cat(BaseModel):
pet_type: int
c: str
class Dog(BaseModel):
pet_type: Literal['dog']
d: str
with pytest.raises(PydanticUserError, match="Model 'Cat' needs field 'pet_type' to be of type `Literal`"):
class Model(BaseModel):
pet: Union[Cat, Dog] = Field(..., discriminator='pet_type')
number: int
def test_discriminated_union_root_same_discriminator():
class BlackCat(BaseModel):
pet_type: Literal['blackcat']
class WhiteCat(BaseModel):
pet_type: Literal['whitecat']
Cat = Union[BlackCat, WhiteCat]
class Dog(BaseModel):
pet_type: Literal['dog']
CatDog = TypeAdapter(Annotated[Union[Cat, Dog], Field(..., discriminator='pet_type')]).validate_python
CatDog({'pet_type': 'blackcat'})
CatDog({'pet_type': 'whitecat'})
CatDog({'pet_type': 'dog'})
with pytest.raises(ValidationError) as exc_info:
CatDog({'pet_type': 'llama'})
assert exc_info.value.errors(include_url=False) == [
{
'ctx': {'discriminator': "'pet_type'", 'expected_tags': "'blackcat', 'whitecat', 'dog'", 'tag': 'llama'},
'input': {'pet_type': 'llama'},
'loc': (),
'msg': "Input tag 'llama' found using 'pet_type' does not match any of the "
"expected tags: 'blackcat', 'whitecat', 'dog'",
'type': 'union_tag_invalid',
}
]
@pytest.mark.parametrize('color_discriminator_kind', ['discriminator', 'field_str', 'field_discriminator'])
@pytest.mark.parametrize('pet_discriminator_kind', ['discriminator', 'field_str', 'field_discriminator'])
def test_discriminated_union_validation(color_discriminator_kind, pet_discriminator_kind):
def _get_str_discriminator(discriminator: str, kind: str):
if kind == 'discriminator':
return Discriminator(discriminator)
elif kind == 'field_str':
return Field(discriminator=discriminator)
elif kind == 'field_discriminator':
return Field(discriminator=Discriminator(discriminator))
raise ValueError(f'Invalid kind: {kind}')
class BlackCat(BaseModel):
pet_type: Literal['cat']
color: Literal['black']
black_infos: str
class WhiteCat(BaseModel):
pet_type: Literal['cat']
color: Literal['white']
white_infos: str
color_discriminator = _get_str_discriminator('color', color_discriminator_kind)
Cat = Annotated[Union[BlackCat, WhiteCat], color_discriminator]
class Dog(BaseModel):
pet_type: Literal['dog']
d: str
class Lizard(BaseModel):
pet_type: Literal['reptile', 'lizard']
m: str
pet_discriminator = _get_str_discriminator('pet_type', pet_discriminator_kind)
class Model(BaseModel):
pet: Annotated[Union[Cat, Dog, Lizard], pet_discriminator]
number: int
with pytest.raises(ValidationError) as exc_info:
Model.model_validate({'pet': {'pet_typ': 'cat'}, 'number': 'x'})
assert exc_info.value.errors(include_url=False) == [
{
'ctx': {'discriminator': "'pet_type'"},
'input': {'pet_typ': 'cat'},
'loc': ('pet',),
'msg': "Unable to extract tag using discriminator 'pet_type'",
'type': 'union_tag_not_found',
},
{
'input': 'x',
'loc': ('number',),
'msg': 'Input should be a valid integer, unable to parse string as an ' 'integer',
'type': 'int_parsing',
},
]
with pytest.raises(ValidationError) as exc_info:
Model.model_validate({'pet': 'fish', 'number': 2})
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{
'type': 'model_attributes_type',
'loc': ('pet',),
'msg': 'Input should be a valid dictionary or object to extract fields from',
'input': 'fish',
}
]
with pytest.raises(ValidationError) as exc_info:
Model.model_validate({'pet': {'pet_type': 'fish'}, 'number': 2})
assert exc_info.value.errors(include_url=False) == [
{
'ctx': {'discriminator': "'pet_type'", 'expected_tags': "'cat', 'dog', 'reptile', 'lizard'", 'tag': 'fish'},
'input': {'pet_type': 'fish'},
'loc': ('pet',),
'msg': "Input tag 'fish' found using 'pet_type' does not match any of the "
"expected tags: 'cat', 'dog', 'reptile', 'lizard'",
'type': 'union_tag_invalid',
}
]
with pytest.raises(ValidationError) as exc_info:
Model.model_validate({'pet': {'pet_type': 'lizard'}, 'number': 2})
assert exc_info.value.errors(include_url=False) == [
{'input': {'pet_type': 'lizard'}, 'loc': ('pet', 'lizard', 'm'), 'msg': 'Field required', 'type': 'missing'}
]
m = Model.model_validate({'pet': {'pet_type': 'lizard', 'm': 'pika'}, 'number': 2})
assert isinstance(m.pet, Lizard)
assert m.model_dump() == {'pet': {'pet_type': 'lizard', 'm': 'pika'}, 'number': 2}
with pytest.raises(ValidationError) as exc_info:
Model.model_validate({'pet': {'pet_type': 'cat', 'color': 'white'}, 'number': 2})
assert exc_info.value.errors(include_url=False) == [
{
'input': {'color': 'white', 'pet_type': 'cat'},
'loc': ('pet', 'cat', 'white', 'white_infos'),
'msg': 'Field required',
'type': 'missing',
}
]
m = Model.model_validate({'pet': {'pet_type': 'cat', 'color': 'white', 'white_infos': 'pika'}, 'number': 2})
assert isinstance(m.pet, WhiteCat)
def test_discriminated_annotated_union():
class BlackCat(BaseModel):
pet_type: Literal['cat']
color: Literal['black']
black_infos: str
class WhiteCat(BaseModel):
pet_type: Literal['cat']
color: Literal['white']
white_infos: str
Cat = Annotated[Union[BlackCat, WhiteCat], Field(discriminator='color')]
class Dog(BaseModel):
pet_type: Literal['dog']
dog_name: str
Pet = Annotated[Union[Cat, Dog], Field(discriminator='pet_type')]
class Model(BaseModel):
pet: Pet
number: int
with pytest.raises(ValidationError) as exc_info:
Model.model_validate({'pet': {'pet_typ': 'cat'}, 'number': 'x'})
assert exc_info.value.errors(include_url=False) == [
{
'ctx': {'discriminator': "'pet_type'"},
'input': {'pet_typ': 'cat'},
'loc': ('pet',),
'msg': "Unable to extract tag using discriminator 'pet_type'",
'type': 'union_tag_not_found',
},
{
'input': 'x',
'loc': ('number',),
'msg': 'Input should be a valid integer, unable to parse string as an ' 'integer',
'type': 'int_parsing',
},
]
with pytest.raises(ValidationError) as exc_info:
Model.model_validate({'pet': {'pet_type': 'fish'}, 'number': 2})
assert exc_info.value.errors(include_url=False) == [
{
'ctx': {'discriminator': "'pet_type'", 'expected_tags': "'cat', 'dog'", 'tag': 'fish'},
'input': {'pet_type': 'fish'},
'loc': ('pet',),
'msg': "Input tag 'fish' found using 'pet_type' does not match any of the " "expected tags: 'cat', 'dog'",
'type': 'union_tag_invalid',
}
]
with pytest.raises(ValidationError) as exc_info:
Model.model_validate({'pet': {'pet_type': 'dog'}, 'number': 2})
assert exc_info.value.errors(include_url=False) == [
{'input': {'pet_type': 'dog'}, 'loc': ('pet', 'dog', 'dog_name'), 'msg': 'Field required', 'type': 'missing'}
]
m = Model.model_validate({'pet': {'pet_type': 'dog', 'dog_name': 'milou'}, 'number': 2})
assert isinstance(m.pet, Dog)
with pytest.raises(ValidationError) as exc_info:
Model.model_validate({'pet': {'pet_type': 'cat', 'color': 'red'}, 'number': 2})
assert exc_info.value.errors(include_url=False) == [
{
'ctx': {'discriminator': "'color'", 'expected_tags': "'black', 'white'", 'tag': 'red'},
'input': {'color': 'red', 'pet_type': 'cat'},
'loc': ('pet', 'cat'),
'msg': "Input tag 'red' found using 'color' does not match any of the " "expected tags: 'black', 'white'",
'type': 'union_tag_invalid',
}
]
with pytest.raises(ValidationError) as exc_info:
Model.model_validate({'pet': {'pet_type': 'cat', 'color': 'white'}, 'number': 2})
assert exc_info.value.errors(include_url=False) == [
{
'input': {'color': 'white', 'pet_type': 'cat'},
'loc': ('pet', 'cat', 'white', 'white_infos'),
'msg': 'Field required',
'type': 'missing',
}
]
m = Model.model_validate({'pet': {'pet_type': 'cat', 'color': 'white', 'white_infos': 'pika'}, 'number': 2})
assert isinstance(m.pet, WhiteCat)
def test_discriminated_union_basemodel_instance_value():
class A(BaseModel):
foo: Literal['a']
class B(BaseModel):
foo: Literal['b']
class Top(BaseModel):
sub: Union[A, B] = Field(..., discriminator='foo')
t = Top(sub=A(foo='a'))
assert isinstance(t, Top)
def test_discriminated_union_basemodel_instance_value_with_alias():
class A(BaseModel):
literal: Literal['a'] = Field(alias='lit')
class B(BaseModel):
model_config = ConfigDict(populate_by_name=True)
literal: Literal['b'] = Field(alias='lit')
class Top(BaseModel):
sub: Union[A, B] = Field(..., discriminator='literal')
with pytest.raises(ValidationError) as exc_info:
Top(sub=A(literal='a'))
assert exc_info.value.errors(include_url=False) == [
{'input': {'literal': 'a'}, 'loc': ('lit',), 'msg': 'Field required', 'type': 'missing'}
]
assert Top(sub=A(lit='a')).sub.literal == 'a'
assert Top(sub=B(lit='b')).sub.literal == 'b'
assert Top(sub=B(literal='b')).sub.literal == 'b'
def test_discriminated_union_int():
class A(BaseModel):
m: Literal[1]
class B(BaseModel):
m: Literal[2]
class Top(BaseModel):
sub: Union[A, B] = Field(..., discriminator='m')
assert isinstance(Top.model_validate({'sub': {'m': 2}}).sub, B)
with pytest.raises(ValidationError) as exc_info:
Top.model_validate({'sub': {'m': 3}})
assert exc_info.value.errors(include_url=False) == [
{
'ctx': {'discriminator': "'m'", 'expected_tags': '1, 2', 'tag': '3'},
'input': {'m': 3},
'loc': ('sub',),
'msg': "Input tag '3' found using 'm' does not match any of the expected " 'tags: 1, 2',
'type': 'union_tag_invalid',
}
]
class FooIntEnum(int, Enum):
pass
class FooStrEnum(str, Enum):
pass
ENUM_TEST_CASES = [
pytest.param(Enum, {'a': 1, 'b': 2}),
pytest.param(Enum, {'a': 'v_a', 'b': 'v_b'}),
(FooIntEnum, {'a': 1, 'b': 2}),
(IntEnum, {'a': 1, 'b': 2}),
(FooStrEnum, {'a': 'v_a', 'b': 'v_b'}),
]
if sys.version_info >= (3, 11):
from enum import StrEnum
ENUM_TEST_CASES.append((StrEnum, {'a': 'v_a', 'b': 'v_b'}))
@pytest.mark.skipif(sys.version_info[:2] == (3, 8), reason='https://github.com/python/cpython/issues/103592')
@pytest.mark.parametrize('base_class,choices', ENUM_TEST_CASES)
def test_discriminated_union_enum(base_class, choices):
EnumValue = base_class('EnumValue', choices)
class A(BaseModel):
m: Literal[EnumValue.a]
class B(BaseModel):
m: Literal[EnumValue.b]
class Top(BaseModel):
sub: Union[A, B] = Field(..., discriminator='m')
assert isinstance(Top.model_validate({'sub': {'m': EnumValue.b}}).sub, B)
if isinstance(EnumValue.b, (int, str)):
assert isinstance(Top.model_validate({'sub': {'m': EnumValue.b.value}}).sub, B)
with pytest.raises(ValidationError) as exc_info:
Top.model_validate({'sub': {'m': 3}})
expected_tags = f'{EnumValue.a!r}, {EnumValue.b!r}'
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{
'type': 'union_tag_invalid',
'loc': ('sub',),
'msg': f"Input tag '3' found using 'm' does not match any of the expected tags: {expected_tags}",
'input': {'m': 3},
'ctx': {'discriminator': "'m'", 'tag': '3', 'expected_tags': expected_tags},
}
]
def test_alias_different():
class Cat(BaseModel):
pet_type: Literal['cat'] = Field(alias='U')
c: str
class Dog(BaseModel):
pet_type: Literal['dog'] = Field(alias='T')
d: str
with pytest.raises(TypeError, match=re.escape("Aliases for discriminator 'pet_type' must be the same (got T, U)")):
class Model(BaseModel):
pet: Union[Cat, Dog] = Field(discriminator='pet_type')
def test_alias_same():
class Cat(BaseModel):
pet_type: Literal['cat'] = Field(alias='typeOfPet')
c: str
class Dog(BaseModel):
pet_type: Literal['dog'] = Field(alias='typeOfPet')
d: str
class Model(BaseModel):
pet: Union[Cat, Dog] = Field(discriminator='pet_type')
assert Model(**{'pet': {'typeOfPet': 'dog', 'd': 'milou'}}).pet.pet_type == 'dog'
def test_nested():
class Cat(BaseModel):
pet_type: Literal['cat']
name: str
class Dog(BaseModel):
pet_type: Literal['dog']
name: str
CommonPet = Annotated[Union[Cat, Dog], Field(discriminator='pet_type')]
class Lizard(BaseModel):
pet_type: Literal['reptile', 'lizard']
name: str
class Model(BaseModel):
pet: Union[CommonPet, Lizard] = Field(..., discriminator='pet_type')
n: int
assert isinstance(Model(**{'pet': {'pet_type': 'dog', 'name': 'Milou'}, 'n': 5}).pet, Dog)
def test_generic():
T = TypeVar('T')
class Success(BaseModel, Generic[T]):
type: Literal['Success'] = 'Success'
data: T
class Failure(BaseModel):
type: Literal['Failure'] = 'Failure'
error_message: str
class Container(BaseModel, Generic[T]):
result: Union[Success[T], Failure] = Field(discriminator='type')
with pytest.raises(ValidationError, match="Unable to extract tag using discriminator 'type'"):
Container[str].model_validate({'result': {}})
with pytest.raises(
ValidationError,
match=re.escape(
"Input tag 'Other' found using 'type' does not match any of the expected tags: 'Success', 'Failure'"
),
):
Container[str].model_validate({'result': {'type': 'Other'}})
with pytest.raises(ValidationError, match=r'Container\[str\]\nresult\.Success\.data') as exc_info:
Container[str].model_validate({'result': {'type': 'Success'}})
assert exc_info.value.errors(include_url=False) == [
{'input': {'type': 'Success'}, 'loc': ('result', 'Success', 'data'), 'msg': 'Field required', 'type': 'missing'}
]
# invalid types error
with pytest.raises(ValidationError) as exc_info:
Container[str].model_validate({'result': {'type': 'Success', 'data': 1}})
assert exc_info.value.errors(include_url=False) == [
{
'input': 1,
'loc': ('result', 'Success', 'data'),
'msg': 'Input should be a valid string',
'type': 'string_type',
}
]
assert Container[str].model_validate({'result': {'type': 'Success', 'data': '1'}}).result.data == '1'
def test_optional_union():
class Cat(BaseModel):
pet_type: Literal['cat']
name: str
class Dog(BaseModel):
pet_type: Literal['dog']
name: str
class Pet(BaseModel):
pet: Optional[Union[Cat, Dog]] = Field(discriminator='pet_type')
assert Pet(pet={'pet_type': 'cat', 'name': 'Milo'}).model_dump() == {'pet': {'name': 'Milo', 'pet_type': 'cat'}}
assert Pet(pet={'pet_type': 'dog', 'name': 'Otis'}).model_dump() == {'pet': {'name': 'Otis', 'pet_type': 'dog'}}
assert Pet(pet=None).model_dump() == {'pet': None}
with pytest.raises(ValidationError) as exc_info:
Pet()
assert exc_info.value.errors(include_url=False) == [
{'input': {}, 'loc': ('pet',), 'msg': 'Field required', 'type': 'missing'}
]
with pytest.raises(ValidationError) as exc_info:
Pet(pet={'name': 'Benji'})
assert exc_info.value.errors(include_url=False) == [
{
'ctx': {'discriminator': "'pet_type'"},
'input': {'name': 'Benji'},
'loc': ('pet',),
'msg': "Unable to extract tag using discriminator 'pet_type'",
'type': 'union_tag_not_found',
}
]
with pytest.raises(ValidationError) as exc_info:
Pet(pet={'pet_type': 'lizard'})
assert exc_info.value.errors(include_url=False) == [
{
'ctx': {'discriminator': "'pet_type'", 'expected_tags': "'cat', 'dog'", 'tag': 'lizard'},
'input': {'pet_type': 'lizard'},
'loc': ('pet',),
'msg': "Input tag 'lizard' found using 'pet_type' does not match any of the " "expected tags: 'cat', 'dog'",
'type': 'union_tag_invalid',
}
]
def test_optional_union_with_defaults():
class Cat(BaseModel):
pet_type: Literal['cat'] = 'cat'
name: str
class Dog(BaseModel):
pet_type: Literal['dog'] = 'dog'
name: str
class Pet(BaseModel):
pet: Optional[Union[Cat, Dog]] = Field(default=None, discriminator='pet_type')
assert Pet(pet={'pet_type': 'cat', 'name': 'Milo'}).model_dump() == {'pet': {'name': 'Milo', 'pet_type': 'cat'}}
assert Pet(pet={'pet_type': 'dog', 'name': 'Otis'}).model_dump() == {'pet': {'name': 'Otis', 'pet_type': 'dog'}}
assert Pet(pet=None).model_dump() == {'pet': None}
assert Pet().model_dump() == {'pet': None}
with pytest.raises(ValidationError) as exc_info:
Pet(pet={'name': 'Benji'})
assert exc_info.value.errors(include_url=False) == [
{
'ctx': {'discriminator': "'pet_type'"},
'input': {'name': 'Benji'},
'loc': ('pet',),
'msg': "Unable to extract tag using discriminator 'pet_type'",
'type': 'union_tag_not_found',
}
]
with pytest.raises(ValidationError) as exc_info:
Pet(pet={'pet_type': 'lizard'})
assert exc_info.value.errors(include_url=False) == [
{
'ctx': {'discriminator': "'pet_type'", 'expected_tags': "'cat', 'dog'", 'tag': 'lizard'},
'input': {'pet_type': 'lizard'},
'loc': ('pet',),
'msg': "Input tag 'lizard' found using 'pet_type' does not match any of the " "expected tags: 'cat', 'dog'",
'type': 'union_tag_invalid',
}
]
def test_aliases_matching_is_not_sufficient() -> None:
class Case1(BaseModel):
kind_one: Literal['1'] = Field(alias='kind')
class Case2(BaseModel):
kind_two: Literal['2'] = Field(alias='kind')
with pytest.raises(PydanticUserError, match="Model 'Case1' needs a discriminator field for key 'kind'"):
class TaggedParent(BaseModel):
tagged: Union[Case1, Case2] = Field(discriminator='kind')
def test_nested_optional_unions() -> None:
class Cat(BaseModel):
pet_type: Literal['cat'] = 'cat'
class Dog(BaseModel):
pet_type: Literal['dog'] = 'dog'
class Lizard(BaseModel):
pet_type: Literal['lizard', 'reptile'] = 'lizard'
MaybeCatDog = Annotated[Optional[Union[Cat, Dog]], Field(discriminator='pet_type')]
MaybeDogLizard = Annotated[Union[Dog, Lizard, None], Field(discriminator='pet_type')]
class Pet(BaseModel):
pet: Union[MaybeCatDog, MaybeDogLizard] = Field(discriminator='pet_type')
Pet.model_validate({'pet': {'pet_type': 'dog'}})
Pet.model_validate({'pet': {'pet_type': 'cat'}})
Pet.model_validate({'pet': {'pet_type': 'lizard'}})
Pet.model_validate({'pet': {'pet_type': 'reptile'}})
Pet.model_validate({'pet': None})
with pytest.raises(ValidationError) as exc_info:
Pet.model_validate({'pet': {'pet_type': None}})
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{
'type': 'union_tag_invalid',
'loc': ('pet',),
'msg': "Input tag 'None' found using 'pet_type' does not match any of the expected tags: 'cat', 'dog', 'lizard', 'reptile'",
'input': {'pet_type': None},
'ctx': {'discriminator': "'pet_type'", 'tag': 'None', 'expected_tags': "'cat', 'dog', 'lizard', 'reptile'"},
}
]
with pytest.raises(ValidationError) as exc_info:
Pet.model_validate({'pet': {'pet_type': 'fox'}})
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{
'type': 'union_tag_invalid',
'loc': ('pet',),
'msg': "Input tag 'fox' found using 'pet_type' does not match any of the expected tags: 'cat', 'dog', 'lizard', 'reptile'",
'input': {'pet_type': 'fox'},
'ctx': {'discriminator': "'pet_type'", 'tag': 'fox', 'expected_tags': "'cat', 'dog', 'lizard', 'reptile'"},
}
]
def test_nested_discriminated_union() -> None:
class Cat(BaseModel):
pet_type: Literal['cat', 'CAT']
class Dog(BaseModel):
pet_type: Literal['dog', 'DOG']
class Lizard(BaseModel):
pet_type: Literal['lizard', 'LIZARD']
CatDog = Annotated[Union[Cat, Dog], Field(discriminator='pet_type')]
CatDogLizard = Annotated[Union[CatDog, Lizard], Field(discriminator='pet_type')]
class Pet(BaseModel):
pet: CatDogLizard
Pet.model_validate({'pet': {'pet_type': 'dog'}})
Pet.model_validate({'pet': {'pet_type': 'cat'}})
Pet.model_validate({'pet': {'pet_type': 'lizard'}})
with pytest.raises(ValidationError) as exc_info:
Pet.model_validate({'pet': {'pet_type': 'reptile'}})
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{
'type': 'union_tag_invalid',
'loc': ('pet',),
'msg': "Input tag 'reptile' found using 'pet_type' does not match any of the expected tags: 'cat', 'CAT', 'dog', 'DOG', 'lizard', 'LIZARD'",
'input': {'pet_type': 'reptile'},
'ctx': {
'discriminator': "'pet_type'",
'tag': 'reptile',
'expected_tags': "'cat', 'CAT', 'dog', 'DOG', 'lizard', 'LIZARD'",
},
}
]
def test_unions_of_optionals() -> None:
class Cat(BaseModel):
pet_type: Literal['cat'] = Field(alias='typeOfPet')
c: str
class Dog(BaseModel):
pet_type: Literal['dog'] = Field(alias='typeOfPet')
d: str
class Lizard(BaseModel):
pet_type: Literal['lizard'] = Field(alias='typeOfPet')
MaybeCat = Annotated[Union[Cat, None], 'some annotation']
MaybeDogLizard = Annotated[Optional[Union[Dog, Lizard]], 'some other annotation']
class Model(BaseModel):
maybe_pet: Union[MaybeCat, MaybeDogLizard] = Field(discriminator='pet_type')
assert Model(**{'maybe_pet': None}).maybe_pet is None
assert Model(**{'maybe_pet': {'typeOfPet': 'dog', 'd': 'milou'}}).maybe_pet.pet_type == 'dog'
assert Model(**{'maybe_pet': {'typeOfPet': 'lizard'}}).maybe_pet.pet_type == 'lizard'
def test_union_discriminator_literals() -> None:
class Cat(BaseModel):
pet_type: Union[Literal['cat'], Literal['CAT']] = Field(alias='typeOfPet')
class Dog(BaseModel):
pet_type: Literal['dog'] = Field(alias='typeOfPet')
class Model(BaseModel):
pet: Union[Cat, Dog] = Field(discriminator='pet_type')
assert Model(**{'pet': {'typeOfPet': 'dog'}}).pet.pet_type == 'dog'
assert Model(**{'pet': {'typeOfPet': 'cat'}}).pet.pet_type == 'cat'
assert Model(**{'pet': {'typeOfPet': 'CAT'}}).pet.pet_type == 'CAT'
with pytest.raises(ValidationError) as exc_info:
Model(**{'pet': {'typeOfPet': 'Cat'}})
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{
'type': 'union_tag_invalid',
'loc': ('pet',),
'msg': "Input tag 'Cat' found using 'pet_type' | 'typeOfPet' does not match any of the expected tags: 'cat', 'CAT', 'dog'",
'input': {'typeOfPet': 'Cat'},
'ctx': {'discriminator': "'pet_type' | 'typeOfPet'", 'tag': 'Cat', 'expected_tags': "'cat', 'CAT', 'dog'"},
}
]
def test_none_schema() -> None:
cat_fields = {'kind': core_schema.typed_dict_field(core_schema.literal_schema(['cat']))}
dog_fields = {'kind': core_schema.typed_dict_field(core_schema.literal_schema(['dog']))}
cat = core_schema.typed_dict_schema(cat_fields)
dog = core_schema.typed_dict_schema(dog_fields)
schema = core_schema.union_schema([cat, dog, core_schema.none_schema()])
schema = apply_discriminator(schema, 'kind')
validator = SchemaValidator(schema)
assert validator.validate_python({'kind': 'cat'})['kind'] == 'cat'
assert validator.validate_python({'kind': 'dog'})['kind'] == 'dog'
assert validator.validate_python(None) is None
with pytest.raises(ValidationError) as exc_info:
validator.validate_python({'kind': 'lizard'})
assert exc_info.value.errors(include_url=False) == [
{
'ctx': {'discriminator': "'kind'", 'expected_tags': "'cat', 'dog'", 'tag': 'lizard'},
'input': {'kind': 'lizard'},
'loc': (),
'msg': "Input tag 'lizard' found using 'kind' does not match any of the " "expected tags: 'cat', 'dog'",
'type': 'union_tag_invalid',
}
]
def test_nested_unwrapping() -> None:
cat_fields = {'kind': core_schema.typed_dict_field(core_schema.literal_schema(['cat']))}
dog_fields = {'kind': core_schema.typed_dict_field(core_schema.literal_schema(['dog']))}
cat = core_schema.typed_dict_schema(cat_fields)
dog = core_schema.typed_dict_schema(dog_fields)
schema = core_schema.union_schema([cat, dog])
for _ in range(3):
schema = core_schema.nullable_schema(schema)
schema = core_schema.nullable_schema(schema)
schema = core_schema.definitions_schema(schema, [])
schema = core_schema.definitions_schema(schema, [])
schema = apply_discriminator(schema, 'kind')
validator = SchemaValidator(schema)
assert validator.validate_python({'kind': 'cat'})['kind'] == 'cat'
assert validator.validate_python({'kind': 'dog'})['kind'] == 'dog'
assert validator.validate_python(None) is None
with pytest.raises(ValidationError) as exc_info:
validator.validate_python({'kind': 'lizard'})
assert exc_info.value.errors(include_url=False) == [
{
'ctx': {'discriminator': "'kind'", 'expected_tags': "'cat', 'dog'", 'tag': 'lizard'},
'input': {'kind': 'lizard'},
'loc': (),
'msg': "Input tag 'lizard' found using 'kind' does not match any of the " "expected tags: 'cat', 'dog'",
'type': 'union_tag_invalid',
}
]
def test_distinct_choices() -> None:
class Cat(BaseModel):
pet_type: Literal['cat', 'dog'] = Field(alias='typeOfPet')
class Dog(BaseModel):
pet_type: Literal['dog'] = Field(alias='typeOfPet')
with pytest.raises(TypeError, match="Value 'dog' for discriminator 'pet_type' mapped to multiple choices"):
class Model(BaseModel):
pet: Union[Cat, Dog] = Field(discriminator='pet_type')
def test_invalid_discriminated_union_type() -> None:
class Cat(BaseModel):
pet_type: Literal['cat'] = Field(alias='typeOfPet')
class Dog(BaseModel):
pet_type: Literal['dog'] = Field(alias='typeOfPet')
with pytest.raises(
TypeError, match="'str' is not a valid discriminated union variant; should be a `BaseModel` or `dataclass`"
):
class Model(BaseModel):
pet: Union[Cat, Dog, str] = Field(discriminator='pet_type')
def test_invalid_alias() -> None:
cat_fields = {
'kind': core_schema.typed_dict_field(core_schema.literal_schema(['cat']), validation_alias=['cat', 'CAT'])
}
dog_fields = {'kind': core_schema.typed_dict_field(core_schema.literal_schema(['dog']))}
cat = core_schema.typed_dict_schema(cat_fields)
dog = core_schema.typed_dict_schema(dog_fields)
schema = core_schema.union_schema([cat, dog])
with pytest.raises(TypeError, match=re.escape("Alias ['cat', 'CAT'] is not supported in a discriminated union")):
apply_discriminator(schema, 'kind')
def test_invalid_discriminator_type() -> None:
cat_fields = {'kind': core_schema.typed_dict_field(core_schema.int_schema())}
dog_fields = {'kind': core_schema.typed_dict_field(core_schema.str_schema())}
cat = core_schema.typed_dict_schema(cat_fields)
dog = core_schema.typed_dict_schema(dog_fields)
with pytest.raises(TypeError, match=re.escape("TypedDict needs field 'kind' to be of type `Literal`")):
apply_discriminator(core_schema.union_schema([cat, dog]), 'kind')
def test_missing_discriminator_field() -> None:
cat_fields = {'kind': core_schema.typed_dict_field(core_schema.int_schema())}
dog_fields = {}
cat = core_schema.typed_dict_schema(cat_fields)
dog = core_schema.typed_dict_schema(dog_fields)
with pytest.raises(TypeError, match=re.escape("TypedDict needs a discriminator field for key 'kind'")):
apply_discriminator(core_schema.union_schema([dog, cat]), 'kind')
def test_wrap_function_schema() -> None:
cat_fields = {'kind': core_schema.typed_dict_field(core_schema.literal_schema(['cat']))}
dog_fields = {'kind': core_schema.typed_dict_field(core_schema.literal_schema(['dog']))}
cat = core_schema.with_info_wrap_validator_function(lambda x, y, z: None, core_schema.typed_dict_schema(cat_fields))
dog = core_schema.typed_dict_schema(dog_fields)
schema = core_schema.union_schema([cat, dog])
assert apply_discriminator(schema, 'kind') == {
'choices': {
'cat': {
'function': {
'type': 'with-info',
'function': HasRepr(IsStr(regex=r'<function [a-z_]*\.<locals>\.<lambda> at 0x[0-9a-fA-F]+>')),
},
'schema': {
'fields': {
'kind': {'schema': {'expected': ['cat'], 'type': 'literal'}, 'type': 'typed-dict-field'}
},
'type': 'typed-dict',
},
'type': 'function-wrap',
},
'dog': {
'fields': {'kind': {'schema': {'expected': ['dog'], 'type': 'literal'}, 'type': 'typed-dict-field'}},
'type': 'typed-dict',
},
},
'discriminator': 'kind',
'from_attributes': True,
'strict': False,
'type': 'tagged-union',
}
def test_plain_function_schema_is_invalid() -> None:
with pytest.raises(
TypeError,
match="'function-plain' is not a valid discriminated union variant; " 'should be a `BaseModel` or `dataclass`',
):
apply_discriminator(
core_schema.union_schema(
[core_schema.with_info_plain_validator_function(lambda x, y: None), core_schema.int_schema()]
),
'kind',
)
def test_invalid_str_choice_discriminator_values() -> None:
cat = core_schema.typed_dict_schema({'kind': core_schema.typed_dict_field(core_schema.literal_schema(['cat']))})
dog = core_schema.str_schema()
schema = core_schema.union_schema(
[
cat,
# NOTE: Wrapping the union with a validator results in failure to more thoroughly decompose the tagged
# union. I think this would be difficult to avoid in the general case, and I would suggest that we not
# attempt to do more than this until presented with scenarios where it is helpful/necessary.
core_schema.with_info_wrap_validator_function(lambda x, y, z: x, dog),
]
)
with pytest.raises(
TypeError, match="'str' is not a valid discriminated union variant; should be a `BaseModel` or `dataclass`"
):
apply_discriminator(schema, 'kind')
def test_lax_or_strict_definitions() -> None:
cat = core_schema.typed_dict_schema({'kind': core_schema.typed_dict_field(core_schema.literal_schema(['cat']))})
lax_dog = core_schema.typed_dict_schema({'kind': core_schema.typed_dict_field(core_schema.literal_schema(['DOG']))})
strict_dog = core_schema.definitions_schema(
core_schema.typed_dict_schema({'kind': core_schema.typed_dict_field(core_schema.literal_schema(['dog']))}),
[core_schema.int_schema(ref='my-int-definition')],
)
dog = core_schema.definitions_schema(
core_schema.lax_or_strict_schema(lax_schema=lax_dog, strict_schema=strict_dog),
[core_schema.str_schema(ref='my-str-definition')],
)
discriminated_schema = apply_discriminator(core_schema.union_schema([cat, dog]), 'kind')
# insert_assert(discriminated_schema)
assert discriminated_schema == {
'type': 'tagged-union',
'choices': {
'cat': {
'type': 'typed-dict',
'fields': {'kind': {'type': 'typed-dict-field', 'schema': {'type': 'literal', 'expected': ['cat']}}},
},
'DOG': {
'type': 'lax-or-strict',
'lax_schema': {
'type': 'typed-dict',
'fields': {
'kind': {'type': 'typed-dict-field', 'schema': {'type': 'literal', 'expected': ['DOG']}}
},