| 799 | |
| 800 | |
| 801 | def test_annotated_discriminator(): |
| 802 | class Cat(BaseModel): |
| 803 | type: Literal['cat'] = 'cat' |
| 804 | food: str |
| 805 | meow: int |
| 806 | |
| 807 | class Dog(BaseModel): |
| 808 | type: Literal['dog'] = 'dog' |
| 809 | food: str |
| 810 | bark: int |
| 811 | |
| 812 | Pet = Annotated[Union[Cat, Dog], Field(discriminator='type')] |
| 813 | |
| 814 | @validate_call |
| 815 | def f(pet: Pet): |
| 816 | return pet |
| 817 | |
| 818 | with pytest.raises(ValidationError) as exc_info: |
| 819 | f({'food': 'fish'}) |
| 820 | |
| 821 | assert exc_info.value.errors(include_url=False) == [ |
| 822 | { |
| 823 | 'type': 'union_tag_not_found', |
| 824 | 'loc': (0,), |
| 825 | 'msg': "Unable to extract tag using discriminator 'type'", |
| 826 | 'input': {'food': 'fish'}, |
| 827 | 'ctx': {'discriminator': "'type'"}, |
| 828 | } |
| 829 | ] |
| 830 | |
| 831 | with pytest.raises(ValidationError) as exc_info: |
| 832 | f({'type': 'dog', 'food': 'fish'}) |
| 833 | |
| 834 | assert exc_info.value.errors(include_url=False) == [ |
| 835 | { |
| 836 | 'type': 'missing', |
| 837 | 'loc': (0, 'dog', 'bark'), |
| 838 | 'msg': 'Field required', |
| 839 | 'input': {'type': 'dog', 'food': 'fish'}, |
| 840 | } |
| 841 | ] |
| 842 | |
| 843 | |
| 844 | def test_annotated_validator(): |