diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonCodegen.java index f287900ef120..14e5468e7e84 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonCodegen.java @@ -1122,6 +1122,10 @@ private ModelsMap postProcessModelsMap(ModelsMap objs) { readOnlyFields.add(cp.name); } + if (cp.vendorExtensions.containsKey("x-python-not-string-enum-values")) { + moduleImports.add(PYDANTIC, "field_validator"); + } + String typing = pydantic.generatePythonType(cp); cp.vendorExtensions.put(X_PY_TYPING, typing); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientCodegen.java index a2001a0633de..af9aab3b7388 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientCodegen.java @@ -1048,6 +1048,20 @@ public void postProcessParameter(CodegenParameter parameter) { @Override public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { super.postProcessModelProperty(model, property); + + if (property.getComposedSchemas() != null + && property.getComposedSchemas().getNot() != null) { + CodegenProperty notProperty = property.getComposedSchemas().getNot(); + if (notProperty.isEnum + && notProperty.isString + && notProperty.allowableValues != null + && notProperty.allowableValues.get("values") != null) { + property.vendorExtensions.put( + "x-python-not-string-enum-values", + notProperty.allowableValues.get("values")); + } + } + if (hasOneOf(model) || hasAnyOf(model)) { return; } diff --git a/modules/openapi-generator/src/main/resources/python/model_generic.mustache b/modules/openapi-generator/src/main/resources/python/model_generic.mustache index 3d1758ac7ec6..67ee274208cf 100644 --- a/modules/openapi-generator/src/main/resources/python/model_generic.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_generic.mustache @@ -133,6 +133,26 @@ https://github.com/OpenAPITools/openapi-generator/blob/c84b949df1a9ec04ba75989cb {{/isContainer}} return value {{/isEnum}} + {{#vendorExtensions.x-python-not-string-enum-values.size}} + @field_validator('{{{name}}}') + def {{{name}}}_validate_not_enum(cls, value): + """Validates values excluded by not""" + {{^required}} + if value is None: + return value + + {{/required}} + {{#required}} + {{#isNullable}} + if value is None: + return value + + {{/isNullable}} + {{/required}} + if value in set([{{#vendorExtensions.x-python-not-string-enum-values}}{{#lambda.pythonStringLiteral}}{{{.}}}{{/lambda.pythonStringLiteral}}{{^-last}}, {{/-last}}{{/vendorExtensions.x-python-not-string-enum-values}}]): + raise ValueError("must not be one of excluded enum values") + return value + {{/vendorExtensions.x-python-not-string-enum-values.size}} {{/vars}} {{#vendorExtensions.x-py-preprocesses-input-names}} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientCodegenTest.java index 2d8557046e31..4c90e38d4ab7 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientCodegenTest.java @@ -198,6 +198,39 @@ public void testInitialConfigValues() throws Exception { Assert.assertNull(codegen.additionalProperties().get(CodegenConstants.SOURCE_FOLDER)); } + @Test + public void testOneOfNotEnumValidation() throws IOException { + File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); + output.deleteOnExit(); + + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("python") + .setInputSpec("src/test/resources/3_1/python/oneof-not-enum.yaml") + .setOutputDir(output.getAbsolutePath()); + + DefaultGenerator generator = new DefaultGenerator(); + List files = generator.opts(configurator.toClientOptInput()).generate(); + files.forEach(File::deleteOnExit); + + Path other = Paths.get( + output.getAbsolutePath(), + "openapi_client", + "models", + "other.py"); + + String otherContent = Files.readString(other); + + Assert.assertTrue(otherContent.contains( + "if value in set([\"known\", \"reserved\"]):")); + Assert.assertTrue(otherContent.contains( + "raise ValueError(\"must not be one of excluded enum values\")")); + Assert.assertTrue(otherContent.contains("@field_validator('kind')")); + + Assert.assertEquals( + otherContent.split("def kind_validate_not_enum", -1).length - 1, + 1); + } + @Test public void testSettersForConfigValues() throws Exception { final PythonClientCodegen codegen = new PythonClientCodegen(); diff --git a/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing.yaml index 6663907fa17d..6de2721e479b 100644 --- a/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing.yaml @@ -2975,3 +2975,30 @@ components: type: string recursive: type: boolean + + Known: + type: object + required: + - kind + properties: + kind: + type: string + enum: + - known + + Other: + type: object + required: + - kind + properties: + kind: + type: string + not: + enum: + - known + - reserved + + TaggedUnion: + oneOf: + - $ref: '#/components/schemas/Known' + - $ref: '#/components/schemas/Other' diff --git a/modules/openapi-generator/src/test/resources/3_1/python/oneof-not-enum.yaml b/modules/openapi-generator/src/test/resources/3_1/python/oneof-not-enum.yaml new file mode 100644 index 000000000000..baee94e2394e --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_1/python/oneof-not-enum.yaml @@ -0,0 +1,36 @@ +openapi: 3.1.0 + +info: + title: oneOf not enum repro + version: 1.0.0 + +paths: {} + +components: + schemas: + Known: + type: object + required: + - kind + properties: + kind: + type: string + enum: + - known + + Other: + type: object + required: + - kind + properties: + kind: + type: string + not: + enum: + - known + - reserved + + TaggedUnion: + oneOf: + - $ref: '#/components/schemas/Known' + - $ref: '#/components/schemas/Other' diff --git a/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/FILES b/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/FILES index d808742215cb..b41f3bc2bf8f 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/FILES @@ -65,6 +65,7 @@ docs/Info.md docs/InnerDictWithProperty.md docs/InputAllOf.md docs/IntOrString.md +docs/Known.md docs/ListClass.md docs/MapOfArrayOfModel.md docs/MapTest.md @@ -82,6 +83,7 @@ docs/ObjectToTestAdditionalProperties.md docs/ObjectWithDeprecatedFields.md docs/OneOfEnumString.md docs/Order.md +docs/Other.md docs/OuterComposite.md docs/OuterEnum.md docs/OuterEnumDefaultValue.md @@ -108,6 +110,7 @@ docs/SpecialModelName.md docs/SpecialName.md docs/StoreApi.md docs/Tag.md +docs/TaggedUnion.md docs/Task.md docs/TaskActivity.md docs/TestEnum.md @@ -199,6 +202,7 @@ petstore_api/models/info.py petstore_api/models/inner_dict_with_property.py petstore_api/models/input_all_of.py petstore_api/models/int_or_string.py +petstore_api/models/known.py petstore_api/models/list_class.py petstore_api/models/map_of_array_of_model.py petstore_api/models/map_test.py @@ -216,6 +220,7 @@ petstore_api/models/object_to_test_additional_properties.py petstore_api/models/object_with_deprecated_fields.py petstore_api/models/one_of_enum_string.py petstore_api/models/order.py +petstore_api/models/other.py petstore_api/models/outer_composite.py petstore_api/models/outer_enum.py petstore_api/models/outer_enum_default_value.py @@ -240,6 +245,7 @@ petstore_api/models/special_character_enum.py petstore_api/models/special_model_name.py petstore_api/models/special_name.py petstore_api/models/tag.py +petstore_api/models/tagged_union.py petstore_api/models/task.py petstore_api/models/task_activity.py petstore_api/models/test_enum.py diff --git a/samples/openapi3/client/petstore/python-aiohttp/README.md b/samples/openapi3/client/petstore/python-aiohttp/README.md index 1fa59cd7e51b..0fb94c50ef00 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/README.md +++ b/samples/openapi3/client/petstore/python-aiohttp/README.md @@ -236,6 +236,7 @@ Class | Method | HTTP request | Description - [InnerDictWithProperty](docs/InnerDictWithProperty.md) - [InputAllOf](docs/InputAllOf.md) - [IntOrString](docs/IntOrString.md) + - [Known](docs/Known.md) - [ListClass](docs/ListClass.md) - [MapOfArrayOfModel](docs/MapOfArrayOfModel.md) - [MapTest](docs/MapTest.md) @@ -253,6 +254,7 @@ Class | Method | HTTP request | Description - [ObjectWithDeprecatedFields](docs/ObjectWithDeprecatedFields.md) - [OneOfEnumString](docs/OneOfEnumString.md) - [Order](docs/Order.md) + - [Other](docs/Other.md) - [OuterComposite](docs/OuterComposite.md) - [OuterEnum](docs/OuterEnum.md) - [OuterEnumDefaultValue](docs/OuterEnumDefaultValue.md) @@ -277,6 +279,7 @@ Class | Method | HTTP request | Description - [SpecialModelName](docs/SpecialModelName.md) - [SpecialName](docs/SpecialName.md) - [Tag](docs/Tag.md) + - [TaggedUnion](docs/TaggedUnion.md) - [Task](docs/Task.md) - [TaskActivity](docs/TaskActivity.md) - [TestEnum](docs/TestEnum.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Known.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Known.md new file mode 100644 index 000000000000..fba8453dcd02 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Known.md @@ -0,0 +1,29 @@ +# Known + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **str** | | + +## Example + +```python +from petstore_api.models.known import Known + +# TODO update the JSON string below +json = "{}" +# create an instance of Known from a JSON string +known_instance = Known.from_json(json) +# print the JSON string representation of the object +print(Known.to_json()) + +# convert the object into a dict +known_dict = known_instance.to_dict() +# create an instance of Known from a dict +known_from_dict = Known.from_dict(known_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Other.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Other.md new file mode 100644 index 000000000000..972767b30e1d --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Other.md @@ -0,0 +1,29 @@ +# Other + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **str** | | + +## Example + +```python +from petstore_api.models.other import Other + +# TODO update the JSON string below +json = "{}" +# create an instance of Other from a JSON string +other_instance = Other.from_json(json) +# print the JSON string representation of the object +print(Other.to_json()) + +# convert the object into a dict +other_dict = other_instance.to_dict() +# create an instance of Other from a dict +other_from_dict = Other.from_dict(other_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/TaggedUnion.md b/samples/openapi3/client/petstore/python-aiohttp/docs/TaggedUnion.md new file mode 100644 index 000000000000..fdeed022e4c7 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/TaggedUnion.md @@ -0,0 +1,29 @@ +# TaggedUnion + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **str** | | + +## Example + +```python +from petstore_api.models.tagged_union import TaggedUnion + +# TODO update the JSON string below +json = "{}" +# create an instance of TaggedUnion from a JSON string +tagged_union_instance = TaggedUnion.from_json(json) +# print the JSON string representation of the object +print(TaggedUnion.to_json()) + +# convert the object into a dict +tagged_union_dict = tagged_union_instance.to_dict() +# create an instance of TaggedUnion from a dict +tagged_union_from_dict = TaggedUnion.from_dict(tagged_union_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/__init__.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/__init__.py index 55be0097b9d0..051197ea04f4 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/__init__.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/__init__.py @@ -93,6 +93,7 @@ "InnerDictWithProperty", "InputAllOf", "IntOrString", + "Known", "ListClass", "MapOfArrayOfModel", "MapTest", @@ -110,6 +111,7 @@ "ObjectWithDeprecatedFields", "OneOfEnumString", "Order", + "Other", "OuterComposite", "OuterEnum", "OuterEnumDefaultValue", @@ -134,6 +136,7 @@ "SpecialModelName", "SpecialName", "Tag", + "TaggedUnion", "Task", "TaskActivity", "TestEnum", @@ -233,6 +236,7 @@ from petstore_api.models.inner_dict_with_property import InnerDictWithProperty as InnerDictWithProperty from petstore_api.models.input_all_of import InputAllOf as InputAllOf from petstore_api.models.int_or_string import IntOrString as IntOrString +from petstore_api.models.known import Known as Known from petstore_api.models.list_class import ListClass as ListClass from petstore_api.models.map_of_array_of_model import MapOfArrayOfModel as MapOfArrayOfModel from petstore_api.models.map_test import MapTest as MapTest @@ -250,6 +254,7 @@ from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields as ObjectWithDeprecatedFields from petstore_api.models.one_of_enum_string import OneOfEnumString as OneOfEnumString from petstore_api.models.order import Order as Order +from petstore_api.models.other import Other as Other from petstore_api.models.outer_composite import OuterComposite as OuterComposite from petstore_api.models.outer_enum import OuterEnum as OuterEnum from petstore_api.models.outer_enum_default_value import OuterEnumDefaultValue as OuterEnumDefaultValue @@ -274,6 +279,7 @@ from petstore_api.models.special_model_name import SpecialModelName as SpecialModelName from petstore_api.models.special_name import SpecialName as SpecialName from petstore_api.models.tag import Tag as Tag +from petstore_api.models.tagged_union import TaggedUnion as TaggedUnion from petstore_api.models.task import Task as Task from petstore_api.models.task_activity import TaskActivity as TaskActivity from petstore_api.models.test_enum import TestEnum as TestEnum diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/__init__.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/__init__.py index 488a82150d32..662ae4a8325d 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/__init__.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/__init__.py @@ -70,6 +70,7 @@ from petstore_api.models.inner_dict_with_property import InnerDictWithProperty from petstore_api.models.input_all_of import InputAllOf from petstore_api.models.int_or_string import IntOrString +from petstore_api.models.known import Known from petstore_api.models.list_class import ListClass from petstore_api.models.map_of_array_of_model import MapOfArrayOfModel from petstore_api.models.map_test import MapTest @@ -87,6 +88,7 @@ from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields from petstore_api.models.one_of_enum_string import OneOfEnumString from petstore_api.models.order import Order +from petstore_api.models.other import Other from petstore_api.models.outer_composite import OuterComposite from petstore_api.models.outer_enum import OuterEnum from petstore_api.models.outer_enum_default_value import OuterEnumDefaultValue @@ -111,6 +113,7 @@ from petstore_api.models.special_model_name import SpecialModelName from petstore_api.models.special_name import SpecialName from petstore_api.models.tag import Tag +from petstore_api.models.tagged_union import TaggedUnion from petstore_api.models.task import Task from petstore_api.models.task_activity import TaskActivity from petstore_api.models.test_enum import TestEnum diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/known.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/known.py new file mode 100644 index 000000000000..daf64e57b96d --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/known.py @@ -0,0 +1,95 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class Known(BaseModel): + """ + Known + """ # noqa: E501 + kind: StrictStr + __properties: ClassVar[List[str]] = ["kind"] + + @field_validator('kind') + def kind_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['known']): + raise ValueError("must be one of enum values ('known')") + return value + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Known from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Known from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "kind": obj.get("kind") + }) + return _obj + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/other.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/other.py new file mode 100644 index 000000000000..2f8d6ca1a282 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/other.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class Other(BaseModel): + """ + Other + """ # noqa: E501 + kind: StrictStr + __properties: ClassVar[List[str]] = ["kind"] + @field_validator('kind') + def kind_validate_not_enum(cls, value): + """Validates values excluded by not""" + if value in set(["known", "reserved"]): + raise ValueError("must not be one of excluded enum values") + return value + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Other from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Other from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "kind": obj.get("kind") + }) + return _obj + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/tagged_union.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/tagged_union.py new file mode 100644 index 000000000000..2930dd983976 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/tagged_union.py @@ -0,0 +1,137 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +import pprint +from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional +from petstore_api.models.known import Known +from petstore_api.models.other import Other +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self + +TAGGEDUNION_ONE_OF_SCHEMAS = ["Known", "Other"] + +class TaggedUnion(BaseModel): + """ + TaggedUnion + """ + # data type: Known + oneof_schema_1_validator: Optional[Known] = None + # data type: Other + oneof_schema_2_validator: Optional[Other] = None + actual_instance: Optional[Union[Known, Other]] = None + one_of_schemas: Set[str] = { "Known", "Other" } + + model_config = ConfigDict( + validate_assignment=True, + protected_namespaces=(), + ) + + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @field_validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = TaggedUnion.model_construct() + error_messages = [] + match = 0 + # validate data type: Known + if not isinstance(v, Known): + error_messages.append(f"Error! Input type `{type(v)}` is not `Known`") + else: + match += 1 + # validate data type: Other + if not isinstance(v, Other): + error_messages.append(f"Error! Input type `{type(v)}` is not `Other`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + instance = cls.model_construct() + error_messages = [] + match = 0 + + # deserialize data into Known + try: + instance.actual_instance = Known.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into Other + try: + instance.actual_instance = Other.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> Optional[Union[Dict[str, Any], Known, Other]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.model_dump()) + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/test/test_known.py b/samples/openapi3/client/petstore/python-aiohttp/test/test_known.py new file mode 100644 index 000000000000..2754cd498854 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/test/test_known.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from petstore_api.models.known import Known + +class TestKnown(unittest.TestCase): + """Known unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Known: + """Test Known + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `Known` + """ + model = Known() + if include_optional: + return Known( + kind = 'known' + ) + else: + return Known( + kind = 'known', + ) + """ + + def testKnown(self): + """Test Known""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-aiohttp/test/test_other.py b/samples/openapi3/client/petstore/python-aiohttp/test/test_other.py new file mode 100644 index 000000000000..293c4e281d57 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/test/test_other.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from petstore_api.models.other import Other + +class TestOther(unittest.TestCase): + """Other unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Other: + """Test Other + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `Other` + """ + model = Other() + if include_optional: + return Other( + kind = '' + ) + else: + return Other( + kind = '', + ) + """ + + def testOther(self): + """Test Other""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-aiohttp/test/test_tagged_union.py b/samples/openapi3/client/petstore/python-aiohttp/test/test_tagged_union.py new file mode 100644 index 000000000000..327181f5c429 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/test/test_tagged_union.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from petstore_api.models.tagged_union import TaggedUnion + +class TestTaggedUnion(unittest.TestCase): + """TaggedUnion unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TaggedUnion: + """Test TaggedUnion + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `TaggedUnion` + """ + model = TaggedUnion() + if include_optional: + return TaggedUnion( + kind = '' + ) + else: + return TaggedUnion( + kind = '', + ) + """ + + def testTaggedUnion(self): + """Test TaggedUnion""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-httpx-sync/.openapi-generator/FILES b/samples/openapi3/client/petstore/python-httpx-sync/.openapi-generator/FILES index 4ced57aeb32e..555dd32c6fed 100644 --- a/samples/openapi3/client/petstore/python-httpx-sync/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python-httpx-sync/.openapi-generator/FILES @@ -65,6 +65,7 @@ docs/Info.md docs/InnerDictWithProperty.md docs/InputAllOf.md docs/IntOrString.md +docs/Known.md docs/ListClass.md docs/MapOfArrayOfModel.md docs/MapTest.md @@ -82,6 +83,7 @@ docs/ObjectToTestAdditionalProperties.md docs/ObjectWithDeprecatedFields.md docs/OneOfEnumString.md docs/Order.md +docs/Other.md docs/OuterComposite.md docs/OuterEnum.md docs/OuterEnumDefaultValue.md @@ -108,6 +110,7 @@ docs/SpecialModelName.md docs/SpecialName.md docs/StoreApi.md docs/Tag.md +docs/TaggedUnion.md docs/Task.md docs/TaskActivity.md docs/TestEnum.md @@ -199,6 +202,7 @@ petstore_api/models/info.py petstore_api/models/inner_dict_with_property.py petstore_api/models/input_all_of.py petstore_api/models/int_or_string.py +petstore_api/models/known.py petstore_api/models/list_class.py petstore_api/models/map_of_array_of_model.py petstore_api/models/map_test.py @@ -216,6 +220,7 @@ petstore_api/models/object_to_test_additional_properties.py petstore_api/models/object_with_deprecated_fields.py petstore_api/models/one_of_enum_string.py petstore_api/models/order.py +petstore_api/models/other.py petstore_api/models/outer_composite.py petstore_api/models/outer_enum.py petstore_api/models/outer_enum_default_value.py @@ -240,6 +245,7 @@ petstore_api/models/special_character_enum.py petstore_api/models/special_model_name.py petstore_api/models/special_name.py petstore_api/models/tag.py +petstore_api/models/tagged_union.py petstore_api/models/task.py petstore_api/models/task_activity.py petstore_api/models/test_enum.py diff --git a/samples/openapi3/client/petstore/python-httpx-sync/README.md b/samples/openapi3/client/petstore/python-httpx-sync/README.md index 5ac850a385de..88e6ac7b317b 100644 --- a/samples/openapi3/client/petstore/python-httpx-sync/README.md +++ b/samples/openapi3/client/petstore/python-httpx-sync/README.md @@ -214,6 +214,7 @@ Class | Method | HTTP request | Description - [InnerDictWithProperty](docs/InnerDictWithProperty.md) - [InputAllOf](docs/InputAllOf.md) - [IntOrString](docs/IntOrString.md) + - [Known](docs/Known.md) - [ListClass](docs/ListClass.md) - [MapOfArrayOfModel](docs/MapOfArrayOfModel.md) - [MapTest](docs/MapTest.md) @@ -231,6 +232,7 @@ Class | Method | HTTP request | Description - [ObjectWithDeprecatedFields](docs/ObjectWithDeprecatedFields.md) - [OneOfEnumString](docs/OneOfEnumString.md) - [Order](docs/Order.md) + - [Other](docs/Other.md) - [OuterComposite](docs/OuterComposite.md) - [OuterEnum](docs/OuterEnum.md) - [OuterEnumDefaultValue](docs/OuterEnumDefaultValue.md) @@ -255,6 +257,7 @@ Class | Method | HTTP request | Description - [SpecialModelName](docs/SpecialModelName.md) - [SpecialName](docs/SpecialName.md) - [Tag](docs/Tag.md) + - [TaggedUnion](docs/TaggedUnion.md) - [Task](docs/Task.md) - [TaskActivity](docs/TaskActivity.md) - [TestEnum](docs/TestEnum.md) diff --git a/samples/openapi3/client/petstore/python-httpx-sync/docs/Known.md b/samples/openapi3/client/petstore/python-httpx-sync/docs/Known.md new file mode 100644 index 000000000000..fba8453dcd02 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx-sync/docs/Known.md @@ -0,0 +1,29 @@ +# Known + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **str** | | + +## Example + +```python +from petstore_api.models.known import Known + +# TODO update the JSON string below +json = "{}" +# create an instance of Known from a JSON string +known_instance = Known.from_json(json) +# print the JSON string representation of the object +print(Known.to_json()) + +# convert the object into a dict +known_dict = known_instance.to_dict() +# create an instance of Known from a dict +known_from_dict = Known.from_dict(known_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-httpx-sync/docs/Other.md b/samples/openapi3/client/petstore/python-httpx-sync/docs/Other.md new file mode 100644 index 000000000000..972767b30e1d --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx-sync/docs/Other.md @@ -0,0 +1,29 @@ +# Other + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **str** | | + +## Example + +```python +from petstore_api.models.other import Other + +# TODO update the JSON string below +json = "{}" +# create an instance of Other from a JSON string +other_instance = Other.from_json(json) +# print the JSON string representation of the object +print(Other.to_json()) + +# convert the object into a dict +other_dict = other_instance.to_dict() +# create an instance of Other from a dict +other_from_dict = Other.from_dict(other_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-httpx-sync/docs/TaggedUnion.md b/samples/openapi3/client/petstore/python-httpx-sync/docs/TaggedUnion.md new file mode 100644 index 000000000000..fdeed022e4c7 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx-sync/docs/TaggedUnion.md @@ -0,0 +1,29 @@ +# TaggedUnion + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **str** | | + +## Example + +```python +from petstore_api.models.tagged_union import TaggedUnion + +# TODO update the JSON string below +json = "{}" +# create an instance of TaggedUnion from a JSON string +tagged_union_instance = TaggedUnion.from_json(json) +# print the JSON string representation of the object +print(TaggedUnion.to_json()) + +# convert the object into a dict +tagged_union_dict = tagged_union_instance.to_dict() +# create an instance of TaggedUnion from a dict +tagged_union_from_dict = TaggedUnion.from_dict(tagged_union_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/__init__.py b/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/__init__.py index 55be0097b9d0..051197ea04f4 100644 --- a/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/__init__.py +++ b/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/__init__.py @@ -93,6 +93,7 @@ "InnerDictWithProperty", "InputAllOf", "IntOrString", + "Known", "ListClass", "MapOfArrayOfModel", "MapTest", @@ -110,6 +111,7 @@ "ObjectWithDeprecatedFields", "OneOfEnumString", "Order", + "Other", "OuterComposite", "OuterEnum", "OuterEnumDefaultValue", @@ -134,6 +136,7 @@ "SpecialModelName", "SpecialName", "Tag", + "TaggedUnion", "Task", "TaskActivity", "TestEnum", @@ -233,6 +236,7 @@ from petstore_api.models.inner_dict_with_property import InnerDictWithProperty as InnerDictWithProperty from petstore_api.models.input_all_of import InputAllOf as InputAllOf from petstore_api.models.int_or_string import IntOrString as IntOrString +from petstore_api.models.known import Known as Known from petstore_api.models.list_class import ListClass as ListClass from petstore_api.models.map_of_array_of_model import MapOfArrayOfModel as MapOfArrayOfModel from petstore_api.models.map_test import MapTest as MapTest @@ -250,6 +254,7 @@ from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields as ObjectWithDeprecatedFields from petstore_api.models.one_of_enum_string import OneOfEnumString as OneOfEnumString from petstore_api.models.order import Order as Order +from petstore_api.models.other import Other as Other from petstore_api.models.outer_composite import OuterComposite as OuterComposite from petstore_api.models.outer_enum import OuterEnum as OuterEnum from petstore_api.models.outer_enum_default_value import OuterEnumDefaultValue as OuterEnumDefaultValue @@ -274,6 +279,7 @@ from petstore_api.models.special_model_name import SpecialModelName as SpecialModelName from petstore_api.models.special_name import SpecialName as SpecialName from petstore_api.models.tag import Tag as Tag +from petstore_api.models.tagged_union import TaggedUnion as TaggedUnion from petstore_api.models.task import Task as Task from petstore_api.models.task_activity import TaskActivity as TaskActivity from petstore_api.models.test_enum import TestEnum as TestEnum diff --git a/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/__init__.py b/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/__init__.py index 488a82150d32..662ae4a8325d 100644 --- a/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/__init__.py +++ b/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/__init__.py @@ -70,6 +70,7 @@ from petstore_api.models.inner_dict_with_property import InnerDictWithProperty from petstore_api.models.input_all_of import InputAllOf from petstore_api.models.int_or_string import IntOrString +from petstore_api.models.known import Known from petstore_api.models.list_class import ListClass from petstore_api.models.map_of_array_of_model import MapOfArrayOfModel from petstore_api.models.map_test import MapTest @@ -87,6 +88,7 @@ from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields from petstore_api.models.one_of_enum_string import OneOfEnumString from petstore_api.models.order import Order +from petstore_api.models.other import Other from petstore_api.models.outer_composite import OuterComposite from petstore_api.models.outer_enum import OuterEnum from petstore_api.models.outer_enum_default_value import OuterEnumDefaultValue @@ -111,6 +113,7 @@ from petstore_api.models.special_model_name import SpecialModelName from petstore_api.models.special_name import SpecialName from petstore_api.models.tag import Tag +from petstore_api.models.tagged_union import TaggedUnion from petstore_api.models.task import Task from petstore_api.models.task_activity import TaskActivity from petstore_api.models.test_enum import TestEnum diff --git a/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/known.py b/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/known.py new file mode 100644 index 000000000000..daf64e57b96d --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/known.py @@ -0,0 +1,95 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class Known(BaseModel): + """ + Known + """ # noqa: E501 + kind: StrictStr + __properties: ClassVar[List[str]] = ["kind"] + + @field_validator('kind') + def kind_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['known']): + raise ValueError("must be one of enum values ('known')") + return value + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Known from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Known from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "kind": obj.get("kind") + }) + return _obj + + diff --git a/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/other.py b/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/other.py new file mode 100644 index 000000000000..2f8d6ca1a282 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/other.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class Other(BaseModel): + """ + Other + """ # noqa: E501 + kind: StrictStr + __properties: ClassVar[List[str]] = ["kind"] + @field_validator('kind') + def kind_validate_not_enum(cls, value): + """Validates values excluded by not""" + if value in set(["known", "reserved"]): + raise ValueError("must not be one of excluded enum values") + return value + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Other from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Other from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "kind": obj.get("kind") + }) + return _obj + + diff --git a/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/tagged_union.py b/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/tagged_union.py new file mode 100644 index 000000000000..2930dd983976 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/tagged_union.py @@ -0,0 +1,137 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +import pprint +from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional +from petstore_api.models.known import Known +from petstore_api.models.other import Other +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self + +TAGGEDUNION_ONE_OF_SCHEMAS = ["Known", "Other"] + +class TaggedUnion(BaseModel): + """ + TaggedUnion + """ + # data type: Known + oneof_schema_1_validator: Optional[Known] = None + # data type: Other + oneof_schema_2_validator: Optional[Other] = None + actual_instance: Optional[Union[Known, Other]] = None + one_of_schemas: Set[str] = { "Known", "Other" } + + model_config = ConfigDict( + validate_assignment=True, + protected_namespaces=(), + ) + + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @field_validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = TaggedUnion.model_construct() + error_messages = [] + match = 0 + # validate data type: Known + if not isinstance(v, Known): + error_messages.append(f"Error! Input type `{type(v)}` is not `Known`") + else: + match += 1 + # validate data type: Other + if not isinstance(v, Other): + error_messages.append(f"Error! Input type `{type(v)}` is not `Other`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + instance = cls.model_construct() + error_messages = [] + match = 0 + + # deserialize data into Known + try: + instance.actual_instance = Known.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into Other + try: + instance.actual_instance = Other.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> Optional[Union[Dict[str, Any], Known, Other]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.model_dump()) + + diff --git a/samples/openapi3/client/petstore/python-httpx-sync/test/test_known.py b/samples/openapi3/client/petstore/python-httpx-sync/test/test_known.py new file mode 100644 index 000000000000..2754cd498854 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx-sync/test/test_known.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from petstore_api.models.known import Known + +class TestKnown(unittest.TestCase): + """Known unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Known: + """Test Known + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `Known` + """ + model = Known() + if include_optional: + return Known( + kind = 'known' + ) + else: + return Known( + kind = 'known', + ) + """ + + def testKnown(self): + """Test Known""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-httpx-sync/test/test_other.py b/samples/openapi3/client/petstore/python-httpx-sync/test/test_other.py new file mode 100644 index 000000000000..293c4e281d57 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx-sync/test/test_other.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from petstore_api.models.other import Other + +class TestOther(unittest.TestCase): + """Other unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Other: + """Test Other + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `Other` + """ + model = Other() + if include_optional: + return Other( + kind = '' + ) + else: + return Other( + kind = '', + ) + """ + + def testOther(self): + """Test Other""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-httpx-sync/test/test_tagged_union.py b/samples/openapi3/client/petstore/python-httpx-sync/test/test_tagged_union.py new file mode 100644 index 000000000000..327181f5c429 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx-sync/test/test_tagged_union.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from petstore_api.models.tagged_union import TaggedUnion + +class TestTaggedUnion(unittest.TestCase): + """TaggedUnion unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TaggedUnion: + """Test TaggedUnion + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `TaggedUnion` + """ + model = TaggedUnion() + if include_optional: + return TaggedUnion( + kind = '' + ) + else: + return TaggedUnion( + kind = '', + ) + """ + + def testTaggedUnion(self): + """Test TaggedUnion""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-httpx/.openapi-generator/FILES b/samples/openapi3/client/petstore/python-httpx/.openapi-generator/FILES index d808742215cb..b41f3bc2bf8f 100644 --- a/samples/openapi3/client/petstore/python-httpx/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python-httpx/.openapi-generator/FILES @@ -65,6 +65,7 @@ docs/Info.md docs/InnerDictWithProperty.md docs/InputAllOf.md docs/IntOrString.md +docs/Known.md docs/ListClass.md docs/MapOfArrayOfModel.md docs/MapTest.md @@ -82,6 +83,7 @@ docs/ObjectToTestAdditionalProperties.md docs/ObjectWithDeprecatedFields.md docs/OneOfEnumString.md docs/Order.md +docs/Other.md docs/OuterComposite.md docs/OuterEnum.md docs/OuterEnumDefaultValue.md @@ -108,6 +110,7 @@ docs/SpecialModelName.md docs/SpecialName.md docs/StoreApi.md docs/Tag.md +docs/TaggedUnion.md docs/Task.md docs/TaskActivity.md docs/TestEnum.md @@ -199,6 +202,7 @@ petstore_api/models/info.py petstore_api/models/inner_dict_with_property.py petstore_api/models/input_all_of.py petstore_api/models/int_or_string.py +petstore_api/models/known.py petstore_api/models/list_class.py petstore_api/models/map_of_array_of_model.py petstore_api/models/map_test.py @@ -216,6 +220,7 @@ petstore_api/models/object_to_test_additional_properties.py petstore_api/models/object_with_deprecated_fields.py petstore_api/models/one_of_enum_string.py petstore_api/models/order.py +petstore_api/models/other.py petstore_api/models/outer_composite.py petstore_api/models/outer_enum.py petstore_api/models/outer_enum_default_value.py @@ -240,6 +245,7 @@ petstore_api/models/special_character_enum.py petstore_api/models/special_model_name.py petstore_api/models/special_name.py petstore_api/models/tag.py +petstore_api/models/tagged_union.py petstore_api/models/task.py petstore_api/models/task_activity.py petstore_api/models/test_enum.py diff --git a/samples/openapi3/client/petstore/python-httpx/README.md b/samples/openapi3/client/petstore/python-httpx/README.md index 5ac850a385de..88e6ac7b317b 100644 --- a/samples/openapi3/client/petstore/python-httpx/README.md +++ b/samples/openapi3/client/petstore/python-httpx/README.md @@ -214,6 +214,7 @@ Class | Method | HTTP request | Description - [InnerDictWithProperty](docs/InnerDictWithProperty.md) - [InputAllOf](docs/InputAllOf.md) - [IntOrString](docs/IntOrString.md) + - [Known](docs/Known.md) - [ListClass](docs/ListClass.md) - [MapOfArrayOfModel](docs/MapOfArrayOfModel.md) - [MapTest](docs/MapTest.md) @@ -231,6 +232,7 @@ Class | Method | HTTP request | Description - [ObjectWithDeprecatedFields](docs/ObjectWithDeprecatedFields.md) - [OneOfEnumString](docs/OneOfEnumString.md) - [Order](docs/Order.md) + - [Other](docs/Other.md) - [OuterComposite](docs/OuterComposite.md) - [OuterEnum](docs/OuterEnum.md) - [OuterEnumDefaultValue](docs/OuterEnumDefaultValue.md) @@ -255,6 +257,7 @@ Class | Method | HTTP request | Description - [SpecialModelName](docs/SpecialModelName.md) - [SpecialName](docs/SpecialName.md) - [Tag](docs/Tag.md) + - [TaggedUnion](docs/TaggedUnion.md) - [Task](docs/Task.md) - [TaskActivity](docs/TaskActivity.md) - [TestEnum](docs/TestEnum.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/Known.md b/samples/openapi3/client/petstore/python-httpx/docs/Known.md new file mode 100644 index 000000000000..fba8453dcd02 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx/docs/Known.md @@ -0,0 +1,29 @@ +# Known + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **str** | | + +## Example + +```python +from petstore_api.models.known import Known + +# TODO update the JSON string below +json = "{}" +# create an instance of Known from a JSON string +known_instance = Known.from_json(json) +# print the JSON string representation of the object +print(Known.to_json()) + +# convert the object into a dict +known_dict = known_instance.to_dict() +# create an instance of Known from a dict +known_from_dict = Known.from_dict(known_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-httpx/docs/Other.md b/samples/openapi3/client/petstore/python-httpx/docs/Other.md new file mode 100644 index 000000000000..972767b30e1d --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx/docs/Other.md @@ -0,0 +1,29 @@ +# Other + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **str** | | + +## Example + +```python +from petstore_api.models.other import Other + +# TODO update the JSON string below +json = "{}" +# create an instance of Other from a JSON string +other_instance = Other.from_json(json) +# print the JSON string representation of the object +print(Other.to_json()) + +# convert the object into a dict +other_dict = other_instance.to_dict() +# create an instance of Other from a dict +other_from_dict = Other.from_dict(other_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-httpx/docs/TaggedUnion.md b/samples/openapi3/client/petstore/python-httpx/docs/TaggedUnion.md new file mode 100644 index 000000000000..fdeed022e4c7 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx/docs/TaggedUnion.md @@ -0,0 +1,29 @@ +# TaggedUnion + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **str** | | + +## Example + +```python +from petstore_api.models.tagged_union import TaggedUnion + +# TODO update the JSON string below +json = "{}" +# create an instance of TaggedUnion from a JSON string +tagged_union_instance = TaggedUnion.from_json(json) +# print the JSON string representation of the object +print(TaggedUnion.to_json()) + +# convert the object into a dict +tagged_union_dict = tagged_union_instance.to_dict() +# create an instance of TaggedUnion from a dict +tagged_union_from_dict = TaggedUnion.from_dict(tagged_union_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/__init__.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/__init__.py index 55be0097b9d0..051197ea04f4 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/__init__.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/__init__.py @@ -93,6 +93,7 @@ "InnerDictWithProperty", "InputAllOf", "IntOrString", + "Known", "ListClass", "MapOfArrayOfModel", "MapTest", @@ -110,6 +111,7 @@ "ObjectWithDeprecatedFields", "OneOfEnumString", "Order", + "Other", "OuterComposite", "OuterEnum", "OuterEnumDefaultValue", @@ -134,6 +136,7 @@ "SpecialModelName", "SpecialName", "Tag", + "TaggedUnion", "Task", "TaskActivity", "TestEnum", @@ -233,6 +236,7 @@ from petstore_api.models.inner_dict_with_property import InnerDictWithProperty as InnerDictWithProperty from petstore_api.models.input_all_of import InputAllOf as InputAllOf from petstore_api.models.int_or_string import IntOrString as IntOrString +from petstore_api.models.known import Known as Known from petstore_api.models.list_class import ListClass as ListClass from petstore_api.models.map_of_array_of_model import MapOfArrayOfModel as MapOfArrayOfModel from petstore_api.models.map_test import MapTest as MapTest @@ -250,6 +254,7 @@ from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields as ObjectWithDeprecatedFields from petstore_api.models.one_of_enum_string import OneOfEnumString as OneOfEnumString from petstore_api.models.order import Order as Order +from petstore_api.models.other import Other as Other from petstore_api.models.outer_composite import OuterComposite as OuterComposite from petstore_api.models.outer_enum import OuterEnum as OuterEnum from petstore_api.models.outer_enum_default_value import OuterEnumDefaultValue as OuterEnumDefaultValue @@ -274,6 +279,7 @@ from petstore_api.models.special_model_name import SpecialModelName as SpecialModelName from petstore_api.models.special_name import SpecialName as SpecialName from petstore_api.models.tag import Tag as Tag +from petstore_api.models.tagged_union import TaggedUnion as TaggedUnion from petstore_api.models.task import Task as Task from petstore_api.models.task_activity import TaskActivity as TaskActivity from petstore_api.models.test_enum import TestEnum as TestEnum diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/__init__.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/__init__.py index 488a82150d32..662ae4a8325d 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/__init__.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/__init__.py @@ -70,6 +70,7 @@ from petstore_api.models.inner_dict_with_property import InnerDictWithProperty from petstore_api.models.input_all_of import InputAllOf from petstore_api.models.int_or_string import IntOrString +from petstore_api.models.known import Known from petstore_api.models.list_class import ListClass from petstore_api.models.map_of_array_of_model import MapOfArrayOfModel from petstore_api.models.map_test import MapTest @@ -87,6 +88,7 @@ from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields from petstore_api.models.one_of_enum_string import OneOfEnumString from petstore_api.models.order import Order +from petstore_api.models.other import Other from petstore_api.models.outer_composite import OuterComposite from petstore_api.models.outer_enum import OuterEnum from petstore_api.models.outer_enum_default_value import OuterEnumDefaultValue @@ -111,6 +113,7 @@ from petstore_api.models.special_model_name import SpecialModelName from petstore_api.models.special_name import SpecialName from petstore_api.models.tag import Tag +from petstore_api.models.tagged_union import TaggedUnion from petstore_api.models.task import Task from petstore_api.models.task_activity import TaskActivity from petstore_api.models.test_enum import TestEnum diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/known.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/known.py new file mode 100644 index 000000000000..daf64e57b96d --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/known.py @@ -0,0 +1,95 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class Known(BaseModel): + """ + Known + """ # noqa: E501 + kind: StrictStr + __properties: ClassVar[List[str]] = ["kind"] + + @field_validator('kind') + def kind_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['known']): + raise ValueError("must be one of enum values ('known')") + return value + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Known from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Known from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "kind": obj.get("kind") + }) + return _obj + + diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/other.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/other.py new file mode 100644 index 000000000000..2f8d6ca1a282 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/other.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class Other(BaseModel): + """ + Other + """ # noqa: E501 + kind: StrictStr + __properties: ClassVar[List[str]] = ["kind"] + @field_validator('kind') + def kind_validate_not_enum(cls, value): + """Validates values excluded by not""" + if value in set(["known", "reserved"]): + raise ValueError("must not be one of excluded enum values") + return value + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Other from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Other from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "kind": obj.get("kind") + }) + return _obj + + diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/tagged_union.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/tagged_union.py new file mode 100644 index 000000000000..2930dd983976 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/tagged_union.py @@ -0,0 +1,137 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +import pprint +from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional +from petstore_api.models.known import Known +from petstore_api.models.other import Other +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self + +TAGGEDUNION_ONE_OF_SCHEMAS = ["Known", "Other"] + +class TaggedUnion(BaseModel): + """ + TaggedUnion + """ + # data type: Known + oneof_schema_1_validator: Optional[Known] = None + # data type: Other + oneof_schema_2_validator: Optional[Other] = None + actual_instance: Optional[Union[Known, Other]] = None + one_of_schemas: Set[str] = { "Known", "Other" } + + model_config = ConfigDict( + validate_assignment=True, + protected_namespaces=(), + ) + + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @field_validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = TaggedUnion.model_construct() + error_messages = [] + match = 0 + # validate data type: Known + if not isinstance(v, Known): + error_messages.append(f"Error! Input type `{type(v)}` is not `Known`") + else: + match += 1 + # validate data type: Other + if not isinstance(v, Other): + error_messages.append(f"Error! Input type `{type(v)}` is not `Other`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + instance = cls.model_construct() + error_messages = [] + match = 0 + + # deserialize data into Known + try: + instance.actual_instance = Known.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into Other + try: + instance.actual_instance = Other.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> Optional[Union[Dict[str, Any], Known, Other]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.model_dump()) + + diff --git a/samples/openapi3/client/petstore/python-httpx/test/test_known.py b/samples/openapi3/client/petstore/python-httpx/test/test_known.py new file mode 100644 index 000000000000..2754cd498854 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx/test/test_known.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from petstore_api.models.known import Known + +class TestKnown(unittest.TestCase): + """Known unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Known: + """Test Known + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `Known` + """ + model = Known() + if include_optional: + return Known( + kind = 'known' + ) + else: + return Known( + kind = 'known', + ) + """ + + def testKnown(self): + """Test Known""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-httpx/test/test_other.py b/samples/openapi3/client/petstore/python-httpx/test/test_other.py new file mode 100644 index 000000000000..293c4e281d57 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx/test/test_other.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from petstore_api.models.other import Other + +class TestOther(unittest.TestCase): + """Other unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Other: + """Test Other + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `Other` + """ + model = Other() + if include_optional: + return Other( + kind = '' + ) + else: + return Other( + kind = '', + ) + """ + + def testOther(self): + """Test Other""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-httpx/test/test_tagged_union.py b/samples/openapi3/client/petstore/python-httpx/test/test_tagged_union.py new file mode 100644 index 000000000000..327181f5c429 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx/test/test_tagged_union.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from petstore_api.models.tagged_union import TaggedUnion + +class TestTaggedUnion(unittest.TestCase): + """TaggedUnion unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TaggedUnion: + """Test TaggedUnion + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `TaggedUnion` + """ + model = TaggedUnion() + if include_optional: + return TaggedUnion( + kind = '' + ) + else: + return TaggedUnion( + kind = '', + ) + """ + + def testTaggedUnion(self): + """Test TaggedUnion""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-httpx2-sync/.openapi-generator/FILES b/samples/openapi3/client/petstore/python-httpx2-sync/.openapi-generator/FILES index 4ced57aeb32e..555dd32c6fed 100644 --- a/samples/openapi3/client/petstore/python-httpx2-sync/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python-httpx2-sync/.openapi-generator/FILES @@ -65,6 +65,7 @@ docs/Info.md docs/InnerDictWithProperty.md docs/InputAllOf.md docs/IntOrString.md +docs/Known.md docs/ListClass.md docs/MapOfArrayOfModel.md docs/MapTest.md @@ -82,6 +83,7 @@ docs/ObjectToTestAdditionalProperties.md docs/ObjectWithDeprecatedFields.md docs/OneOfEnumString.md docs/Order.md +docs/Other.md docs/OuterComposite.md docs/OuterEnum.md docs/OuterEnumDefaultValue.md @@ -108,6 +110,7 @@ docs/SpecialModelName.md docs/SpecialName.md docs/StoreApi.md docs/Tag.md +docs/TaggedUnion.md docs/Task.md docs/TaskActivity.md docs/TestEnum.md @@ -199,6 +202,7 @@ petstore_api/models/info.py petstore_api/models/inner_dict_with_property.py petstore_api/models/input_all_of.py petstore_api/models/int_or_string.py +petstore_api/models/known.py petstore_api/models/list_class.py petstore_api/models/map_of_array_of_model.py petstore_api/models/map_test.py @@ -216,6 +220,7 @@ petstore_api/models/object_to_test_additional_properties.py petstore_api/models/object_with_deprecated_fields.py petstore_api/models/one_of_enum_string.py petstore_api/models/order.py +petstore_api/models/other.py petstore_api/models/outer_composite.py petstore_api/models/outer_enum.py petstore_api/models/outer_enum_default_value.py @@ -240,6 +245,7 @@ petstore_api/models/special_character_enum.py petstore_api/models/special_model_name.py petstore_api/models/special_name.py petstore_api/models/tag.py +petstore_api/models/tagged_union.py petstore_api/models/task.py petstore_api/models/task_activity.py petstore_api/models/test_enum.py diff --git a/samples/openapi3/client/petstore/python-httpx2-sync/README.md b/samples/openapi3/client/petstore/python-httpx2-sync/README.md index b288de0bcfec..3cc4672935b6 100644 --- a/samples/openapi3/client/petstore/python-httpx2-sync/README.md +++ b/samples/openapi3/client/petstore/python-httpx2-sync/README.md @@ -217,6 +217,7 @@ Class | Method | HTTP request | Description - [InnerDictWithProperty](docs/InnerDictWithProperty.md) - [InputAllOf](docs/InputAllOf.md) - [IntOrString](docs/IntOrString.md) + - [Known](docs/Known.md) - [ListClass](docs/ListClass.md) - [MapOfArrayOfModel](docs/MapOfArrayOfModel.md) - [MapTest](docs/MapTest.md) @@ -234,6 +235,7 @@ Class | Method | HTTP request | Description - [ObjectWithDeprecatedFields](docs/ObjectWithDeprecatedFields.md) - [OneOfEnumString](docs/OneOfEnumString.md) - [Order](docs/Order.md) + - [Other](docs/Other.md) - [OuterComposite](docs/OuterComposite.md) - [OuterEnum](docs/OuterEnum.md) - [OuterEnumDefaultValue](docs/OuterEnumDefaultValue.md) @@ -258,6 +260,7 @@ Class | Method | HTTP request | Description - [SpecialModelName](docs/SpecialModelName.md) - [SpecialName](docs/SpecialName.md) - [Tag](docs/Tag.md) + - [TaggedUnion](docs/TaggedUnion.md) - [Task](docs/Task.md) - [TaskActivity](docs/TaskActivity.md) - [TestEnum](docs/TestEnum.md) diff --git a/samples/openapi3/client/petstore/python-httpx2-sync/docs/Known.md b/samples/openapi3/client/petstore/python-httpx2-sync/docs/Known.md new file mode 100644 index 000000000000..fba8453dcd02 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2-sync/docs/Known.md @@ -0,0 +1,29 @@ +# Known + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **str** | | + +## Example + +```python +from petstore_api.models.known import Known + +# TODO update the JSON string below +json = "{}" +# create an instance of Known from a JSON string +known_instance = Known.from_json(json) +# print the JSON string representation of the object +print(Known.to_json()) + +# convert the object into a dict +known_dict = known_instance.to_dict() +# create an instance of Known from a dict +known_from_dict = Known.from_dict(known_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-httpx2-sync/docs/Other.md b/samples/openapi3/client/petstore/python-httpx2-sync/docs/Other.md new file mode 100644 index 000000000000..972767b30e1d --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2-sync/docs/Other.md @@ -0,0 +1,29 @@ +# Other + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **str** | | + +## Example + +```python +from petstore_api.models.other import Other + +# TODO update the JSON string below +json = "{}" +# create an instance of Other from a JSON string +other_instance = Other.from_json(json) +# print the JSON string representation of the object +print(Other.to_json()) + +# convert the object into a dict +other_dict = other_instance.to_dict() +# create an instance of Other from a dict +other_from_dict = Other.from_dict(other_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-httpx2-sync/docs/TaggedUnion.md b/samples/openapi3/client/petstore/python-httpx2-sync/docs/TaggedUnion.md new file mode 100644 index 000000000000..fdeed022e4c7 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2-sync/docs/TaggedUnion.md @@ -0,0 +1,29 @@ +# TaggedUnion + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **str** | | + +## Example + +```python +from petstore_api.models.tagged_union import TaggedUnion + +# TODO update the JSON string below +json = "{}" +# create an instance of TaggedUnion from a JSON string +tagged_union_instance = TaggedUnion.from_json(json) +# print the JSON string representation of the object +print(TaggedUnion.to_json()) + +# convert the object into a dict +tagged_union_dict = tagged_union_instance.to_dict() +# create an instance of TaggedUnion from a dict +tagged_union_from_dict = TaggedUnion.from_dict(tagged_union_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/__init__.py b/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/__init__.py index 55be0097b9d0..051197ea04f4 100644 --- a/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/__init__.py +++ b/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/__init__.py @@ -93,6 +93,7 @@ "InnerDictWithProperty", "InputAllOf", "IntOrString", + "Known", "ListClass", "MapOfArrayOfModel", "MapTest", @@ -110,6 +111,7 @@ "ObjectWithDeprecatedFields", "OneOfEnumString", "Order", + "Other", "OuterComposite", "OuterEnum", "OuterEnumDefaultValue", @@ -134,6 +136,7 @@ "SpecialModelName", "SpecialName", "Tag", + "TaggedUnion", "Task", "TaskActivity", "TestEnum", @@ -233,6 +236,7 @@ from petstore_api.models.inner_dict_with_property import InnerDictWithProperty as InnerDictWithProperty from petstore_api.models.input_all_of import InputAllOf as InputAllOf from petstore_api.models.int_or_string import IntOrString as IntOrString +from petstore_api.models.known import Known as Known from petstore_api.models.list_class import ListClass as ListClass from petstore_api.models.map_of_array_of_model import MapOfArrayOfModel as MapOfArrayOfModel from petstore_api.models.map_test import MapTest as MapTest @@ -250,6 +254,7 @@ from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields as ObjectWithDeprecatedFields from petstore_api.models.one_of_enum_string import OneOfEnumString as OneOfEnumString from petstore_api.models.order import Order as Order +from petstore_api.models.other import Other as Other from petstore_api.models.outer_composite import OuterComposite as OuterComposite from petstore_api.models.outer_enum import OuterEnum as OuterEnum from petstore_api.models.outer_enum_default_value import OuterEnumDefaultValue as OuterEnumDefaultValue @@ -274,6 +279,7 @@ from petstore_api.models.special_model_name import SpecialModelName as SpecialModelName from petstore_api.models.special_name import SpecialName as SpecialName from petstore_api.models.tag import Tag as Tag +from petstore_api.models.tagged_union import TaggedUnion as TaggedUnion from petstore_api.models.task import Task as Task from petstore_api.models.task_activity import TaskActivity as TaskActivity from petstore_api.models.test_enum import TestEnum as TestEnum diff --git a/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/__init__.py b/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/__init__.py index 488a82150d32..662ae4a8325d 100644 --- a/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/__init__.py +++ b/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/__init__.py @@ -70,6 +70,7 @@ from petstore_api.models.inner_dict_with_property import InnerDictWithProperty from petstore_api.models.input_all_of import InputAllOf from petstore_api.models.int_or_string import IntOrString +from petstore_api.models.known import Known from petstore_api.models.list_class import ListClass from petstore_api.models.map_of_array_of_model import MapOfArrayOfModel from petstore_api.models.map_test import MapTest @@ -87,6 +88,7 @@ from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields from petstore_api.models.one_of_enum_string import OneOfEnumString from petstore_api.models.order import Order +from petstore_api.models.other import Other from petstore_api.models.outer_composite import OuterComposite from petstore_api.models.outer_enum import OuterEnum from petstore_api.models.outer_enum_default_value import OuterEnumDefaultValue @@ -111,6 +113,7 @@ from petstore_api.models.special_model_name import SpecialModelName from petstore_api.models.special_name import SpecialName from petstore_api.models.tag import Tag +from petstore_api.models.tagged_union import TaggedUnion from petstore_api.models.task import Task from petstore_api.models.task_activity import TaskActivity from petstore_api.models.test_enum import TestEnum diff --git a/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/known.py b/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/known.py new file mode 100644 index 000000000000..daf64e57b96d --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/known.py @@ -0,0 +1,95 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class Known(BaseModel): + """ + Known + """ # noqa: E501 + kind: StrictStr + __properties: ClassVar[List[str]] = ["kind"] + + @field_validator('kind') + def kind_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['known']): + raise ValueError("must be one of enum values ('known')") + return value + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Known from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Known from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "kind": obj.get("kind") + }) + return _obj + + diff --git a/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/other.py b/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/other.py new file mode 100644 index 000000000000..2f8d6ca1a282 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/other.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class Other(BaseModel): + """ + Other + """ # noqa: E501 + kind: StrictStr + __properties: ClassVar[List[str]] = ["kind"] + @field_validator('kind') + def kind_validate_not_enum(cls, value): + """Validates values excluded by not""" + if value in set(["known", "reserved"]): + raise ValueError("must not be one of excluded enum values") + return value + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Other from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Other from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "kind": obj.get("kind") + }) + return _obj + + diff --git a/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/tagged_union.py b/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/tagged_union.py new file mode 100644 index 000000000000..2930dd983976 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/tagged_union.py @@ -0,0 +1,137 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +import pprint +from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional +from petstore_api.models.known import Known +from petstore_api.models.other import Other +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self + +TAGGEDUNION_ONE_OF_SCHEMAS = ["Known", "Other"] + +class TaggedUnion(BaseModel): + """ + TaggedUnion + """ + # data type: Known + oneof_schema_1_validator: Optional[Known] = None + # data type: Other + oneof_schema_2_validator: Optional[Other] = None + actual_instance: Optional[Union[Known, Other]] = None + one_of_schemas: Set[str] = { "Known", "Other" } + + model_config = ConfigDict( + validate_assignment=True, + protected_namespaces=(), + ) + + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @field_validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = TaggedUnion.model_construct() + error_messages = [] + match = 0 + # validate data type: Known + if not isinstance(v, Known): + error_messages.append(f"Error! Input type `{type(v)}` is not `Known`") + else: + match += 1 + # validate data type: Other + if not isinstance(v, Other): + error_messages.append(f"Error! Input type `{type(v)}` is not `Other`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + instance = cls.model_construct() + error_messages = [] + match = 0 + + # deserialize data into Known + try: + instance.actual_instance = Known.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into Other + try: + instance.actual_instance = Other.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> Optional[Union[Dict[str, Any], Known, Other]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.model_dump()) + + diff --git a/samples/openapi3/client/petstore/python-httpx2-sync/test/test_known.py b/samples/openapi3/client/petstore/python-httpx2-sync/test/test_known.py new file mode 100644 index 000000000000..2754cd498854 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2-sync/test/test_known.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from petstore_api.models.known import Known + +class TestKnown(unittest.TestCase): + """Known unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Known: + """Test Known + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `Known` + """ + model = Known() + if include_optional: + return Known( + kind = 'known' + ) + else: + return Known( + kind = 'known', + ) + """ + + def testKnown(self): + """Test Known""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-httpx2-sync/test/test_other.py b/samples/openapi3/client/petstore/python-httpx2-sync/test/test_other.py new file mode 100644 index 000000000000..293c4e281d57 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2-sync/test/test_other.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from petstore_api.models.other import Other + +class TestOther(unittest.TestCase): + """Other unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Other: + """Test Other + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `Other` + """ + model = Other() + if include_optional: + return Other( + kind = '' + ) + else: + return Other( + kind = '', + ) + """ + + def testOther(self): + """Test Other""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-httpx2-sync/test/test_tagged_union.py b/samples/openapi3/client/petstore/python-httpx2-sync/test/test_tagged_union.py new file mode 100644 index 000000000000..327181f5c429 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2-sync/test/test_tagged_union.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from petstore_api.models.tagged_union import TaggedUnion + +class TestTaggedUnion(unittest.TestCase): + """TaggedUnion unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TaggedUnion: + """Test TaggedUnion + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `TaggedUnion` + """ + model = TaggedUnion() + if include_optional: + return TaggedUnion( + kind = '' + ) + else: + return TaggedUnion( + kind = '', + ) + """ + + def testTaggedUnion(self): + """Test TaggedUnion""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-httpx2/.openapi-generator/FILES b/samples/openapi3/client/petstore/python-httpx2/.openapi-generator/FILES index d808742215cb..b41f3bc2bf8f 100644 --- a/samples/openapi3/client/petstore/python-httpx2/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python-httpx2/.openapi-generator/FILES @@ -65,6 +65,7 @@ docs/Info.md docs/InnerDictWithProperty.md docs/InputAllOf.md docs/IntOrString.md +docs/Known.md docs/ListClass.md docs/MapOfArrayOfModel.md docs/MapTest.md @@ -82,6 +83,7 @@ docs/ObjectToTestAdditionalProperties.md docs/ObjectWithDeprecatedFields.md docs/OneOfEnumString.md docs/Order.md +docs/Other.md docs/OuterComposite.md docs/OuterEnum.md docs/OuterEnumDefaultValue.md @@ -108,6 +110,7 @@ docs/SpecialModelName.md docs/SpecialName.md docs/StoreApi.md docs/Tag.md +docs/TaggedUnion.md docs/Task.md docs/TaskActivity.md docs/TestEnum.md @@ -199,6 +202,7 @@ petstore_api/models/info.py petstore_api/models/inner_dict_with_property.py petstore_api/models/input_all_of.py petstore_api/models/int_or_string.py +petstore_api/models/known.py petstore_api/models/list_class.py petstore_api/models/map_of_array_of_model.py petstore_api/models/map_test.py @@ -216,6 +220,7 @@ petstore_api/models/object_to_test_additional_properties.py petstore_api/models/object_with_deprecated_fields.py petstore_api/models/one_of_enum_string.py petstore_api/models/order.py +petstore_api/models/other.py petstore_api/models/outer_composite.py petstore_api/models/outer_enum.py petstore_api/models/outer_enum_default_value.py @@ -240,6 +245,7 @@ petstore_api/models/special_character_enum.py petstore_api/models/special_model_name.py petstore_api/models/special_name.py petstore_api/models/tag.py +petstore_api/models/tagged_union.py petstore_api/models/task.py petstore_api/models/task_activity.py petstore_api/models/test_enum.py diff --git a/samples/openapi3/client/petstore/python-httpx2/README.md b/samples/openapi3/client/petstore/python-httpx2/README.md index 9652b103ca11..4f1e13737e55 100644 --- a/samples/openapi3/client/petstore/python-httpx2/README.md +++ b/samples/openapi3/client/petstore/python-httpx2/README.md @@ -216,6 +216,7 @@ Class | Method | HTTP request | Description - [InnerDictWithProperty](docs/InnerDictWithProperty.md) - [InputAllOf](docs/InputAllOf.md) - [IntOrString](docs/IntOrString.md) + - [Known](docs/Known.md) - [ListClass](docs/ListClass.md) - [MapOfArrayOfModel](docs/MapOfArrayOfModel.md) - [MapTest](docs/MapTest.md) @@ -233,6 +234,7 @@ Class | Method | HTTP request | Description - [ObjectWithDeprecatedFields](docs/ObjectWithDeprecatedFields.md) - [OneOfEnumString](docs/OneOfEnumString.md) - [Order](docs/Order.md) + - [Other](docs/Other.md) - [OuterComposite](docs/OuterComposite.md) - [OuterEnum](docs/OuterEnum.md) - [OuterEnumDefaultValue](docs/OuterEnumDefaultValue.md) @@ -257,6 +259,7 @@ Class | Method | HTTP request | Description - [SpecialModelName](docs/SpecialModelName.md) - [SpecialName](docs/SpecialName.md) - [Tag](docs/Tag.md) + - [TaggedUnion](docs/TaggedUnion.md) - [Task](docs/Task.md) - [TaskActivity](docs/TaskActivity.md) - [TestEnum](docs/TestEnum.md) diff --git a/samples/openapi3/client/petstore/python-httpx2/docs/Known.md b/samples/openapi3/client/petstore/python-httpx2/docs/Known.md new file mode 100644 index 000000000000..fba8453dcd02 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2/docs/Known.md @@ -0,0 +1,29 @@ +# Known + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **str** | | + +## Example + +```python +from petstore_api.models.known import Known + +# TODO update the JSON string below +json = "{}" +# create an instance of Known from a JSON string +known_instance = Known.from_json(json) +# print the JSON string representation of the object +print(Known.to_json()) + +# convert the object into a dict +known_dict = known_instance.to_dict() +# create an instance of Known from a dict +known_from_dict = Known.from_dict(known_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-httpx2/docs/Other.md b/samples/openapi3/client/petstore/python-httpx2/docs/Other.md new file mode 100644 index 000000000000..972767b30e1d --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2/docs/Other.md @@ -0,0 +1,29 @@ +# Other + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **str** | | + +## Example + +```python +from petstore_api.models.other import Other + +# TODO update the JSON string below +json = "{}" +# create an instance of Other from a JSON string +other_instance = Other.from_json(json) +# print the JSON string representation of the object +print(Other.to_json()) + +# convert the object into a dict +other_dict = other_instance.to_dict() +# create an instance of Other from a dict +other_from_dict = Other.from_dict(other_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-httpx2/docs/TaggedUnion.md b/samples/openapi3/client/petstore/python-httpx2/docs/TaggedUnion.md new file mode 100644 index 000000000000..fdeed022e4c7 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2/docs/TaggedUnion.md @@ -0,0 +1,29 @@ +# TaggedUnion + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **str** | | + +## Example + +```python +from petstore_api.models.tagged_union import TaggedUnion + +# TODO update the JSON string below +json = "{}" +# create an instance of TaggedUnion from a JSON string +tagged_union_instance = TaggedUnion.from_json(json) +# print the JSON string representation of the object +print(TaggedUnion.to_json()) + +# convert the object into a dict +tagged_union_dict = tagged_union_instance.to_dict() +# create an instance of TaggedUnion from a dict +tagged_union_from_dict = TaggedUnion.from_dict(tagged_union_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-httpx2/petstore_api/__init__.py b/samples/openapi3/client/petstore/python-httpx2/petstore_api/__init__.py index 55be0097b9d0..051197ea04f4 100644 --- a/samples/openapi3/client/petstore/python-httpx2/petstore_api/__init__.py +++ b/samples/openapi3/client/petstore/python-httpx2/petstore_api/__init__.py @@ -93,6 +93,7 @@ "InnerDictWithProperty", "InputAllOf", "IntOrString", + "Known", "ListClass", "MapOfArrayOfModel", "MapTest", @@ -110,6 +111,7 @@ "ObjectWithDeprecatedFields", "OneOfEnumString", "Order", + "Other", "OuterComposite", "OuterEnum", "OuterEnumDefaultValue", @@ -134,6 +136,7 @@ "SpecialModelName", "SpecialName", "Tag", + "TaggedUnion", "Task", "TaskActivity", "TestEnum", @@ -233,6 +236,7 @@ from petstore_api.models.inner_dict_with_property import InnerDictWithProperty as InnerDictWithProperty from petstore_api.models.input_all_of import InputAllOf as InputAllOf from petstore_api.models.int_or_string import IntOrString as IntOrString +from petstore_api.models.known import Known as Known from petstore_api.models.list_class import ListClass as ListClass from petstore_api.models.map_of_array_of_model import MapOfArrayOfModel as MapOfArrayOfModel from petstore_api.models.map_test import MapTest as MapTest @@ -250,6 +254,7 @@ from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields as ObjectWithDeprecatedFields from petstore_api.models.one_of_enum_string import OneOfEnumString as OneOfEnumString from petstore_api.models.order import Order as Order +from petstore_api.models.other import Other as Other from petstore_api.models.outer_composite import OuterComposite as OuterComposite from petstore_api.models.outer_enum import OuterEnum as OuterEnum from petstore_api.models.outer_enum_default_value import OuterEnumDefaultValue as OuterEnumDefaultValue @@ -274,6 +279,7 @@ from petstore_api.models.special_model_name import SpecialModelName as SpecialModelName from petstore_api.models.special_name import SpecialName as SpecialName from petstore_api.models.tag import Tag as Tag +from petstore_api.models.tagged_union import TaggedUnion as TaggedUnion from petstore_api.models.task import Task as Task from petstore_api.models.task_activity import TaskActivity as TaskActivity from petstore_api.models.test_enum import TestEnum as TestEnum diff --git a/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/__init__.py b/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/__init__.py index 488a82150d32..662ae4a8325d 100644 --- a/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/__init__.py +++ b/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/__init__.py @@ -70,6 +70,7 @@ from petstore_api.models.inner_dict_with_property import InnerDictWithProperty from petstore_api.models.input_all_of import InputAllOf from petstore_api.models.int_or_string import IntOrString +from petstore_api.models.known import Known from petstore_api.models.list_class import ListClass from petstore_api.models.map_of_array_of_model import MapOfArrayOfModel from petstore_api.models.map_test import MapTest @@ -87,6 +88,7 @@ from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields from petstore_api.models.one_of_enum_string import OneOfEnumString from petstore_api.models.order import Order +from petstore_api.models.other import Other from petstore_api.models.outer_composite import OuterComposite from petstore_api.models.outer_enum import OuterEnum from petstore_api.models.outer_enum_default_value import OuterEnumDefaultValue @@ -111,6 +113,7 @@ from petstore_api.models.special_model_name import SpecialModelName from petstore_api.models.special_name import SpecialName from petstore_api.models.tag import Tag +from petstore_api.models.tagged_union import TaggedUnion from petstore_api.models.task import Task from petstore_api.models.task_activity import TaskActivity from petstore_api.models.test_enum import TestEnum diff --git a/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/known.py b/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/known.py new file mode 100644 index 000000000000..daf64e57b96d --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/known.py @@ -0,0 +1,95 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class Known(BaseModel): + """ + Known + """ # noqa: E501 + kind: StrictStr + __properties: ClassVar[List[str]] = ["kind"] + + @field_validator('kind') + def kind_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['known']): + raise ValueError("must be one of enum values ('known')") + return value + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Known from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Known from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "kind": obj.get("kind") + }) + return _obj + + diff --git a/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/other.py b/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/other.py new file mode 100644 index 000000000000..2f8d6ca1a282 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/other.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class Other(BaseModel): + """ + Other + """ # noqa: E501 + kind: StrictStr + __properties: ClassVar[List[str]] = ["kind"] + @field_validator('kind') + def kind_validate_not_enum(cls, value): + """Validates values excluded by not""" + if value in set(["known", "reserved"]): + raise ValueError("must not be one of excluded enum values") + return value + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Other from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Other from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "kind": obj.get("kind") + }) + return _obj + + diff --git a/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/tagged_union.py b/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/tagged_union.py new file mode 100644 index 000000000000..2930dd983976 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/tagged_union.py @@ -0,0 +1,137 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +import pprint +from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional +from petstore_api.models.known import Known +from petstore_api.models.other import Other +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self + +TAGGEDUNION_ONE_OF_SCHEMAS = ["Known", "Other"] + +class TaggedUnion(BaseModel): + """ + TaggedUnion + """ + # data type: Known + oneof_schema_1_validator: Optional[Known] = None + # data type: Other + oneof_schema_2_validator: Optional[Other] = None + actual_instance: Optional[Union[Known, Other]] = None + one_of_schemas: Set[str] = { "Known", "Other" } + + model_config = ConfigDict( + validate_assignment=True, + protected_namespaces=(), + ) + + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @field_validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = TaggedUnion.model_construct() + error_messages = [] + match = 0 + # validate data type: Known + if not isinstance(v, Known): + error_messages.append(f"Error! Input type `{type(v)}` is not `Known`") + else: + match += 1 + # validate data type: Other + if not isinstance(v, Other): + error_messages.append(f"Error! Input type `{type(v)}` is not `Other`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + instance = cls.model_construct() + error_messages = [] + match = 0 + + # deserialize data into Known + try: + instance.actual_instance = Known.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into Other + try: + instance.actual_instance = Other.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> Optional[Union[Dict[str, Any], Known, Other]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.model_dump()) + + diff --git a/samples/openapi3/client/petstore/python-httpx2/test/test_known.py b/samples/openapi3/client/petstore/python-httpx2/test/test_known.py new file mode 100644 index 000000000000..2754cd498854 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2/test/test_known.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from petstore_api.models.known import Known + +class TestKnown(unittest.TestCase): + """Known unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Known: + """Test Known + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `Known` + """ + model = Known() + if include_optional: + return Known( + kind = 'known' + ) + else: + return Known( + kind = 'known', + ) + """ + + def testKnown(self): + """Test Known""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-httpx2/test/test_other.py b/samples/openapi3/client/petstore/python-httpx2/test/test_other.py new file mode 100644 index 000000000000..293c4e281d57 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2/test/test_other.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from petstore_api.models.other import Other + +class TestOther(unittest.TestCase): + """Other unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Other: + """Test Other + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `Other` + """ + model = Other() + if include_optional: + return Other( + kind = '' + ) + else: + return Other( + kind = '', + ) + """ + + def testOther(self): + """Test Other""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-httpx2/test/test_tagged_union.py b/samples/openapi3/client/petstore/python-httpx2/test/test_tagged_union.py new file mode 100644 index 000000000000..327181f5c429 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2/test/test_tagged_union.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from petstore_api.models.tagged_union import TaggedUnion + +class TestTaggedUnion(unittest.TestCase): + """TaggedUnion unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TaggedUnion: + """Test TaggedUnion + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `TaggedUnion` + """ + model = TaggedUnion() + if include_optional: + return TaggedUnion( + kind = '' + ) + else: + return TaggedUnion( + kind = '', + ) + """ + + def testTaggedUnion(self): + """Test TaggedUnion""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-lazyImports/.openapi-generator/FILES b/samples/openapi3/client/petstore/python-lazyImports/.openapi-generator/FILES index d808742215cb..b41f3bc2bf8f 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python-lazyImports/.openapi-generator/FILES @@ -65,6 +65,7 @@ docs/Info.md docs/InnerDictWithProperty.md docs/InputAllOf.md docs/IntOrString.md +docs/Known.md docs/ListClass.md docs/MapOfArrayOfModel.md docs/MapTest.md @@ -82,6 +83,7 @@ docs/ObjectToTestAdditionalProperties.md docs/ObjectWithDeprecatedFields.md docs/OneOfEnumString.md docs/Order.md +docs/Other.md docs/OuterComposite.md docs/OuterEnum.md docs/OuterEnumDefaultValue.md @@ -108,6 +110,7 @@ docs/SpecialModelName.md docs/SpecialName.md docs/StoreApi.md docs/Tag.md +docs/TaggedUnion.md docs/Task.md docs/TaskActivity.md docs/TestEnum.md @@ -199,6 +202,7 @@ petstore_api/models/info.py petstore_api/models/inner_dict_with_property.py petstore_api/models/input_all_of.py petstore_api/models/int_or_string.py +petstore_api/models/known.py petstore_api/models/list_class.py petstore_api/models/map_of_array_of_model.py petstore_api/models/map_test.py @@ -216,6 +220,7 @@ petstore_api/models/object_to_test_additional_properties.py petstore_api/models/object_with_deprecated_fields.py petstore_api/models/one_of_enum_string.py petstore_api/models/order.py +petstore_api/models/other.py petstore_api/models/outer_composite.py petstore_api/models/outer_enum.py petstore_api/models/outer_enum_default_value.py @@ -240,6 +245,7 @@ petstore_api/models/special_character_enum.py petstore_api/models/special_model_name.py petstore_api/models/special_name.py petstore_api/models/tag.py +petstore_api/models/tagged_union.py petstore_api/models/task.py petstore_api/models/task_activity.py petstore_api/models/test_enum.py diff --git a/samples/openapi3/client/petstore/python-lazyImports/README.md b/samples/openapi3/client/petstore/python-lazyImports/README.md index e25561c194cc..6e2b2ed2b060 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/README.md +++ b/samples/openapi3/client/petstore/python-lazyImports/README.md @@ -237,6 +237,7 @@ Class | Method | HTTP request | Description - [InnerDictWithProperty](docs/InnerDictWithProperty.md) - [InputAllOf](docs/InputAllOf.md) - [IntOrString](docs/IntOrString.md) + - [Known](docs/Known.md) - [ListClass](docs/ListClass.md) - [MapOfArrayOfModel](docs/MapOfArrayOfModel.md) - [MapTest](docs/MapTest.md) @@ -254,6 +255,7 @@ Class | Method | HTTP request | Description - [ObjectWithDeprecatedFields](docs/ObjectWithDeprecatedFields.md) - [OneOfEnumString](docs/OneOfEnumString.md) - [Order](docs/Order.md) + - [Other](docs/Other.md) - [OuterComposite](docs/OuterComposite.md) - [OuterEnum](docs/OuterEnum.md) - [OuterEnumDefaultValue](docs/OuterEnumDefaultValue.md) @@ -278,6 +280,7 @@ Class | Method | HTTP request | Description - [SpecialModelName](docs/SpecialModelName.md) - [SpecialName](docs/SpecialName.md) - [Tag](docs/Tag.md) + - [TaggedUnion](docs/TaggedUnion.md) - [Task](docs/Task.md) - [TaskActivity](docs/TaskActivity.md) - [TestEnum](docs/TestEnum.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/Known.md b/samples/openapi3/client/petstore/python-lazyImports/docs/Known.md new file mode 100644 index 000000000000..fba8453dcd02 --- /dev/null +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/Known.md @@ -0,0 +1,29 @@ +# Known + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **str** | | + +## Example + +```python +from petstore_api.models.known import Known + +# TODO update the JSON string below +json = "{}" +# create an instance of Known from a JSON string +known_instance = Known.from_json(json) +# print the JSON string representation of the object +print(Known.to_json()) + +# convert the object into a dict +known_dict = known_instance.to_dict() +# create an instance of Known from a dict +known_from_dict = Known.from_dict(known_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/Other.md b/samples/openapi3/client/petstore/python-lazyImports/docs/Other.md new file mode 100644 index 000000000000..972767b30e1d --- /dev/null +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/Other.md @@ -0,0 +1,29 @@ +# Other + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **str** | | + +## Example + +```python +from petstore_api.models.other import Other + +# TODO update the JSON string below +json = "{}" +# create an instance of Other from a JSON string +other_instance = Other.from_json(json) +# print the JSON string representation of the object +print(Other.to_json()) + +# convert the object into a dict +other_dict = other_instance.to_dict() +# create an instance of Other from a dict +other_from_dict = Other.from_dict(other_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/TaggedUnion.md b/samples/openapi3/client/petstore/python-lazyImports/docs/TaggedUnion.md new file mode 100644 index 000000000000..fdeed022e4c7 --- /dev/null +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/TaggedUnion.md @@ -0,0 +1,29 @@ +# TaggedUnion + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **str** | | + +## Example + +```python +from petstore_api.models.tagged_union import TaggedUnion + +# TODO update the JSON string below +json = "{}" +# create an instance of TaggedUnion from a JSON string +tagged_union_instance = TaggedUnion.from_json(json) +# print the JSON string representation of the object +print(TaggedUnion.to_json()) + +# convert the object into a dict +tagged_union_dict = tagged_union_instance.to_dict() +# create an instance of TaggedUnion from a dict +tagged_union_from_dict = TaggedUnion.from_dict(tagged_union_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/__init__.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/__init__.py index e488e2a0ab56..b24fe4be25e1 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/__init__.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/__init__.py @@ -93,6 +93,7 @@ "InnerDictWithProperty", "InputAllOf", "IntOrString", + "Known", "ListClass", "MapOfArrayOfModel", "MapTest", @@ -110,6 +111,7 @@ "ObjectWithDeprecatedFields", "OneOfEnumString", "Order", + "Other", "OuterComposite", "OuterEnum", "OuterEnumDefaultValue", @@ -134,6 +136,7 @@ "SpecialModelName", "SpecialName", "Tag", + "TaggedUnion", "Task", "TaskActivity", "TestEnum", @@ -236,6 +239,7 @@ from petstore_api.models.inner_dict_with_property import InnerDictWithProperty as InnerDictWithProperty from petstore_api.models.input_all_of import InputAllOf as InputAllOf from petstore_api.models.int_or_string import IntOrString as IntOrString + from petstore_api.models.known import Known as Known from petstore_api.models.list_class import ListClass as ListClass from petstore_api.models.map_of_array_of_model import MapOfArrayOfModel as MapOfArrayOfModel from petstore_api.models.map_test import MapTest as MapTest @@ -253,6 +257,7 @@ from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields as ObjectWithDeprecatedFields from petstore_api.models.one_of_enum_string import OneOfEnumString as OneOfEnumString from petstore_api.models.order import Order as Order + from petstore_api.models.other import Other as Other from petstore_api.models.outer_composite import OuterComposite as OuterComposite from petstore_api.models.outer_enum import OuterEnum as OuterEnum from petstore_api.models.outer_enum_default_value import OuterEnumDefaultValue as OuterEnumDefaultValue @@ -277,6 +282,7 @@ from petstore_api.models.special_model_name import SpecialModelName as SpecialModelName from petstore_api.models.special_name import SpecialName as SpecialName from petstore_api.models.tag import Tag as Tag + from petstore_api.models.tagged_union import TaggedUnion as TaggedUnion from petstore_api.models.task import Task as Task from petstore_api.models.task_activity import TaskActivity as TaskActivity from petstore_api.models.test_enum import TestEnum as TestEnum @@ -374,6 +380,7 @@ "InnerDictWithProperty": ".models.inner_dict_with_property", "InputAllOf": ".models.input_all_of", "IntOrString": ".models.int_or_string", + "Known": ".models.known", "ListClass": ".models.list_class", "MapOfArrayOfModel": ".models.map_of_array_of_model", "MapTest": ".models.map_test", @@ -391,6 +398,7 @@ "ObjectWithDeprecatedFields": ".models.object_with_deprecated_fields", "OneOfEnumString": ".models.one_of_enum_string", "Order": ".models.order", + "Other": ".models.other", "OuterComposite": ".models.outer_composite", "OuterEnum": ".models.outer_enum", "OuterEnumDefaultValue": ".models.outer_enum_default_value", @@ -415,6 +423,7 @@ "SpecialModelName": ".models.special_model_name", "SpecialName": ".models.special_name", "Tag": ".models.tag", + "TaggedUnion": ".models.tagged_union", "Task": ".models.task", "TaskActivity": ".models.task_activity", "TestEnum": ".models.test_enum", diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/__init__.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/__init__.py index cd5b0e8ca469..1b44704ace17 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/__init__.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/__init__.py @@ -70,6 +70,7 @@ "InnerDictWithProperty", "InputAllOf", "IntOrString", + "Known", "ListClass", "MapOfArrayOfModel", "MapTest", @@ -87,6 +88,7 @@ "ObjectWithDeprecatedFields", "OneOfEnumString", "Order", + "Other", "OuterComposite", "OuterEnum", "OuterEnumDefaultValue", @@ -111,6 +113,7 @@ "SpecialModelName", "SpecialName", "Tag", + "TaggedUnion", "Task", "TaskActivity", "TestEnum", @@ -191,6 +194,7 @@ from petstore_api.models.inner_dict_with_property import InnerDictWithProperty from petstore_api.models.input_all_of import InputAllOf from petstore_api.models.int_or_string import IntOrString + from petstore_api.models.known import Known from petstore_api.models.list_class import ListClass from petstore_api.models.map_of_array_of_model import MapOfArrayOfModel from petstore_api.models.map_test import MapTest @@ -208,6 +212,7 @@ from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields from petstore_api.models.one_of_enum_string import OneOfEnumString from petstore_api.models.order import Order + from petstore_api.models.other import Other from petstore_api.models.outer_composite import OuterComposite from petstore_api.models.outer_enum import OuterEnum from petstore_api.models.outer_enum_default_value import OuterEnumDefaultValue @@ -232,6 +237,7 @@ from petstore_api.models.special_model_name import SpecialModelName from petstore_api.models.special_name import SpecialName from petstore_api.models.tag import Tag + from petstore_api.models.tagged_union import TaggedUnion from petstore_api.models.task import Task from petstore_api.models.task_activity import TaskActivity from petstore_api.models.test_enum import TestEnum @@ -311,6 +317,7 @@ "InnerDictWithProperty": ".inner_dict_with_property", "InputAllOf": ".input_all_of", "IntOrString": ".int_or_string", + "Known": ".known", "ListClass": ".list_class", "MapOfArrayOfModel": ".map_of_array_of_model", "MapTest": ".map_test", @@ -328,6 +335,7 @@ "ObjectWithDeprecatedFields": ".object_with_deprecated_fields", "OneOfEnumString": ".one_of_enum_string", "Order": ".order", + "Other": ".other", "OuterComposite": ".outer_composite", "OuterEnum": ".outer_enum", "OuterEnumDefaultValue": ".outer_enum_default_value", @@ -352,6 +360,7 @@ "SpecialModelName": ".special_model_name", "SpecialName": ".special_name", "Tag": ".tag", + "TaggedUnion": ".tagged_union", "Task": ".task", "TaskActivity": ".task_activity", "TestEnum": ".test_enum", diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/known.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/known.py new file mode 100644 index 000000000000..8d837239ac79 --- /dev/null +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/known.py @@ -0,0 +1,108 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class Known(BaseModel): + """ + Known + """ # noqa: E501 + kind: StrictStr + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["kind"] + + @field_validator('kind') + def kind_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['known']): + raise ValueError("must be one of enum values ('known')") + return value + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Known from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + * Fields in `self.additional_properties` are added to the output dict. + """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Known from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "kind": obj.get("kind") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/other.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/other.py new file mode 100644 index 000000000000..665e41e78584 --- /dev/null +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/other.py @@ -0,0 +1,107 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class Other(BaseModel): + """ + Other + """ # noqa: E501 + kind: StrictStr + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["kind"] + @field_validator('kind') + def kind_validate_not_enum(cls, value): + """Validates values excluded by not""" + if value in set(["known", "reserved"]): + raise ValueError("must not be one of excluded enum values") + return value + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Other from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + * Fields in `self.additional_properties` are added to the output dict. + """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Other from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "kind": obj.get("kind") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/tagged_union.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/tagged_union.py new file mode 100644 index 000000000000..2930dd983976 --- /dev/null +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/tagged_union.py @@ -0,0 +1,137 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +import pprint +from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional +from petstore_api.models.known import Known +from petstore_api.models.other import Other +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self + +TAGGEDUNION_ONE_OF_SCHEMAS = ["Known", "Other"] + +class TaggedUnion(BaseModel): + """ + TaggedUnion + """ + # data type: Known + oneof_schema_1_validator: Optional[Known] = None + # data type: Other + oneof_schema_2_validator: Optional[Other] = None + actual_instance: Optional[Union[Known, Other]] = None + one_of_schemas: Set[str] = { "Known", "Other" } + + model_config = ConfigDict( + validate_assignment=True, + protected_namespaces=(), + ) + + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @field_validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = TaggedUnion.model_construct() + error_messages = [] + match = 0 + # validate data type: Known + if not isinstance(v, Known): + error_messages.append(f"Error! Input type `{type(v)}` is not `Known`") + else: + match += 1 + # validate data type: Other + if not isinstance(v, Other): + error_messages.append(f"Error! Input type `{type(v)}` is not `Other`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + instance = cls.model_construct() + error_messages = [] + match = 0 + + # deserialize data into Known + try: + instance.actual_instance = Known.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into Other + try: + instance.actual_instance = Other.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> Optional[Union[Dict[str, Any], Known, Other]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.model_dump()) + + diff --git a/samples/openapi3/client/petstore/python-lazyImports/test/test_known.py b/samples/openapi3/client/petstore/python-lazyImports/test/test_known.py new file mode 100644 index 000000000000..2754cd498854 --- /dev/null +++ b/samples/openapi3/client/petstore/python-lazyImports/test/test_known.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from petstore_api.models.known import Known + +class TestKnown(unittest.TestCase): + """Known unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Known: + """Test Known + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `Known` + """ + model = Known() + if include_optional: + return Known( + kind = 'known' + ) + else: + return Known( + kind = 'known', + ) + """ + + def testKnown(self): + """Test Known""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-lazyImports/test/test_other.py b/samples/openapi3/client/petstore/python-lazyImports/test/test_other.py new file mode 100644 index 000000000000..293c4e281d57 --- /dev/null +++ b/samples/openapi3/client/petstore/python-lazyImports/test/test_other.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from petstore_api.models.other import Other + +class TestOther(unittest.TestCase): + """Other unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Other: + """Test Other + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `Other` + """ + model = Other() + if include_optional: + return Other( + kind = '' + ) + else: + return Other( + kind = '', + ) + """ + + def testOther(self): + """Test Other""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-lazyImports/test/test_tagged_union.py b/samples/openapi3/client/petstore/python-lazyImports/test/test_tagged_union.py new file mode 100644 index 000000000000..327181f5c429 --- /dev/null +++ b/samples/openapi3/client/petstore/python-lazyImports/test/test_tagged_union.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from petstore_api.models.tagged_union import TaggedUnion + +class TestTaggedUnion(unittest.TestCase): + """TaggedUnion unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TaggedUnion: + """Test TaggedUnion + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `TaggedUnion` + """ + model = TaggedUnion() + if include_optional: + return TaggedUnion( + kind = '' + ) + else: + return TaggedUnion( + kind = '', + ) + """ + + def testTaggedUnion(self): + """Test TaggedUnion""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/.openapi-generator/FILES b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/.openapi-generator/FILES index c2c1ad09f121..af3a7fd58277 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/.openapi-generator/FILES @@ -67,6 +67,7 @@ docs/Info.md docs/InnerDictWithProperty.md docs/InputAllOf.md docs/IntOrString.md +docs/Known.md docs/ListClass.md docs/MapOfArrayOfModel.md docs/MapTest.md @@ -82,6 +83,7 @@ docs/ObjectToTestAdditionalProperties.md docs/ObjectWithDeprecatedFields.md docs/OneOfEnumString.md docs/Order.md +docs/Other.md docs/OuterComposite.md docs/OuterEnum.md docs/OuterEnumDefaultValue.md @@ -108,6 +110,7 @@ docs/SpecialModelName.md docs/SpecialName.md docs/StoreApi.md docs/Tag.md +docs/TaggedUnion.md docs/Task.md docs/TaskActivity.md docs/TestEnum.md @@ -201,6 +204,7 @@ petstore_api/models/info.py petstore_api/models/inner_dict_with_property.py petstore_api/models/input_all_of.py petstore_api/models/int_or_string.py +petstore_api/models/known.py petstore_api/models/list_class.py petstore_api/models/map_of_array_of_model.py petstore_api/models/map_test.py @@ -216,6 +220,7 @@ petstore_api/models/object_to_test_additional_properties.py petstore_api/models/object_with_deprecated_fields.py petstore_api/models/one_of_enum_string.py petstore_api/models/order.py +petstore_api/models/other.py petstore_api/models/outer_composite.py petstore_api/models/outer_enum.py petstore_api/models/outer_enum_default_value.py @@ -240,6 +245,7 @@ petstore_api/models/special_character_enum.py petstore_api/models/special_model_name.py petstore_api/models/special_name.py petstore_api/models/tag.py +petstore_api/models/tagged_union.py petstore_api/models/task.py petstore_api/models/task_activity.py petstore_api/models/test_enum.py diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/README.md b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/README.md index 86b3becb86bb..6d7a3ccbe92c 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/README.md +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/README.md @@ -212,6 +212,7 @@ Class | Method | HTTP request | Description - [InnerDictWithProperty](docs/InnerDictWithProperty.md) - [InputAllOf](docs/InputAllOf.md) - [IntOrString](docs/IntOrString.md) + - [Known](docs/Known.md) - [ListClass](docs/ListClass.md) - [MapOfArrayOfModel](docs/MapOfArrayOfModel.md) - [MapTest](docs/MapTest.md) @@ -227,6 +228,7 @@ Class | Method | HTTP request | Description - [ObjectWithDeprecatedFields](docs/ObjectWithDeprecatedFields.md) - [OneOfEnumString](docs/OneOfEnumString.md) - [Order](docs/Order.md) + - [Other](docs/Other.md) - [OuterComposite](docs/OuterComposite.md) - [OuterEnum](docs/OuterEnum.md) - [OuterEnumDefaultValue](docs/OuterEnumDefaultValue.md) @@ -251,6 +253,7 @@ Class | Method | HTTP request | Description - [SpecialModelName](docs/SpecialModelName.md) - [SpecialName](docs/SpecialName.md) - [Tag](docs/Tag.md) + - [TaggedUnion](docs/TaggedUnion.md) - [Task](docs/Task.md) - [TaskActivity](docs/TaskActivity.md) - [TestEnum](docs/TestEnum.md) diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/Known.md b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/Known.md new file mode 100644 index 000000000000..943774bfa614 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/Known.md @@ -0,0 +1,28 @@ +# Known + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **str** | | + +## Example + +```python +from petstore_api.models.known import Known + +# TODO update the JSON string below +json = "{}" +# create an instance of Known from a JSON string +known_instance = Known.from_json(json) +# print the JSON string representation of the object +print Known.to_json() + +# convert the object into a dict +known_dict = known_instance.to_dict() +# create an instance of Known from a dict +known_from_dict = Known.from_dict(known_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/Other.md b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/Other.md new file mode 100644 index 000000000000..200c37329313 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/Other.md @@ -0,0 +1,28 @@ +# Other + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **str** | | + +## Example + +```python +from petstore_api.models.other import Other + +# TODO update the JSON string below +json = "{}" +# create an instance of Other from a JSON string +other_instance = Other.from_json(json) +# print the JSON string representation of the object +print Other.to_json() + +# convert the object into a dict +other_dict = other_instance.to_dict() +# create an instance of Other from a dict +other_from_dict = Other.from_dict(other_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/TaggedUnion.md b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/TaggedUnion.md new file mode 100644 index 000000000000..2f340c0f83ac --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/TaggedUnion.md @@ -0,0 +1,28 @@ +# TaggedUnion + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **str** | | + +## Example + +```python +from petstore_api.models.tagged_union import TaggedUnion + +# TODO update the JSON string below +json = "{}" +# create an instance of TaggedUnion from a JSON string +tagged_union_instance = TaggedUnion.from_json(json) +# print the JSON string representation of the object +print TaggedUnion.to_json() + +# convert the object into a dict +tagged_union_dict = tagged_union_instance.to_dict() +# create an instance of TaggedUnion from a dict +tagged_union_from_dict = TaggedUnion.from_dict(tagged_union_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/__init__.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/__init__.py index ed391cc674af..898177398403 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/__init__.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/__init__.py @@ -95,6 +95,7 @@ "InnerDictWithProperty", "InputAllOf", "IntOrString", + "Known", "ListClass", "MapOfArrayOfModel", "MapTest", @@ -110,6 +111,7 @@ "ObjectWithDeprecatedFields", "OneOfEnumString", "Order", + "Other", "OuterComposite", "OuterEnum", "OuterEnumDefaultValue", @@ -134,6 +136,7 @@ "SpecialModelName", "SpecialName", "Tag", + "TaggedUnion", "Task", "TaskActivity", "TestEnum", @@ -235,6 +238,7 @@ from petstore_api.models.inner_dict_with_property import InnerDictWithProperty as InnerDictWithProperty from petstore_api.models.input_all_of import InputAllOf as InputAllOf from petstore_api.models.int_or_string import IntOrString as IntOrString +from petstore_api.models.known import Known as Known from petstore_api.models.list_class import ListClass as ListClass from petstore_api.models.map_of_array_of_model import MapOfArrayOfModel as MapOfArrayOfModel from petstore_api.models.map_test import MapTest as MapTest @@ -250,6 +254,7 @@ from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields as ObjectWithDeprecatedFields from petstore_api.models.one_of_enum_string import OneOfEnumString as OneOfEnumString from petstore_api.models.order import Order as Order +from petstore_api.models.other import Other as Other from petstore_api.models.outer_composite import OuterComposite as OuterComposite from petstore_api.models.outer_enum import OuterEnum as OuterEnum from petstore_api.models.outer_enum_default_value import OuterEnumDefaultValue as OuterEnumDefaultValue @@ -274,6 +279,7 @@ from petstore_api.models.special_model_name import SpecialModelName as SpecialModelName from petstore_api.models.special_name import SpecialName as SpecialName from petstore_api.models.tag import Tag as Tag +from petstore_api.models.tagged_union import TaggedUnion as TaggedUnion from petstore_api.models.task import Task as Task from petstore_api.models.task_activity import TaskActivity as TaskActivity from petstore_api.models.test_enum import TestEnum as TestEnum diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/__init__.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/__init__.py index 1f1469015ee0..5e8fb9139ae8 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/__init__.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/__init__.py @@ -73,6 +73,7 @@ from petstore_api.models.inner_dict_with_property import InnerDictWithProperty from petstore_api.models.input_all_of import InputAllOf from petstore_api.models.int_or_string import IntOrString +from petstore_api.models.known import Known from petstore_api.models.list_class import ListClass from petstore_api.models.map_of_array_of_model import MapOfArrayOfModel from petstore_api.models.map_test import MapTest @@ -88,6 +89,7 @@ from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields from petstore_api.models.one_of_enum_string import OneOfEnumString from petstore_api.models.order import Order +from petstore_api.models.other import Other from petstore_api.models.outer_composite import OuterComposite from petstore_api.models.outer_enum import OuterEnum from petstore_api.models.outer_enum_default_value import OuterEnumDefaultValue @@ -112,6 +114,7 @@ from petstore_api.models.special_model_name import SpecialModelName from petstore_api.models.special_name import SpecialName from petstore_api.models.tag import Tag +from petstore_api.models.tagged_union import TaggedUnion from petstore_api.models.task import Task from petstore_api.models.task_activity import TaskActivity from petstore_api.models.test_enum import TestEnum diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/known.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/known.py new file mode 100644 index 000000000000..8a56acac8b75 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/known.py @@ -0,0 +1,78 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + + +from pydantic import BaseModel, Field, StrictStr, validator + +class Known(BaseModel): + """ + Known + """ + kind: StrictStr = Field(...) + __properties = ["kind"] + + @validator('kind') + def kind_validate_enum(cls, value): + """Validates the enum""" + if value not in ('known',): + raise ValueError("must be one of enum values ('known')") + return value + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Known: + """Create an instance of Known from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + }, + exclude_none=True) + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> Known: + """Create an instance of Known from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return Known.parse_obj(obj) + + _obj = Known.parse_obj({ + "kind": obj.get("kind") + }) + return _obj + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/other.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/other.py new file mode 100644 index 000000000000..0355ae385e33 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/other.py @@ -0,0 +1,71 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + + +from pydantic import BaseModel, Field, StrictStr + +class Other(BaseModel): + """ + Other + """ + kind: StrictStr = Field(...) + __properties = ["kind"] + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Other: + """Create an instance of Other from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + }, + exclude_none=True) + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> Other: + """Create an instance of Other from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return Other.parse_obj(obj) + + _obj = Other.parse_obj({ + "kind": obj.get("kind") + }) + return _obj + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/tagged_union.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/tagged_union.py new file mode 100644 index 000000000000..52c475f6f9b2 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/tagged_union.py @@ -0,0 +1,141 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +from inspect import getfullargspec +import json +import pprint +import re # noqa: F401 + +from typing import Any, List, Optional +from pydantic import BaseModel, Field, StrictStr, ValidationError, validator +from petstore_api.models.known import Known +from petstore_api.models.other import Other +from typing import Union, Any, List, TYPE_CHECKING +from pydantic import StrictStr, Field + +TAGGEDUNION_ONE_OF_SCHEMAS = ["Known", "Other"] + +class TaggedUnion(BaseModel): + """ + TaggedUnion + """ + # data type: Known + oneof_schema_1_validator: Optional[Known] = None + # data type: Other + oneof_schema_2_validator: Optional[Other] = None + if TYPE_CHECKING: + actual_instance: Union[Known, Other] + else: + actual_instance: Any + one_of_schemas: List[str] = Field(TAGGEDUNION_ONE_OF_SCHEMAS, const=True) + + class Config: + validate_assignment = True + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = TaggedUnion.construct() + error_messages = [] + match = 0 + # validate data type: Known + if not isinstance(v, Known): + error_messages.append(f"Error! Input type `{type(v)}` is not `Known`") + else: + match += 1 + # validate data type: Other + if not isinstance(v, Other): + error_messages.append(f"Error! Input type `{type(v)}` is not `Other`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: dict) -> TaggedUnion: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> TaggedUnion: + """Returns the object represented by the json string""" + instance = TaggedUnion.construct() + error_messages = [] + match = 0 + + # deserialize data into Known + try: + instance.actual_instance = Known.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into Other + try: + instance.actual_instance = Other.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + to_json = getattr(self.actual_instance, "to_json", None) + if callable(to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> dict: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + to_dict = getattr(self.actual_instance, "to_dict", None) + if callable(to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.dict()) + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_known.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_known.py new file mode 100644 index 000000000000..1e88c2b12317 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_known.py @@ -0,0 +1,53 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +from petstore_api.models.known import Known # noqa: E501 + +class TestKnown(unittest.TestCase): + """Known unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Known: + """Test Known + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `Known` + """ + model = Known() # noqa: E501 + if include_optional: + return Known( + kind = 'known' + ) + else: + return Known( + kind = 'known', + ) + """ + + def testKnown(self): + """Test Known""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_other.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_other.py new file mode 100644 index 000000000000..6caf6ebbeb66 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_other.py @@ -0,0 +1,53 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +from petstore_api.models.other import Other # noqa: E501 + +class TestOther(unittest.TestCase): + """Other unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Other: + """Test Other + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `Other` + """ + model = Other() # noqa: E501 + if include_optional: + return Other( + kind = '' + ) + else: + return Other( + kind = '', + ) + """ + + def testOther(self): + """Test Other""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_tagged_union.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_tagged_union.py new file mode 100644 index 000000000000..b919fd2c7d85 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_tagged_union.py @@ -0,0 +1,53 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +from petstore_api.models.tagged_union import TaggedUnion # noqa: E501 + +class TestTaggedUnion(unittest.TestCase): + """TaggedUnion unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TaggedUnion: + """Test TaggedUnion + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `TaggedUnion` + """ + model = TaggedUnion() # noqa: E501 + if include_optional: + return TaggedUnion( + kind = '' + ) + else: + return TaggedUnion( + kind = '', + ) + """ + + def testTaggedUnion(self): + """Test TaggedUnion""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/.openapi-generator/FILES b/samples/openapi3/client/petstore/python-pydantic-v1/.openapi-generator/FILES index c2c1ad09f121..af3a7fd58277 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python-pydantic-v1/.openapi-generator/FILES @@ -67,6 +67,7 @@ docs/Info.md docs/InnerDictWithProperty.md docs/InputAllOf.md docs/IntOrString.md +docs/Known.md docs/ListClass.md docs/MapOfArrayOfModel.md docs/MapTest.md @@ -82,6 +83,7 @@ docs/ObjectToTestAdditionalProperties.md docs/ObjectWithDeprecatedFields.md docs/OneOfEnumString.md docs/Order.md +docs/Other.md docs/OuterComposite.md docs/OuterEnum.md docs/OuterEnumDefaultValue.md @@ -108,6 +110,7 @@ docs/SpecialModelName.md docs/SpecialName.md docs/StoreApi.md docs/Tag.md +docs/TaggedUnion.md docs/Task.md docs/TaskActivity.md docs/TestEnum.md @@ -201,6 +204,7 @@ petstore_api/models/info.py petstore_api/models/inner_dict_with_property.py petstore_api/models/input_all_of.py petstore_api/models/int_or_string.py +petstore_api/models/known.py petstore_api/models/list_class.py petstore_api/models/map_of_array_of_model.py petstore_api/models/map_test.py @@ -216,6 +220,7 @@ petstore_api/models/object_to_test_additional_properties.py petstore_api/models/object_with_deprecated_fields.py petstore_api/models/one_of_enum_string.py petstore_api/models/order.py +petstore_api/models/other.py petstore_api/models/outer_composite.py petstore_api/models/outer_enum.py petstore_api/models/outer_enum_default_value.py @@ -240,6 +245,7 @@ petstore_api/models/special_character_enum.py petstore_api/models/special_model_name.py petstore_api/models/special_name.py petstore_api/models/tag.py +petstore_api/models/tagged_union.py petstore_api/models/task.py petstore_api/models/task_activity.py petstore_api/models/test_enum.py diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/README.md b/samples/openapi3/client/petstore/python-pydantic-v1/README.md index e2ad40592c8f..f9e814400d26 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/README.md +++ b/samples/openapi3/client/petstore/python-pydantic-v1/README.md @@ -212,6 +212,7 @@ Class | Method | HTTP request | Description - [InnerDictWithProperty](docs/InnerDictWithProperty.md) - [InputAllOf](docs/InputAllOf.md) - [IntOrString](docs/IntOrString.md) + - [Known](docs/Known.md) - [ListClass](docs/ListClass.md) - [MapOfArrayOfModel](docs/MapOfArrayOfModel.md) - [MapTest](docs/MapTest.md) @@ -227,6 +228,7 @@ Class | Method | HTTP request | Description - [ObjectWithDeprecatedFields](docs/ObjectWithDeprecatedFields.md) - [OneOfEnumString](docs/OneOfEnumString.md) - [Order](docs/Order.md) + - [Other](docs/Other.md) - [OuterComposite](docs/OuterComposite.md) - [OuterEnum](docs/OuterEnum.md) - [OuterEnumDefaultValue](docs/OuterEnumDefaultValue.md) @@ -251,6 +253,7 @@ Class | Method | HTTP request | Description - [SpecialModelName](docs/SpecialModelName.md) - [SpecialName](docs/SpecialName.md) - [Tag](docs/Tag.md) + - [TaggedUnion](docs/TaggedUnion.md) - [Task](docs/Task.md) - [TaskActivity](docs/TaskActivity.md) - [TestEnum](docs/TestEnum.md) diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/docs/Known.md b/samples/openapi3/client/petstore/python-pydantic-v1/docs/Known.md new file mode 100644 index 000000000000..943774bfa614 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/docs/Known.md @@ -0,0 +1,28 @@ +# Known + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **str** | | + +## Example + +```python +from petstore_api.models.known import Known + +# TODO update the JSON string below +json = "{}" +# create an instance of Known from a JSON string +known_instance = Known.from_json(json) +# print the JSON string representation of the object +print Known.to_json() + +# convert the object into a dict +known_dict = known_instance.to_dict() +# create an instance of Known from a dict +known_from_dict = Known.from_dict(known_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/docs/Other.md b/samples/openapi3/client/petstore/python-pydantic-v1/docs/Other.md new file mode 100644 index 000000000000..200c37329313 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/docs/Other.md @@ -0,0 +1,28 @@ +# Other + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **str** | | + +## Example + +```python +from petstore_api.models.other import Other + +# TODO update the JSON string below +json = "{}" +# create an instance of Other from a JSON string +other_instance = Other.from_json(json) +# print the JSON string representation of the object +print Other.to_json() + +# convert the object into a dict +other_dict = other_instance.to_dict() +# create an instance of Other from a dict +other_from_dict = Other.from_dict(other_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/docs/TaggedUnion.md b/samples/openapi3/client/petstore/python-pydantic-v1/docs/TaggedUnion.md new file mode 100644 index 000000000000..2f340c0f83ac --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/docs/TaggedUnion.md @@ -0,0 +1,28 @@ +# TaggedUnion + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **str** | | + +## Example + +```python +from petstore_api.models.tagged_union import TaggedUnion + +# TODO update the JSON string below +json = "{}" +# create an instance of TaggedUnion from a JSON string +tagged_union_instance = TaggedUnion.from_json(json) +# print the JSON string representation of the object +print TaggedUnion.to_json() + +# convert the object into a dict +tagged_union_dict = tagged_union_instance.to_dict() +# create an instance of TaggedUnion from a dict +tagged_union_from_dict = TaggedUnion.from_dict(tagged_union_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/__init__.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/__init__.py index ed391cc674af..898177398403 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/__init__.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/__init__.py @@ -95,6 +95,7 @@ "InnerDictWithProperty", "InputAllOf", "IntOrString", + "Known", "ListClass", "MapOfArrayOfModel", "MapTest", @@ -110,6 +111,7 @@ "ObjectWithDeprecatedFields", "OneOfEnumString", "Order", + "Other", "OuterComposite", "OuterEnum", "OuterEnumDefaultValue", @@ -134,6 +136,7 @@ "SpecialModelName", "SpecialName", "Tag", + "TaggedUnion", "Task", "TaskActivity", "TestEnum", @@ -235,6 +238,7 @@ from petstore_api.models.inner_dict_with_property import InnerDictWithProperty as InnerDictWithProperty from petstore_api.models.input_all_of import InputAllOf as InputAllOf from petstore_api.models.int_or_string import IntOrString as IntOrString +from petstore_api.models.known import Known as Known from petstore_api.models.list_class import ListClass as ListClass from petstore_api.models.map_of_array_of_model import MapOfArrayOfModel as MapOfArrayOfModel from petstore_api.models.map_test import MapTest as MapTest @@ -250,6 +254,7 @@ from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields as ObjectWithDeprecatedFields from petstore_api.models.one_of_enum_string import OneOfEnumString as OneOfEnumString from petstore_api.models.order import Order as Order +from petstore_api.models.other import Other as Other from petstore_api.models.outer_composite import OuterComposite as OuterComposite from petstore_api.models.outer_enum import OuterEnum as OuterEnum from petstore_api.models.outer_enum_default_value import OuterEnumDefaultValue as OuterEnumDefaultValue @@ -274,6 +279,7 @@ from petstore_api.models.special_model_name import SpecialModelName as SpecialModelName from petstore_api.models.special_name import SpecialName as SpecialName from petstore_api.models.tag import Tag as Tag +from petstore_api.models.tagged_union import TaggedUnion as TaggedUnion from petstore_api.models.task import Task as Task from petstore_api.models.task_activity import TaskActivity as TaskActivity from petstore_api.models.test_enum import TestEnum as TestEnum diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/__init__.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/__init__.py index 1f1469015ee0..5e8fb9139ae8 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/__init__.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/__init__.py @@ -73,6 +73,7 @@ from petstore_api.models.inner_dict_with_property import InnerDictWithProperty from petstore_api.models.input_all_of import InputAllOf from petstore_api.models.int_or_string import IntOrString +from petstore_api.models.known import Known from petstore_api.models.list_class import ListClass from petstore_api.models.map_of_array_of_model import MapOfArrayOfModel from petstore_api.models.map_test import MapTest @@ -88,6 +89,7 @@ from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields from petstore_api.models.one_of_enum_string import OneOfEnumString from petstore_api.models.order import Order +from petstore_api.models.other import Other from petstore_api.models.outer_composite import OuterComposite from petstore_api.models.outer_enum import OuterEnum from petstore_api.models.outer_enum_default_value import OuterEnumDefaultValue @@ -112,6 +114,7 @@ from petstore_api.models.special_model_name import SpecialModelName from petstore_api.models.special_name import SpecialName from petstore_api.models.tag import Tag +from petstore_api.models.tagged_union import TaggedUnion from petstore_api.models.task import Task from petstore_api.models.task_activity import TaskActivity from petstore_api.models.test_enum import TestEnum diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/known.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/known.py new file mode 100644 index 000000000000..8fd795715dc3 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/known.py @@ -0,0 +1,90 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, Dict +from pydantic import BaseModel, Field, StrictStr, validator + +class Known(BaseModel): + """ + Known + """ + kind: StrictStr = Field(...) + additional_properties: Dict[str, Any] = {} + __properties = ["kind"] + + @validator('kind') + def kind_validate_enum(cls, value): + """Validates the enum""" + if value not in ('known',): + raise ValueError("must be one of enum values ('known')") + return value + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Known: + """Create an instance of Known from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + "additional_properties" + }, + exclude_none=True) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> Known: + """Create an instance of Known from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return Known.parse_obj(obj) + + _obj = Known.parse_obj({ + "kind": obj.get("kind") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/other.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/other.py new file mode 100644 index 000000000000..7219121e446b --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/other.py @@ -0,0 +1,83 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, Dict +from pydantic import BaseModel, Field, StrictStr + +class Other(BaseModel): + """ + Other + """ + kind: StrictStr = Field(...) + additional_properties: Dict[str, Any] = {} + __properties = ["kind"] + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Other: + """Create an instance of Other from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + "additional_properties" + }, + exclude_none=True) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> Other: + """Create an instance of Other from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return Other.parse_obj(obj) + + _obj = Other.parse_obj({ + "kind": obj.get("kind") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/tagged_union.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/tagged_union.py new file mode 100644 index 000000000000..52c475f6f9b2 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/tagged_union.py @@ -0,0 +1,141 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +from inspect import getfullargspec +import json +import pprint +import re # noqa: F401 + +from typing import Any, List, Optional +from pydantic import BaseModel, Field, StrictStr, ValidationError, validator +from petstore_api.models.known import Known +from petstore_api.models.other import Other +from typing import Union, Any, List, TYPE_CHECKING +from pydantic import StrictStr, Field + +TAGGEDUNION_ONE_OF_SCHEMAS = ["Known", "Other"] + +class TaggedUnion(BaseModel): + """ + TaggedUnion + """ + # data type: Known + oneof_schema_1_validator: Optional[Known] = None + # data type: Other + oneof_schema_2_validator: Optional[Other] = None + if TYPE_CHECKING: + actual_instance: Union[Known, Other] + else: + actual_instance: Any + one_of_schemas: List[str] = Field(TAGGEDUNION_ONE_OF_SCHEMAS, const=True) + + class Config: + validate_assignment = True + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = TaggedUnion.construct() + error_messages = [] + match = 0 + # validate data type: Known + if not isinstance(v, Known): + error_messages.append(f"Error! Input type `{type(v)}` is not `Known`") + else: + match += 1 + # validate data type: Other + if not isinstance(v, Other): + error_messages.append(f"Error! Input type `{type(v)}` is not `Other`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: dict) -> TaggedUnion: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> TaggedUnion: + """Returns the object represented by the json string""" + instance = TaggedUnion.construct() + error_messages = [] + match = 0 + + # deserialize data into Known + try: + instance.actual_instance = Known.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into Other + try: + instance.actual_instance = Other.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + to_json = getattr(self.actual_instance, "to_json", None) + if callable(to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> dict: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + to_dict = getattr(self.actual_instance, "to_dict", None) + if callable(to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.dict()) + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/test/test_known.py b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_known.py new file mode 100644 index 000000000000..1e88c2b12317 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_known.py @@ -0,0 +1,53 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +from petstore_api.models.known import Known # noqa: E501 + +class TestKnown(unittest.TestCase): + """Known unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Known: + """Test Known + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `Known` + """ + model = Known() # noqa: E501 + if include_optional: + return Known( + kind = 'known' + ) + else: + return Known( + kind = 'known', + ) + """ + + def testKnown(self): + """Test Known""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/test/test_other.py b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_other.py new file mode 100644 index 000000000000..6caf6ebbeb66 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_other.py @@ -0,0 +1,53 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +from petstore_api.models.other import Other # noqa: E501 + +class TestOther(unittest.TestCase): + """Other unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Other: + """Test Other + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `Other` + """ + model = Other() # noqa: E501 + if include_optional: + return Other( + kind = '' + ) + else: + return Other( + kind = '', + ) + """ + + def testOther(self): + """Test Other""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/test/test_tagged_union.py b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_tagged_union.py new file mode 100644 index 000000000000..b919fd2c7d85 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_tagged_union.py @@ -0,0 +1,53 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +from petstore_api.models.tagged_union import TaggedUnion # noqa: E501 + +class TestTaggedUnion(unittest.TestCase): + """TaggedUnion unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TaggedUnion: + """Test TaggedUnion + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `TaggedUnion` + """ + model = TaggedUnion() # noqa: E501 + if include_optional: + return TaggedUnion( + kind = '' + ) + else: + return TaggedUnion( + kind = '', + ) + """ + + def testTaggedUnion(self): + """Test TaggedUnion""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/.openapi-generator/FILES b/samples/openapi3/client/petstore/python/.openapi-generator/FILES index d808742215cb..b41f3bc2bf8f 100755 --- a/samples/openapi3/client/petstore/python/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python/.openapi-generator/FILES @@ -65,6 +65,7 @@ docs/Info.md docs/InnerDictWithProperty.md docs/InputAllOf.md docs/IntOrString.md +docs/Known.md docs/ListClass.md docs/MapOfArrayOfModel.md docs/MapTest.md @@ -82,6 +83,7 @@ docs/ObjectToTestAdditionalProperties.md docs/ObjectWithDeprecatedFields.md docs/OneOfEnumString.md docs/Order.md +docs/Other.md docs/OuterComposite.md docs/OuterEnum.md docs/OuterEnumDefaultValue.md @@ -108,6 +110,7 @@ docs/SpecialModelName.md docs/SpecialName.md docs/StoreApi.md docs/Tag.md +docs/TaggedUnion.md docs/Task.md docs/TaskActivity.md docs/TestEnum.md @@ -199,6 +202,7 @@ petstore_api/models/info.py petstore_api/models/inner_dict_with_property.py petstore_api/models/input_all_of.py petstore_api/models/int_or_string.py +petstore_api/models/known.py petstore_api/models/list_class.py petstore_api/models/map_of_array_of_model.py petstore_api/models/map_test.py @@ -216,6 +220,7 @@ petstore_api/models/object_to_test_additional_properties.py petstore_api/models/object_with_deprecated_fields.py petstore_api/models/one_of_enum_string.py petstore_api/models/order.py +petstore_api/models/other.py petstore_api/models/outer_composite.py petstore_api/models/outer_enum.py petstore_api/models/outer_enum_default_value.py @@ -240,6 +245,7 @@ petstore_api/models/special_character_enum.py petstore_api/models/special_model_name.py petstore_api/models/special_name.py petstore_api/models/tag.py +petstore_api/models/tagged_union.py petstore_api/models/task.py petstore_api/models/task_activity.py petstore_api/models/test_enum.py diff --git a/samples/openapi3/client/petstore/python/README.md b/samples/openapi3/client/petstore/python/README.md index 8b8090a64c7e..d78bc29f67f0 100755 --- a/samples/openapi3/client/petstore/python/README.md +++ b/samples/openapi3/client/petstore/python/README.md @@ -214,6 +214,7 @@ Class | Method | HTTP request | Description - [InnerDictWithProperty](docs/InnerDictWithProperty.md) - [InputAllOf](docs/InputAllOf.md) - [IntOrString](docs/IntOrString.md) + - [Known](docs/Known.md) - [ListClass](docs/ListClass.md) - [MapOfArrayOfModel](docs/MapOfArrayOfModel.md) - [MapTest](docs/MapTest.md) @@ -231,6 +232,7 @@ Class | Method | HTTP request | Description - [ObjectWithDeprecatedFields](docs/ObjectWithDeprecatedFields.md) - [OneOfEnumString](docs/OneOfEnumString.md) - [Order](docs/Order.md) + - [Other](docs/Other.md) - [OuterComposite](docs/OuterComposite.md) - [OuterEnum](docs/OuterEnum.md) - [OuterEnumDefaultValue](docs/OuterEnumDefaultValue.md) @@ -255,6 +257,7 @@ Class | Method | HTTP request | Description - [SpecialModelName](docs/SpecialModelName.md) - [SpecialName](docs/SpecialName.md) - [Tag](docs/Tag.md) + - [TaggedUnion](docs/TaggedUnion.md) - [Task](docs/Task.md) - [TaskActivity](docs/TaskActivity.md) - [TestEnum](docs/TestEnum.md) diff --git a/samples/openapi3/client/petstore/python/docs/Known.md b/samples/openapi3/client/petstore/python/docs/Known.md new file mode 100644 index 000000000000..fba8453dcd02 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/Known.md @@ -0,0 +1,29 @@ +# Known + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **str** | | + +## Example + +```python +from petstore_api.models.known import Known + +# TODO update the JSON string below +json = "{}" +# create an instance of Known from a JSON string +known_instance = Known.from_json(json) +# print the JSON string representation of the object +print(Known.to_json()) + +# convert the object into a dict +known_dict = known_instance.to_dict() +# create an instance of Known from a dict +known_from_dict = Known.from_dict(known_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python/docs/Other.md b/samples/openapi3/client/petstore/python/docs/Other.md new file mode 100644 index 000000000000..972767b30e1d --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/Other.md @@ -0,0 +1,29 @@ +# Other + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **str** | | + +## Example + +```python +from petstore_api.models.other import Other + +# TODO update the JSON string below +json = "{}" +# create an instance of Other from a JSON string +other_instance = Other.from_json(json) +# print the JSON string representation of the object +print(Other.to_json()) + +# convert the object into a dict +other_dict = other_instance.to_dict() +# create an instance of Other from a dict +other_from_dict = Other.from_dict(other_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python/docs/TaggedUnion.md b/samples/openapi3/client/petstore/python/docs/TaggedUnion.md new file mode 100644 index 000000000000..fdeed022e4c7 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/TaggedUnion.md @@ -0,0 +1,29 @@ +# TaggedUnion + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **str** | | + +## Example + +```python +from petstore_api.models.tagged_union import TaggedUnion + +# TODO update the JSON string below +json = "{}" +# create an instance of TaggedUnion from a JSON string +tagged_union_instance = TaggedUnion.from_json(json) +# print the JSON string representation of the object +print(TaggedUnion.to_json()) + +# convert the object into a dict +tagged_union_dict = tagged_union_instance.to_dict() +# create an instance of TaggedUnion from a dict +tagged_union_from_dict = TaggedUnion.from_dict(tagged_union_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/__init__.py index 55be0097b9d0..051197ea04f4 100755 --- a/samples/openapi3/client/petstore/python/petstore_api/__init__.py +++ b/samples/openapi3/client/petstore/python/petstore_api/__init__.py @@ -93,6 +93,7 @@ "InnerDictWithProperty", "InputAllOf", "IntOrString", + "Known", "ListClass", "MapOfArrayOfModel", "MapTest", @@ -110,6 +111,7 @@ "ObjectWithDeprecatedFields", "OneOfEnumString", "Order", + "Other", "OuterComposite", "OuterEnum", "OuterEnumDefaultValue", @@ -134,6 +136,7 @@ "SpecialModelName", "SpecialName", "Tag", + "TaggedUnion", "Task", "TaskActivity", "TestEnum", @@ -233,6 +236,7 @@ from petstore_api.models.inner_dict_with_property import InnerDictWithProperty as InnerDictWithProperty from petstore_api.models.input_all_of import InputAllOf as InputAllOf from petstore_api.models.int_or_string import IntOrString as IntOrString +from petstore_api.models.known import Known as Known from petstore_api.models.list_class import ListClass as ListClass from petstore_api.models.map_of_array_of_model import MapOfArrayOfModel as MapOfArrayOfModel from petstore_api.models.map_test import MapTest as MapTest @@ -250,6 +254,7 @@ from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields as ObjectWithDeprecatedFields from petstore_api.models.one_of_enum_string import OneOfEnumString as OneOfEnumString from petstore_api.models.order import Order as Order +from petstore_api.models.other import Other as Other from petstore_api.models.outer_composite import OuterComposite as OuterComposite from petstore_api.models.outer_enum import OuterEnum as OuterEnum from petstore_api.models.outer_enum_default_value import OuterEnumDefaultValue as OuterEnumDefaultValue @@ -274,6 +279,7 @@ from petstore_api.models.special_model_name import SpecialModelName as SpecialModelName from petstore_api.models.special_name import SpecialName as SpecialName from petstore_api.models.tag import Tag as Tag +from petstore_api.models.tagged_union import TaggedUnion as TaggedUnion from petstore_api.models.task import Task as Task from petstore_api.models.task_activity import TaskActivity as TaskActivity from petstore_api.models.test_enum import TestEnum as TestEnum diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py index 488a82150d32..662ae4a8325d 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py @@ -70,6 +70,7 @@ from petstore_api.models.inner_dict_with_property import InnerDictWithProperty from petstore_api.models.input_all_of import InputAllOf from petstore_api.models.int_or_string import IntOrString +from petstore_api.models.known import Known from petstore_api.models.list_class import ListClass from petstore_api.models.map_of_array_of_model import MapOfArrayOfModel from petstore_api.models.map_test import MapTest @@ -87,6 +88,7 @@ from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields from petstore_api.models.one_of_enum_string import OneOfEnumString from petstore_api.models.order import Order +from petstore_api.models.other import Other from petstore_api.models.outer_composite import OuterComposite from petstore_api.models.outer_enum import OuterEnum from petstore_api.models.outer_enum_default_value import OuterEnumDefaultValue @@ -111,6 +113,7 @@ from petstore_api.models.special_model_name import SpecialModelName from petstore_api.models.special_name import SpecialName from petstore_api.models.tag import Tag +from petstore_api.models.tagged_union import TaggedUnion from petstore_api.models.task import Task from petstore_api.models.task_activity import TaskActivity from petstore_api.models.test_enum import TestEnum diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/known.py b/samples/openapi3/client/petstore/python/petstore_api/models/known.py new file mode 100644 index 000000000000..8d837239ac79 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/models/known.py @@ -0,0 +1,108 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class Known(BaseModel): + """ + Known + """ # noqa: E501 + kind: StrictStr + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["kind"] + + @field_validator('kind') + def kind_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['known']): + raise ValueError("must be one of enum values ('known')") + return value + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Known from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + * Fields in `self.additional_properties` are added to the output dict. + """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Known from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "kind": obj.get("kind") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/other.py b/samples/openapi3/client/petstore/python/petstore_api/models/other.py new file mode 100644 index 000000000000..665e41e78584 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/models/other.py @@ -0,0 +1,107 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class Other(BaseModel): + """ + Other + """ # noqa: E501 + kind: StrictStr + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["kind"] + @field_validator('kind') + def kind_validate_not_enum(cls, value): + """Validates values excluded by not""" + if value in set(["known", "reserved"]): + raise ValueError("must not be one of excluded enum values") + return value + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Other from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + * Fields in `self.additional_properties` are added to the output dict. + """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Other from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "kind": obj.get("kind") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/tagged_union.py b/samples/openapi3/client/petstore/python/petstore_api/models/tagged_union.py new file mode 100644 index 000000000000..2930dd983976 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/models/tagged_union.py @@ -0,0 +1,137 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +import pprint +from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional +from petstore_api.models.known import Known +from petstore_api.models.other import Other +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self + +TAGGEDUNION_ONE_OF_SCHEMAS = ["Known", "Other"] + +class TaggedUnion(BaseModel): + """ + TaggedUnion + """ + # data type: Known + oneof_schema_1_validator: Optional[Known] = None + # data type: Other + oneof_schema_2_validator: Optional[Other] = None + actual_instance: Optional[Union[Known, Other]] = None + one_of_schemas: Set[str] = { "Known", "Other" } + + model_config = ConfigDict( + validate_assignment=True, + protected_namespaces=(), + ) + + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @field_validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = TaggedUnion.model_construct() + error_messages = [] + match = 0 + # validate data type: Known + if not isinstance(v, Known): + error_messages.append(f"Error! Input type `{type(v)}` is not `Known`") + else: + match += 1 + # validate data type: Other + if not isinstance(v, Other): + error_messages.append(f"Error! Input type `{type(v)}` is not `Other`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + instance = cls.model_construct() + error_messages = [] + match = 0 + + # deserialize data into Known + try: + instance.actual_instance = Known.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into Other + try: + instance.actual_instance = Other.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into TaggedUnion with oneOf schemas: Known, Other. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> Optional[Union[Dict[str, Any], Known, Other]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.model_dump()) + + diff --git a/samples/openapi3/client/petstore/python/test/test_known.py b/samples/openapi3/client/petstore/python/test/test_known.py new file mode 100644 index 000000000000..2754cd498854 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_known.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from petstore_api.models.known import Known + +class TestKnown(unittest.TestCase): + """Known unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Known: + """Test Known + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `Known` + """ + model = Known() + if include_optional: + return Known( + kind = 'known' + ) + else: + return Known( + kind = 'known', + ) + """ + + def testKnown(self): + """Test Known""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_other.py b/samples/openapi3/client/petstore/python/test/test_other.py new file mode 100644 index 000000000000..293c4e281d57 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_other.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from petstore_api.models.other import Other + +class TestOther(unittest.TestCase): + """Other unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Other: + """Test Other + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `Other` + """ + model = Other() + if include_optional: + return Other( + kind = '' + ) + else: + return Other( + kind = '', + ) + """ + + def testOther(self): + """Test Other""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_tagged_union.py b/samples/openapi3/client/petstore/python/test/test_tagged_union.py new file mode 100644 index 000000000000..327181f5c429 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_tagged_union.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from petstore_api.models.tagged_union import TaggedUnion + +class TestTaggedUnion(unittest.TestCase): + """TaggedUnion unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TaggedUnion: + """Test TaggedUnion + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `TaggedUnion` + """ + model = TaggedUnion() + if include_optional: + return TaggedUnion( + kind = '' + ) + else: + return TaggedUnion( + kind = '', + ) + """ + + def testTaggedUnion(self): + """Test TaggedUnion""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main()