|
8 | 8 |
|
9 | 9 | from pydantic_core import (
|
10 | 10 | ArgsKwargs,
|
| 11 | + PydanticUndefined, |
11 | 12 | PydanticUseDefault,
|
12 | 13 | SchemaError,
|
13 | 14 | SchemaValidator,
|
@@ -819,3 +820,59 @@ def _raise(ex: Exception) -> None:
|
819 | 820 | v.validate_python(input_value)
|
820 | 821 |
|
821 | 822 | assert exc_info.value.errors(include_url=False, include_context=False) == expected
|
| 823 | + |
| 824 | + |
| 825 | +def test_default_factory_not_called_if_existing_error(pydantic_version) -> None: |
| 826 | + class Test: |
| 827 | + def __init__(self, a: int, b: int): |
| 828 | + self.a = a |
| 829 | + self.b = b |
| 830 | + |
| 831 | + schema = core_schema.model_schema( |
| 832 | + cls=Test, |
| 833 | + schema=core_schema.model_fields_schema( |
| 834 | + computed_fields=[], |
| 835 | + fields={ |
| 836 | + 'a': core_schema.model_field( |
| 837 | + schema=core_schema.int_schema(), |
| 838 | + ), |
| 839 | + 'b': core_schema.model_field( |
| 840 | + schema=core_schema.with_default_schema( |
| 841 | + schema=core_schema.int_schema(), |
| 842 | + default_factory=lambda data: data['a'], |
| 843 | + default_factory_takes_data=True, |
| 844 | + ), |
| 845 | + ), |
| 846 | + }, |
| 847 | + ), |
| 848 | + ) |
| 849 | + |
| 850 | + v = SchemaValidator(schema) |
| 851 | + with pytest.raises(ValidationError) as e: |
| 852 | + v.validate_python({'a': 'not_an_int'}) |
| 853 | + |
| 854 | + assert e.value.errors(include_url=False) == [ |
| 855 | + { |
| 856 | + 'type': 'int_parsing', |
| 857 | + 'loc': ('a',), |
| 858 | + 'msg': 'Input should be a valid integer, unable to parse string as an integer', |
| 859 | + 'input': 'not_an_int', |
| 860 | + }, |
| 861 | + { |
| 862 | + 'input': PydanticUndefined, |
| 863 | + 'loc': ('b',), |
| 864 | + 'msg': 'The default factory uses validated data, but at least one validation error occurred', |
| 865 | + 'type': 'default_factory_not_called', |
| 866 | + }, |
| 867 | + ] |
| 868 | + |
| 869 | + assert ( |
| 870 | + str(e.value) |
| 871 | + == f"""2 validation errors for Test |
| 872 | +a |
| 873 | + Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='not_an_int', input_type=str] |
| 874 | + For further information visit https://errors.pydantic.dev/{pydantic_version}/v/int_parsing |
| 875 | +b |
| 876 | + The default factory uses validated data, but at least one validation error occurred [type=default_factory_not_called] |
| 877 | + For further information visit https://errors.pydantic.dev/{pydantic_version}/v/default_factory_not_called""" |
| 878 | + ) |
0 commit comments