diff --git a/end_to_end_tests/functional_tests/generated_code_execution/test_unions.py b/end_to_end_tests/functional_tests/generated_code_execution/test_unions.py index ca20e64ac..64693f8d8 100644 --- a/end_to_end_tests/functional_tests/generated_code_execution/test_unions.py +++ b/end_to_end_tests/functional_tests/generated_code_execution/test_unions.py @@ -1,3 +1,7 @@ +from uuid import UUID + +import pytest + from end_to_end_tests.functional_tests.helpers import ( assert_model_decode_encode, assert_model_property_type_hint, @@ -6,6 +10,63 @@ ) +@with_generated_client_fixture( + """ +components: + schemas: + Child: + type: object + required: [id] + properties: + id: {type: string, format: uuid} + Thing: + type: object + required: [child] + properties: + child: + anyOf: + - $ref: "#/components/schemas/Child" + - type: "null" + OptionalThing: + type: object + properties: + child: + oneOf: + - type: "null" + - $ref: "#/components/schemas/Child" + MixedThing: + type: object + required: [child] + properties: + child: + anyOf: + - $ref: "#/components/schemas/Child" + - type: "null" + - type: string +""" +) +@with_generated_code_imports(".models.Child", ".models.Thing", ".models.OptionalThing", ".models.MixedThing") +class TestNullableModel: + def test_valid_nullable_models_round_trip(self, Child, Thing, OptionalThing, MixedThing): + value = UUID("89d81c74-f6f5-46d6-a9d5-6dbc084d04aa") + for model in (Thing, OptionalThing, MixedThing): + assert_model_decode_encode(model, {"child": {"id": str(value)}}, model(child=Child(id=value))) + assert_model_decode_encode(model, {"child": None}, model(child=None)) + assert_model_decode_encode(OptionalThing, {}, OptionalThing()) + assert_model_decode_encode(MixedThing, {"child": "external"}, MixedThing(child="external")) + assert_model_property_type_hint(Thing, "child", "Child | None") + assert_model_property_type_hint(OptionalThing, "child", "Child | None | Unset") + + @pytest.mark.parametrize( + ("child", "error"), + [({}, KeyError), ({"id": "invalid"}, ValueError), ("external", TypeError), (7, TypeError)], + ) + def test_invalid_nested_model_raises(self, Thing, OptionalThing, child, error): + for model in (Thing, OptionalThing): + with pytest.raises(error): + model.from_dict({"child": child}) + + @with_generated_client_fixture( """ components: diff --git a/end_to_end_tests/golden-records/my-test-api-client/my_test_api_client/models/a_model.py b/end_to_end_tests/golden-records/my-test-api-client/my_test_api_client/models/a_model.py index 4ca83858f..ddc5d0325 100644 --- a/end_to_end_tests/golden-records/my-test-api-client/my_test_api_client/models/a_model.py +++ b/end_to_end_tests/golden-records/my-test-api-client/my_test_api_client/models/a_model.py @@ -373,15 +373,11 @@ def _parse_nullable_one_of_models(data: object) -> FreeFormModel | ModelWithUnio def _parse_nullable_model(data: object) -> ModelWithUnionProperty | None: if data is None: return data - try: - if not isinstance(data, dict): - raise TypeError() - nullable_model_type_1 = ModelWithUnionProperty.from_dict(data) + if not isinstance(data, dict): + raise TypeError() + nullable_model_type_1 = ModelWithUnionProperty.from_dict(data) - return nullable_model_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(ModelWithUnionProperty | None, data) + return nullable_model_type_1 nullable_model = _parse_nullable_model(d.pop("nullable_model")) @@ -497,15 +493,11 @@ def _parse_not_required_nullable_model(data: object) -> ModelWithUnionProperty | return data if isinstance(data, Unset): return data - try: - if not isinstance(data, dict): - raise TypeError() - not_required_nullable_model_type_1 = ModelWithUnionProperty.from_dict(data) + if not isinstance(data, dict): + raise TypeError() + not_required_nullable_model_type_1 = ModelWithUnionProperty.from_dict(data) - return not_required_nullable_model_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(ModelWithUnionProperty | None | Unset, data) + return not_required_nullable_model_type_1 not_required_nullable_model = _parse_not_required_nullable_model(d.pop("not_required_nullable_model", UNSET)) diff --git a/end_to_end_tests/golden-records/my-test-api-client/my_test_api_client/models/body_upload_file_tests_upload_post.py b/end_to_end_tests/golden-records/my-test-api-client/my_test_api_client/models/body_upload_file_tests_upload_post.py index df8fdc77f..9b8d1fc59 100644 --- a/end_to_end_tests/golden-records/my-test-api-client/my_test_api_client/models/body_upload_file_tests_upload_post.py +++ b/end_to_end_tests/golden-records/my-test-api-client/my_test_api_client/models/body_upload_file_tests_upload_post.py @@ -273,15 +273,11 @@ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: def _parse_some_nullable_object(data: object) -> BodyUploadFileTestsUploadPostSomeNullableObject | None: if data is None: return data - try: - if not isinstance(data, dict): - raise TypeError() - some_nullable_object_type_0 = BodyUploadFileTestsUploadPostSomeNullableObject.from_dict(data) + if not isinstance(data, dict): + raise TypeError() + some_nullable_object_type_0 = BodyUploadFileTestsUploadPostSomeNullableObject.from_dict(data) - return some_nullable_object_type_0 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(BodyUploadFileTestsUploadPostSomeNullableObject | None, data) + return some_nullable_object_type_0 some_nullable_object = _parse_some_nullable_object(d.pop("some_nullable_object")) diff --git a/end_to_end_tests/golden-records/my-test-api-client/my_test_api_client/models/extended.py b/end_to_end_tests/golden-records/my-test-api-client/my_test_api_client/models/extended.py index cf4966bf0..66e878d2a 100644 --- a/end_to_end_tests/golden-records/my-test-api-client/my_test_api_client/models/extended.py +++ b/end_to_end_tests/golden-records/my-test-api-client/my_test_api_client/models/extended.py @@ -380,15 +380,11 @@ def _parse_nullable_one_of_models(data: object) -> FreeFormModel | ModelWithUnio def _parse_nullable_model(data: object) -> ModelWithUnionProperty | None: if data is None: return data - try: - if not isinstance(data, dict): - raise TypeError() - nullable_model_type_1 = ModelWithUnionProperty.from_dict(data) + if not isinstance(data, dict): + raise TypeError() + nullable_model_type_1 = ModelWithUnionProperty.from_dict(data) - return nullable_model_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(ModelWithUnionProperty | None, data) + return nullable_model_type_1 nullable_model = _parse_nullable_model(d.pop("nullable_model")) @@ -504,15 +500,11 @@ def _parse_not_required_nullable_model(data: object) -> ModelWithUnionProperty | return data if isinstance(data, Unset): return data - try: - if not isinstance(data, dict): - raise TypeError() - not_required_nullable_model_type_1 = ModelWithUnionProperty.from_dict(data) + if not isinstance(data, dict): + raise TypeError() + not_required_nullable_model_type_1 = ModelWithUnionProperty.from_dict(data) - return not_required_nullable_model_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(ModelWithUnionProperty | None | Unset, data) + return not_required_nullable_model_type_1 not_required_nullable_model = _parse_not_required_nullable_model(d.pop("not_required_nullable_model", UNSET)) diff --git a/openapi_python_client/parser/properties/union.py b/openapi_python_client/parser/properties/union.py index 788e803a6..d88799318 100644 --- a/openapi_python_client/parser/properties/union.py +++ b/openapi_python_client/parser/properties/union.py @@ -10,6 +10,7 @@ from ... import schema as oai from ...strings import PythonIdentifier from ..errors import ParseError, PropertyError +from .none import NoneProperty from .protocol import PropertyProtocol, Value, convert_example from .schemas import Schemas @@ -174,6 +175,18 @@ def get_type_strings_in_union(self, *, no_optional: bool = False, json: bool) -> type_strings.add(strings.PythonCode("Unset")) return type_strings + def get_construct_properties(self) -> list[PropertyProtocol]: + """Use the normal model parser after the generated null check.""" + from .model_property import ModelProperty # noqa: PLC0415 + + if len(self.inner_properties) == 2: + first, second = self.inner_properties + if isinstance(first, NoneProperty): + first, second = second, first + if isinstance(first, ModelProperty) and isinstance(second, NoneProperty): + return [first] + return self.inner_properties + def get_type_string( self, no_optional: bool = False, diff --git a/openapi_python_client/templates/property_templates/union_property.py.jinja b/openapi_python_client/templates/property_templates/union_property.py.jinja index 45f350f5e..d333ab8c5 100644 --- a/openapi_python_client/templates/property_templates/union_property.py.jinja +++ b/openapi_python_client/templates/property_templates/union_property.py.jinja @@ -9,7 +9,7 @@ def _parse_{{ property.python_name }}(data: object) -> {{ property.get_type_stri return data {% endif %} {% set ns = namespace(contains_unmodified_properties = false) %} - {% for inner_property in property.inner_properties %} + {% for inner_property in property.get_construct_properties() %} {% import "property_templates/" + inner_property.template as inner_template %} {% if not inner_template.construct %} {% set ns.contains_unmodified_properties = true %}