From 2b275f99ebf1d165773a101ddc60253106a40b04 Mon Sep 17 00:00:00 2001 From: markstuart-oai Date: Wed, 23 Sep 2026 22:48:27 +0000 Subject: [PATCH] fix(python): preserve composed models in union containers --- .../languages/PythonClientCodegen.java | 51 ++++ .../python/_composed_model_dict.mustache | 9 + .../resources/python/model_anyof.mustache | 21 +- .../resources/python/model_oneof.mustache | 22 +- ...ith-fake-endpoints-models-for-testing.yaml | 54 +++++ .../models/any_of_model.py | 10 +- .../models/one_of_model.py | 10 +- .../python-aiohttp/.openapi-generator/FILES | 6 + .../client/petstore/python-aiohttp/README.md | 3 + .../python-aiohttp/docs/AnyOfContainer.md | 28 +++ .../docs/NestedUnionContainer.md | 28 +++ .../python-aiohttp/docs/OneOfContainer.md | 28 +++ .../python-aiohttp/petstore_api/__init__.py | 6 + .../petstore_api/models/__init__.py | 3 + .../petstore_api/models/any_of_color.py | 28 ++- .../petstore_api/models/any_of_container.py | 225 +++++++++++++++++ .../petstore_api/models/any_of_pig.py | 18 +- .../petstore_api/models/color.py | 29 ++- .../petstore_api/models/int_or_string.py | 19 +- .../models/nested_union_container.py | 153 ++++++++++++ .../petstore_api/models/one_of_container.py | 229 ++++++++++++++++++ .../python-aiohttp/petstore_api/models/pig.py | 19 +- .../petstore_api/models/task_activity.py | 19 +- .../test/test_any_of_container.py | 50 ++++ .../test/test_nested_union_container.py | 50 ++++ .../test/test_one_of_container.py | 50 ++++ .../.openapi-generator/FILES | 6 + .../petstore/python-httpx-sync/README.md | 3 + .../python-httpx-sync/docs/AnyOfContainer.md | 28 +++ .../docs/NestedUnionContainer.md | 28 +++ .../python-httpx-sync/docs/OneOfContainer.md | 28 +++ .../petstore_api/__init__.py | 6 + .../petstore_api/models/__init__.py | 3 + .../petstore_api/models/any_of_color.py | 28 ++- .../petstore_api/models/any_of_container.py | 225 +++++++++++++++++ .../petstore_api/models/any_of_pig.py | 18 +- .../petstore_api/models/color.py | 29 ++- .../petstore_api/models/int_or_string.py | 19 +- .../models/nested_union_container.py | 153 ++++++++++++ .../petstore_api/models/one_of_container.py | 229 ++++++++++++++++++ .../petstore_api/models/pig.py | 19 +- .../petstore_api/models/task_activity.py | 19 +- .../test/test_any_of_container.py | 50 ++++ .../test/test_nested_union_container.py | 50 ++++ .../test/test_one_of_container.py | 50 ++++ .../python-httpx/.openapi-generator/FILES | 6 + .../client/petstore/python-httpx/README.md | 3 + .../python-httpx/docs/AnyOfContainer.md | 28 +++ .../python-httpx/docs/NestedUnionContainer.md | 28 +++ .../python-httpx/docs/OneOfContainer.md | 28 +++ .../python-httpx/petstore_api/__init__.py | 6 + .../petstore_api/models/__init__.py | 3 + .../petstore_api/models/any_of_color.py | 28 ++- .../petstore_api/models/any_of_container.py | 225 +++++++++++++++++ .../petstore_api/models/any_of_pig.py | 18 +- .../python-httpx/petstore_api/models/color.py | 29 ++- .../petstore_api/models/int_or_string.py | 19 +- .../models/nested_union_container.py | 153 ++++++++++++ .../petstore_api/models/one_of_container.py | 229 ++++++++++++++++++ .../python-httpx/petstore_api/models/pig.py | 19 +- .../petstore_api/models/task_activity.py | 19 +- .../test/test_any_of_container.py | 50 ++++ .../test/test_nested_union_container.py | 50 ++++ .../test/test_one_of_container.py | 50 ++++ .../.openapi-generator/FILES | 6 + .../petstore/python-httpx2-sync/README.md | 3 + .../python-httpx2-sync/docs/AnyOfContainer.md | 28 +++ .../docs/NestedUnionContainer.md | 28 +++ .../python-httpx2-sync/docs/OneOfContainer.md | 28 +++ .../petstore_api/__init__.py | 6 + .../petstore_api/models/__init__.py | 3 + .../petstore_api/models/any_of_color.py | 28 ++- .../petstore_api/models/any_of_container.py | 225 +++++++++++++++++ .../petstore_api/models/any_of_pig.py | 18 +- .../petstore_api/models/color.py | 29 ++- .../petstore_api/models/int_or_string.py | 19 +- .../models/nested_union_container.py | 153 ++++++++++++ .../petstore_api/models/one_of_container.py | 229 ++++++++++++++++++ .../petstore_api/models/pig.py | 19 +- .../petstore_api/models/task_activity.py | 19 +- .../test/test_any_of_container.py | 50 ++++ .../test/test_nested_union_container.py | 50 ++++ .../test/test_one_of_container.py | 50 ++++ .../python-httpx2/.openapi-generator/FILES | 6 + .../client/petstore/python-httpx2/README.md | 3 + .../python-httpx2/docs/AnyOfContainer.md | 28 +++ .../docs/NestedUnionContainer.md | 28 +++ .../python-httpx2/docs/OneOfContainer.md | 28 +++ .../python-httpx2/petstore_api/__init__.py | 6 + .../petstore_api/models/__init__.py | 3 + .../petstore_api/models/any_of_color.py | 28 ++- .../petstore_api/models/any_of_container.py | 225 +++++++++++++++++ .../petstore_api/models/any_of_pig.py | 18 +- .../petstore_api/models/color.py | 29 ++- .../petstore_api/models/int_or_string.py | 19 +- .../models/nested_union_container.py | 153 ++++++++++++ .../petstore_api/models/one_of_container.py | 229 ++++++++++++++++++ .../python-httpx2/petstore_api/models/pig.py | 19 +- .../petstore_api/models/task_activity.py | 19 +- .../test/test_any_of_container.py | 50 ++++ .../test/test_nested_union_container.py | 50 ++++ .../test/test_one_of_container.py | 50 ++++ .../.openapi-generator/FILES | 6 + .../petstore/python-lazyImports/README.md | 3 + .../python-lazyImports/docs/AnyOfContainer.md | 28 +++ .../docs/NestedUnionContainer.md | 28 +++ .../python-lazyImports/docs/OneOfContainer.md | 28 +++ .../petstore_api/__init__.py | 9 + .../petstore_api/models/__init__.py | 9 + .../petstore_api/models/any_of_color.py | 28 ++- .../petstore_api/models/any_of_container.py | 225 +++++++++++++++++ .../petstore_api/models/any_of_pig.py | 18 +- .../petstore_api/models/color.py | 29 ++- .../petstore_api/models/int_or_string.py | 19 +- .../models/nested_union_container.py | 153 ++++++++++++ .../petstore_api/models/one_of_container.py | 229 ++++++++++++++++++ .../petstore_api/models/one_of_enum_string.py | 19 +- .../petstore_api/models/pig.py | 19 +- .../petstore_api/models/task_activity.py | 19 +- .../test/test_any_of_container.py | 50 ++++ .../test/test_nested_union_container.py | 50 ++++ .../test/test_one_of_container.py | 50 ++++ .../.openapi-generator/FILES | 6 + .../python-pydantic-v1-aiohttp/README.md | 3 + .../docs/AnyOfContainer.md | 27 +++ .../docs/NestedUnionContainer.md | 27 +++ .../docs/OneOfContainer.md | 27 +++ .../petstore_api/__init__.py | 6 + .../petstore_api/models/__init__.py | 3 + .../petstore_api/models/any_of_container.py | 210 ++++++++++++++++ .../models/nested_union_container.py | 148 +++++++++++ .../petstore_api/models/one_of_container.py | 218 +++++++++++++++++ .../test/test_any_of_container.py | 51 ++++ .../test/test_nested_union_container.py | 51 ++++ .../test/test_one_of_container.py | 51 ++++ .../.openapi-generator/FILES | 6 + .../petstore/python-pydantic-v1/README.md | 3 + .../python-pydantic-v1/docs/AnyOfContainer.md | 27 +++ .../docs/NestedUnionContainer.md | 27 +++ .../python-pydantic-v1/docs/OneOfContainer.md | 27 +++ .../petstore_api/__init__.py | 6 + .../petstore_api/models/__init__.py | 3 + .../petstore_api/models/any_of_container.py | 210 ++++++++++++++++ .../models/nested_union_container.py | 148 +++++++++++ .../petstore_api/models/one_of_container.py | 218 +++++++++++++++++ .../test/test_any_of_container.py | 51 ++++ .../test/test_nested_union_container.py | 51 ++++ .../test/test_one_of_container.py | 51 ++++ .../petstore/python/.openapi-generator/FILES | 6 + .../openapi3/client/petstore/python/README.md | 3 + .../petstore/python/docs/AnyOfContainer.md | 28 +++ .../python/docs/NestedUnionContainer.md | 28 +++ .../petstore/python/docs/OneOfContainer.md | 28 +++ .../petstore/python/petstore_api/__init__.py | 6 + .../python/petstore_api/models/__init__.py | 3 + .../petstore_api/models/any_of_color.py | 28 ++- .../petstore_api/models/any_of_container.py | 225 +++++++++++++++++ .../python/petstore_api/models/any_of_pig.py | 18 +- .../python/petstore_api/models/color.py | 29 ++- .../petstore_api/models/int_or_string.py | 19 +- .../models/nested_union_container.py | 153 ++++++++++++ .../petstore_api/models/one_of_container.py | 229 ++++++++++++++++++ .../petstore_api/models/one_of_enum_string.py | 19 +- .../python/petstore_api/models/pig.py | 19 +- .../petstore_api/models/task_activity.py | 19 +- .../python/test/test_any_of_container.py | 50 ++++ .../test/test_nested_union_container.py | 50 ++++ .../python/test/test_one_of_container.py | 50 ++++ .../python/tests/test_union_containers.py | 72 ++++++ 169 files changed, 8558 insertions(+), 331 deletions(-) create mode 100644 modules/openapi-generator/src/main/resources/python/_composed_model_dict.mustache create mode 100644 samples/openapi3/client/petstore/python-aiohttp/docs/AnyOfContainer.md create mode 100644 samples/openapi3/client/petstore/python-aiohttp/docs/NestedUnionContainer.md create mode 100644 samples/openapi3/client/petstore/python-aiohttp/docs/OneOfContainer.md create mode 100644 samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/any_of_container.py create mode 100644 samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/nested_union_container.py create mode 100644 samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/one_of_container.py create mode 100644 samples/openapi3/client/petstore/python-aiohttp/test/test_any_of_container.py create mode 100644 samples/openapi3/client/petstore/python-aiohttp/test/test_nested_union_container.py create mode 100644 samples/openapi3/client/petstore/python-aiohttp/test/test_one_of_container.py create mode 100644 samples/openapi3/client/petstore/python-httpx-sync/docs/AnyOfContainer.md create mode 100644 samples/openapi3/client/petstore/python-httpx-sync/docs/NestedUnionContainer.md create mode 100644 samples/openapi3/client/petstore/python-httpx-sync/docs/OneOfContainer.md create mode 100644 samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/any_of_container.py create mode 100644 samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/nested_union_container.py create mode 100644 samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/one_of_container.py create mode 100644 samples/openapi3/client/petstore/python-httpx-sync/test/test_any_of_container.py create mode 100644 samples/openapi3/client/petstore/python-httpx-sync/test/test_nested_union_container.py create mode 100644 samples/openapi3/client/petstore/python-httpx-sync/test/test_one_of_container.py create mode 100644 samples/openapi3/client/petstore/python-httpx/docs/AnyOfContainer.md create mode 100644 samples/openapi3/client/petstore/python-httpx/docs/NestedUnionContainer.md create mode 100644 samples/openapi3/client/petstore/python-httpx/docs/OneOfContainer.md create mode 100644 samples/openapi3/client/petstore/python-httpx/petstore_api/models/any_of_container.py create mode 100644 samples/openapi3/client/petstore/python-httpx/petstore_api/models/nested_union_container.py create mode 100644 samples/openapi3/client/petstore/python-httpx/petstore_api/models/one_of_container.py create mode 100644 samples/openapi3/client/petstore/python-httpx/test/test_any_of_container.py create mode 100644 samples/openapi3/client/petstore/python-httpx/test/test_nested_union_container.py create mode 100644 samples/openapi3/client/petstore/python-httpx/test/test_one_of_container.py create mode 100644 samples/openapi3/client/petstore/python-httpx2-sync/docs/AnyOfContainer.md create mode 100644 samples/openapi3/client/petstore/python-httpx2-sync/docs/NestedUnionContainer.md create mode 100644 samples/openapi3/client/petstore/python-httpx2-sync/docs/OneOfContainer.md create mode 100644 samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/any_of_container.py create mode 100644 samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/nested_union_container.py create mode 100644 samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/one_of_container.py create mode 100644 samples/openapi3/client/petstore/python-httpx2-sync/test/test_any_of_container.py create mode 100644 samples/openapi3/client/petstore/python-httpx2-sync/test/test_nested_union_container.py create mode 100644 samples/openapi3/client/petstore/python-httpx2-sync/test/test_one_of_container.py create mode 100644 samples/openapi3/client/petstore/python-httpx2/docs/AnyOfContainer.md create mode 100644 samples/openapi3/client/petstore/python-httpx2/docs/NestedUnionContainer.md create mode 100644 samples/openapi3/client/petstore/python-httpx2/docs/OneOfContainer.md create mode 100644 samples/openapi3/client/petstore/python-httpx2/petstore_api/models/any_of_container.py create mode 100644 samples/openapi3/client/petstore/python-httpx2/petstore_api/models/nested_union_container.py create mode 100644 samples/openapi3/client/petstore/python-httpx2/petstore_api/models/one_of_container.py create mode 100644 samples/openapi3/client/petstore/python-httpx2/test/test_any_of_container.py create mode 100644 samples/openapi3/client/petstore/python-httpx2/test/test_nested_union_container.py create mode 100644 samples/openapi3/client/petstore/python-httpx2/test/test_one_of_container.py create mode 100644 samples/openapi3/client/petstore/python-lazyImports/docs/AnyOfContainer.md create mode 100644 samples/openapi3/client/petstore/python-lazyImports/docs/NestedUnionContainer.md create mode 100644 samples/openapi3/client/petstore/python-lazyImports/docs/OneOfContainer.md create mode 100644 samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/any_of_container.py create mode 100644 samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/nested_union_container.py create mode 100644 samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/one_of_container.py create mode 100644 samples/openapi3/client/petstore/python-lazyImports/test/test_any_of_container.py create mode 100644 samples/openapi3/client/petstore/python-lazyImports/test/test_nested_union_container.py create mode 100644 samples/openapi3/client/petstore/python-lazyImports/test/test_one_of_container.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/AnyOfContainer.md create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/NestedUnionContainer.md create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/OneOfContainer.md create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/any_of_container.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/nested_union_container.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/one_of_container.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_any_of_container.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_nested_union_container.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_one_of_container.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1/docs/AnyOfContainer.md create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1/docs/NestedUnionContainer.md create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1/docs/OneOfContainer.md create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/any_of_container.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/nested_union_container.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/one_of_container.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1/test/test_any_of_container.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1/test/test_nested_union_container.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1/test/test_one_of_container.py create mode 100644 samples/openapi3/client/petstore/python/docs/AnyOfContainer.md create mode 100644 samples/openapi3/client/petstore/python/docs/NestedUnionContainer.md create mode 100644 samples/openapi3/client/petstore/python/docs/OneOfContainer.md create mode 100644 samples/openapi3/client/petstore/python/petstore_api/models/any_of_container.py create mode 100644 samples/openapi3/client/petstore/python/petstore_api/models/nested_union_container.py create mode 100644 samples/openapi3/client/petstore/python/petstore_api/models/one_of_container.py create mode 100644 samples/openapi3/client/petstore/python/test/test_any_of_container.py create mode 100644 samples/openapi3/client/petstore/python/test/test_nested_union_container.py create mode 100644 samples/openapi3/client/petstore/python/test/test_one_of_container.py create mode 100644 samples/openapi3/client/petstore/python/tests/test_union_containers.py 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 ce8ca4bcef37..3c74f4442ed6 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 @@ -726,9 +726,31 @@ public Map postProcessAllModels(Map objs) } Map processed = super.postProcessAllModels(objs); + Set composedModels = new HashSet<>(); for (ModelsMap modelsMap : processed.values()) { for (ModelMap modelMap : modelsMap.getModels()) { CodegenModel model = modelMap.getModel(); + if (model != null && (hasOneOf(model) || hasAnyOf(model))) { + composedModels.add(model.classname); + } + } + } + for (ModelsMap modelsMap : processed.values()) { + for (ModelMap modelMap : modelsMap.getModels()) { + CodegenModel model = modelMap.getModel(); + if (model != null && (hasOneOf(model) || hasAnyOf(model))) { + List alternatives = hasOneOf(model) + ? model.getComposedSchemas().getOneOf() + : model.getComposedSchemas().getAnyOf(); + for (CodegenProperty property : alternatives) { + if (property.isContainer) { + String expression = fromDictExpression(property, "data", 0, composedModels); + if (!expression.equals("data")) { + property.vendorExtensions.put("x-py-from-dict", expression); + } + } + } + } if (model != null && model.oneOf.isEmpty() && model.anyOf.isEmpty()) { for (CodegenProperty property : model.vars) { if (property.vendorExtensions.containsKey( @@ -751,6 +773,35 @@ public Map postProcessAllModels(Map objs) return processed; } + private String fromDictExpression(CodegenProperty property, String value, int depth, + Set composedModels) { + String item = "_item" + depth; + if (property.isContainer && property.items != null) { + String expression = fromDictExpression(property.items, item, depth + 1, composedModels); + if (expression.equals(item)) { + return value; + } + if (property.isArray) { + return "([" + expression + + " for " + item + " in " + value + "] if isinstance(" + value + + ", list) else " + value + ")"; + } + if (property.isMap) { + String key = "_key" + depth; + return "({" + key + ": " + expression + + " for " + key + ", " + item + " in " + value + ".items()} if isinstance(" + + value + ", dict) else " + value + ")"; + } + } + // Pydantic cannot decode raw values into the generated union wrappers. + // Ordinary models must retain Pydantic's existing defaults/field presence. + if (composedModels.contains(property.dataType)) { + return "(" + property.dataType + ".from_dict(" + value + ") if " + + value + " is not None else None)"; + } + return value; + } + private void configurePublicNameInputs(List properties) { for (CodegenProperty property : properties) { String publicName = (String) property.vendorExtensions.getOrDefault( diff --git a/modules/openapi-generator/src/main/resources/python/_composed_model_dict.mustache b/modules/openapi-generator/src/main/resources/python/_composed_model_dict.mustache new file mode 100644 index 000000000000..77a61815b967 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/_composed_model_dict.mustache @@ -0,0 +1,9 @@ +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + diff --git a/modules/openapi-generator/src/main/resources/python/model_anyof.mustache b/modules/openapi-generator/src/main/resources/python/model_anyof.mustache index 7a7f52f755a0..e817f4430fd6 100644 --- a/modules/openapi-generator/src/main/resources/python/model_anyof.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_anyof.mustache @@ -12,12 +12,16 @@ import re # noqa: F401 from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict from typing_extensions import Literal, Self from pydantic import Field -{{#compatibleWithPythonLegacy}} from pydantic_core import to_jsonable_python +{{#compatibleWithPythonLegacy}} {{>_legacy_model_dict_helpers}} +{{/compatibleWithPythonLegacy}} +{{^compatibleWithPythonLegacy}} + +{{>_composed_model_dict}} {{/compatibleWithPythonLegacy}} {{#lambda.uppercase}}{{{classname}}}{{/lambda.uppercase}}_ANY_OF_SCHEMAS = [{{#anyOf}}"{{.}}"{{^-last}}, {{/-last}}{{/anyOf}}] @@ -119,12 +123,16 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} {{#isContainer}} # deserialize data into {{{dataType}}} try: + data = json.loads(json_str) + {{#vendorExtensions.x-py-from-dict}} + data = {{{vendorExtensions.x-py-from-dict}}} + {{/vendorExtensions.x-py-from-dict}} # validation - instance.{{vendorExtensions.x-py-name}} = json.loads(json_str) + instance.{{vendorExtensions.x-py-name}} = data # assign value to actual_instance instance.actual_instance = instance.{{vendorExtensions.x-py-name}} return instance - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) {{/isContainer}} {{^isContainer}} @@ -172,7 +180,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} {{/compatibleWithPythonLegacy}} {{^compatibleWithPythonLegacy}} else: - return json.dumps(self.actual_instance) + return json.dumps(to_jsonable_python(self.to_dict())) {{/compatibleWithPythonLegacy}} {{#compatibleWithPythonLegacy}} @@ -198,10 +206,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} 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: - return self.actual_instance + return _to_dict(self.actual_instance) {{/compatibleWithPythonLegacy}} def to_str(self) -> str: diff --git a/modules/openapi-generator/src/main/resources/python/model_oneof.mustache b/modules/openapi-generator/src/main/resources/python/model_oneof.mustache index 8365ae0bb61f..e84093095187 100644 --- a/modules/openapi-generator/src/main/resources/python/model_oneof.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_oneof.mustache @@ -10,12 +10,16 @@ import pprint from pydantic import StrictStr, Field from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self -{{#compatibleWithPythonLegacy}} from pydantic_core import to_jsonable_python +{{#compatibleWithPythonLegacy}} {{>_legacy_model_dict_helpers}} +{{/compatibleWithPythonLegacy}} +{{^compatibleWithPythonLegacy}} + +{{>_composed_model_dict}} {{/compatibleWithPythonLegacy}} {{#lambda.uppercase}}{{{classname}}}{{/lambda.uppercase}}_ONE_OF_SCHEMAS = [{{#oneOf}}"{{.}}"{{^-last}}, {{/-last}}{{/oneOf}}] @@ -143,12 +147,16 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} {{#isContainer}} # deserialize data into {{{dataType}}} try: + data = json.loads(json_str) + {{#vendorExtensions.x-py-from-dict}} + data = {{{vendorExtensions.x-py-from-dict}}} + {{/vendorExtensions.x-py-from-dict}} # validation - instance.{{vendorExtensions.x-py-name}} = json.loads(json_str) + instance.{{vendorExtensions.x-py-name}} = data # assign value to actual_instance instance.actual_instance = instance.{{vendorExtensions.x-py-name}} match += 1 - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) {{/isContainer}} {{^isContainer}} @@ -199,7 +207,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} {{/compatibleWithPythonLegacy}} {{^compatibleWithPythonLegacy}} else: - return json.dumps(self.actual_instance) + return json.dumps(to_jsonable_python(self.to_dict())) {{/compatibleWithPythonLegacy}} {{#compatibleWithPythonLegacy}} @@ -225,11 +233,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} 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 + return _to_dict(self.actual_instance) {{/compatibleWithPythonLegacy}} def to_str(self) -> str: 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 427b2b70d7c4..36863c7f4e0b 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 @@ -2579,6 +2579,60 @@ components: $ref: '#/components/schemas/Pig' nested_oneof_enum_string: $ref: '#/components/schemas/OneOfEnumString' + OneOfContainer: + oneOf: + - type: string + - type: array + minItems: 1 + items: + $ref: '#/components/schemas/Pig' + - type: object + additionalProperties: + $ref: '#/components/schemas/Pig' + - type: array + minItems: 1 + items: + type: integer + - type: array + minItems: 1 + items: + $ref: '#/components/schemas/EnumString1' + - type: array + minItems: 1 + items: + $ref: '#/components/schemas/NullableClass' + AnyOfContainer: + anyOf: + - type: string + - type: array + minItems: 1 + items: + $ref: '#/components/schemas/AnyOfPig' + - type: object + additionalProperties: + $ref: '#/components/schemas/AnyOfPig' + - type: array + minItems: 1 + items: + type: integer + - type: array + minItems: 1 + items: + $ref: '#/components/schemas/EnumString1' + - type: array + minItems: 1 + items: + $ref: '#/components/schemas/NullableClass' + NestedUnionContainer: + oneOf: + - type: string + - type: array + items: + type: object + additionalProperties: + type: array + items: + $ref: '#/components/schemas/Pig' Self-Reference-Model: type: object properties: diff --git a/samples/client/others/python-legacy-model-dictionaries/legacy_model_dict_client/models/any_of_model.py b/samples/client/others/python-legacy-model-dictionaries/legacy_model_dict_client/models/any_of_model.py index a3bf6fd9d696..b8380e36bdbf 100644 --- a/samples/client/others/python-legacy-model-dictionaries/legacy_model_dict_client/models/any_of_model.py +++ b/samples/client/others/python-legacy-model-dictionaries/legacy_model_dict_client/models/any_of_model.py @@ -182,21 +182,23 @@ def from_json(cls, json_str: str) -> Self: error_messages.append(str(e)) # deserialize data into List[NestedModel] try: + data = json.loads(json_str) # validation - instance.anyof_schema_2_validator = json.loads(json_str) + instance.anyof_schema_2_validator = data # assign value to actual_instance instance.actual_instance = instance.anyof_schema_2_validator return instance - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) # deserialize data into Dict[str, NestedModel] try: + data = json.loads(json_str) # validation - instance.anyof_schema_3_validator = json.loads(json_str) + instance.anyof_schema_3_validator = data # assign value to actual_instance instance.actual_instance = instance.anyof_schema_3_validator return instance - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) # deserialize data into str try: diff --git a/samples/client/others/python-legacy-model-dictionaries/legacy_model_dict_client/models/one_of_model.py b/samples/client/others/python-legacy-model-dictionaries/legacy_model_dict_client/models/one_of_model.py index 57bebc2c3e6e..baa8ba3194c0 100644 --- a/samples/client/others/python-legacy-model-dictionaries/legacy_model_dict_client/models/one_of_model.py +++ b/samples/client/others/python-legacy-model-dictionaries/legacy_model_dict_client/models/one_of_model.py @@ -182,21 +182,23 @@ def from_json(cls, json_str: str) -> Self: error_messages.append(str(e)) # deserialize data into List[NestedModel] try: + data = json.loads(json_str) # validation - instance.oneof_schema_2_validator = json.loads(json_str) + instance.oneof_schema_2_validator = data # assign value to actual_instance instance.actual_instance = instance.oneof_schema_2_validator match += 1 - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) # deserialize data into Dict[str, NestedModel] try: + data = json.loads(json_str) # validation - instance.oneof_schema_3_validator = json.loads(json_str) + instance.oneof_schema_3_validator = data # assign value to actual_instance instance.actual_instance = instance.oneof_schema_3_validator match += 1 - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) # deserialize data into str try: diff --git a/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/FILES b/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/FILES index 1eb565d74f11..6af8faf4dffe 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/FILES @@ -12,6 +12,7 @@ docs/AllOfWithSingleRef.md docs/Animal.md docs/AnotherFakeApi.md docs/AnyOfColor.md +docs/AnyOfContainer.md docs/AnyOfPig.md docs/ArrayOfArrayOfModel.md docs/ArrayOfArrayOfNumberOnly.md @@ -74,11 +75,13 @@ docs/ModelField.md docs/ModelReturn.md docs/MultiArrays.md docs/Name.md +docs/NestedUnionContainer.md docs/NullableClass.md docs/NullableProperty.md docs/NumberOnly.md docs/ObjectToTestAdditionalProperties.md docs/ObjectWithDeprecatedFields.md +docs/OneOfContainer.md docs/OneOfEnumString.md docs/Order.md docs/OuterComposite.md @@ -149,6 +152,7 @@ petstore_api/models/all_of_super_model.py petstore_api/models/all_of_with_single_ref.py petstore_api/models/animal.py petstore_api/models/any_of_color.py +petstore_api/models/any_of_container.py petstore_api/models/any_of_pig.py petstore_api/models/array_of_array_of_model.py petstore_api/models/array_of_array_of_number_only.py @@ -207,11 +211,13 @@ petstore_api/models/model_field.py petstore_api/models/model_return.py petstore_api/models/multi_arrays.py petstore_api/models/name.py +petstore_api/models/nested_union_container.py petstore_api/models/nullable_class.py petstore_api/models/nullable_property.py petstore_api/models/number_only.py petstore_api/models/object_to_test_additional_properties.py petstore_api/models/object_with_deprecated_fields.py +petstore_api/models/one_of_container.py petstore_api/models/one_of_enum_string.py petstore_api/models/order.py petstore_api/models/outer_composite.py diff --git a/samples/openapi3/client/petstore/python-aiohttp/README.md b/samples/openapi3/client/petstore/python-aiohttp/README.md index 17a693587c53..beb51bce6cca 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/README.md +++ b/samples/openapi3/client/petstore/python-aiohttp/README.md @@ -186,6 +186,7 @@ Class | Method | HTTP request | Description - [AllOfWithSingleRef](docs/AllOfWithSingleRef.md) - [Animal](docs/Animal.md) - [AnyOfColor](docs/AnyOfColor.md) + - [AnyOfContainer](docs/AnyOfContainer.md) - [AnyOfPig](docs/AnyOfPig.md) - [ArrayOfArrayOfModel](docs/ArrayOfArrayOfModel.md) - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) @@ -244,11 +245,13 @@ Class | Method | HTTP request | Description - [ModelReturn](docs/ModelReturn.md) - [MultiArrays](docs/MultiArrays.md) - [Name](docs/Name.md) + - [NestedUnionContainer](docs/NestedUnionContainer.md) - [NullableClass](docs/NullableClass.md) - [NullableProperty](docs/NullableProperty.md) - [NumberOnly](docs/NumberOnly.md) - [ObjectToTestAdditionalProperties](docs/ObjectToTestAdditionalProperties.md) - [ObjectWithDeprecatedFields](docs/ObjectWithDeprecatedFields.md) + - [OneOfContainer](docs/OneOfContainer.md) - [OneOfEnumString](docs/OneOfEnumString.md) - [Order](docs/Order.md) - [OuterComposite](docs/OuterComposite.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/AnyOfContainer.md b/samples/openapi3/client/petstore/python-aiohttp/docs/AnyOfContainer.md new file mode 100644 index 000000000000..4644b55530c7 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/AnyOfContainer.md @@ -0,0 +1,28 @@ +# AnyOfContainer + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +```python +from petstore_api.models.any_of_container import AnyOfContainer + +# TODO update the JSON string below +json = "{}" +# create an instance of AnyOfContainer from a JSON string +any_of_container_instance = AnyOfContainer.from_json(json) +# print the JSON string representation of the object +print(AnyOfContainer.to_json()) + +# convert the object into a dict +any_of_container_dict = any_of_container_instance.to_dict() +# create an instance of AnyOfContainer from a dict +any_of_container_from_dict = AnyOfContainer.from_dict(any_of_container_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/NestedUnionContainer.md b/samples/openapi3/client/petstore/python-aiohttp/docs/NestedUnionContainer.md new file mode 100644 index 000000000000..9cf24bc0668a --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/NestedUnionContainer.md @@ -0,0 +1,28 @@ +# NestedUnionContainer + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +```python +from petstore_api.models.nested_union_container import NestedUnionContainer + +# TODO update the JSON string below +json = "{}" +# create an instance of NestedUnionContainer from a JSON string +nested_union_container_instance = NestedUnionContainer.from_json(json) +# print the JSON string representation of the object +print(NestedUnionContainer.to_json()) + +# convert the object into a dict +nested_union_container_dict = nested_union_container_instance.to_dict() +# create an instance of NestedUnionContainer from a dict +nested_union_container_from_dict = NestedUnionContainer.from_dict(nested_union_container_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/OneOfContainer.md b/samples/openapi3/client/petstore/python-aiohttp/docs/OneOfContainer.md new file mode 100644 index 000000000000..50d13d3399ac --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/OneOfContainer.md @@ -0,0 +1,28 @@ +# OneOfContainer + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +```python +from petstore_api.models.one_of_container import OneOfContainer + +# TODO update the JSON string below +json = "{}" +# create an instance of OneOfContainer from a JSON string +one_of_container_instance = OneOfContainer.from_json(json) +# print the JSON string representation of the object +print(OneOfContainer.to_json()) + +# convert the object into a dict +one_of_container_dict = one_of_container_instance.to_dict() +# create an instance of OneOfContainer from a dict +one_of_container_from_dict = OneOfContainer.from_dict(one_of_container_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 c7f461775f59..341a3e34513b 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/__init__.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/__init__.py @@ -44,6 +44,7 @@ "AllOfWithSingleRef", "Animal", "AnyOfColor", + "AnyOfContainer", "AnyOfPig", "ArrayOfArrayOfModel", "ArrayOfArrayOfNumberOnly", @@ -102,11 +103,13 @@ "ModelReturn", "MultiArrays", "Name", + "NestedUnionContainer", "NullableClass", "NullableProperty", "NumberOnly", "ObjectToTestAdditionalProperties", "ObjectWithDeprecatedFields", + "OneOfContainer", "OneOfEnumString", "Order", "OuterComposite", @@ -183,6 +186,7 @@ from petstore_api.models.all_of_with_single_ref import AllOfWithSingleRef as AllOfWithSingleRef from petstore_api.models.animal import Animal as Animal from petstore_api.models.any_of_color import AnyOfColor as AnyOfColor +from petstore_api.models.any_of_container import AnyOfContainer as AnyOfContainer from petstore_api.models.any_of_pig import AnyOfPig as AnyOfPig from petstore_api.models.array_of_array_of_model import ArrayOfArrayOfModel as ArrayOfArrayOfModel from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly as ArrayOfArrayOfNumberOnly @@ -241,11 +245,13 @@ from petstore_api.models.model_return import ModelReturn as ModelReturn from petstore_api.models.multi_arrays import MultiArrays as MultiArrays from petstore_api.models.name import Name as Name +from petstore_api.models.nested_union_container import NestedUnionContainer as NestedUnionContainer from petstore_api.models.nullable_class import NullableClass as NullableClass from petstore_api.models.nullable_property import NullableProperty as NullableProperty from petstore_api.models.number_only import NumberOnly as NumberOnly from petstore_api.models.object_to_test_additional_properties import ObjectToTestAdditionalProperties as ObjectToTestAdditionalProperties from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields as ObjectWithDeprecatedFields +from petstore_api.models.one_of_container import OneOfContainer as OneOfContainer 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.outer_composite import OuterComposite as OuterComposite 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 308e6dfc3ebb..336021dd171d 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 @@ -21,6 +21,7 @@ from petstore_api.models.all_of_with_single_ref import AllOfWithSingleRef from petstore_api.models.animal import Animal from petstore_api.models.any_of_color import AnyOfColor +from petstore_api.models.any_of_container import AnyOfContainer from petstore_api.models.any_of_pig import AnyOfPig from petstore_api.models.array_of_array_of_model import ArrayOfArrayOfModel from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly @@ -79,11 +80,13 @@ from petstore_api.models.model_return import ModelReturn from petstore_api.models.multi_arrays import MultiArrays from petstore_api.models.name import Name +from petstore_api.models.nested_union_container import NestedUnionContainer from petstore_api.models.nullable_class import NullableClass from petstore_api.models.nullable_property import NullableProperty from petstore_api.models.number_only import NumberOnly from petstore_api.models.object_to_test_additional_properties import ObjectToTestAdditionalProperties from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields +from petstore_api.models.one_of_container import OneOfContainer from petstore_api.models.one_of_enum_string import OneOfEnumString from petstore_api.models.order import Order from petstore_api.models.outer_composite import OuterComposite diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/any_of_color.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/any_of_color.py index f6d277e79498..80858f210971 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/any_of_color.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/any_of_color.py @@ -23,6 +23,17 @@ from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict from typing_extensions import Literal, Self from pydantic import Field +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + ANYOFCOLOR_ANY_OF_SCHEMAS = ["List[int]", "str"] @@ -97,21 +108,23 @@ def from_json(cls, json_str: str) -> Self: error_messages = [] # deserialize data into List[int] try: + data = json.loads(json_str) # validation - instance.anyof_schema_1_validator = json.loads(json_str) + instance.anyof_schema_1_validator = data # assign value to actual_instance instance.actual_instance = instance.anyof_schema_1_validator return instance - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) # deserialize data into List[int] try: + data = json.loads(json_str) # validation - instance.anyof_schema_2_validator = json.loads(json_str) + instance.anyof_schema_2_validator = data # assign value to actual_instance instance.actual_instance = instance.anyof_schema_2_validator return instance - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) # deserialize data into str try: @@ -137,17 +150,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], List[int], str]]: """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: - return self.actual_instance + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/any_of_container.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/any_of_container.py new file mode 100644 index 000000000000..534b12f2dbb3 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/any_of_container.py @@ -0,0 +1,225 @@ +# 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 pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr, ValidationError, field_validator +from typing import Dict, List, Optional +from typing_extensions import Annotated +from petstore_api.models.any_of_pig import AnyOfPig +from petstore_api.models.enum_string1 import EnumString1 +from petstore_api.models.nullable_class import NullableClass +from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict +from typing_extensions import Literal, Self +from pydantic import Field +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + + +ANYOFCONTAINER_ANY_OF_SCHEMAS = ["Dict[str, AnyOfPig]", "List[AnyOfPig]", "List[EnumString1]", "List[NullableClass]", "List[int]", "str"] + +class AnyOfContainer(BaseModel): + """ + AnyOfContainer + """ + + # data type: str + anyof_schema_1_validator: Optional[StrictStr] = None + # data type: List[AnyOfPig] + anyof_schema_2_validator: Optional[Annotated[List[AnyOfPig], Field(min_length=1)]] = None + # data type: Dict[str, AnyOfPig] + anyof_schema_3_validator: Optional[Dict[str, AnyOfPig]] = None + # data type: List[int] + anyof_schema_4_validator: Optional[Annotated[List[StrictInt], Field(min_length=1)]] = None + # data type: List[EnumString1] + anyof_schema_5_validator: Optional[Annotated[List[EnumString1], Field(min_length=1)]] = None + # data type: List[NullableClass] + anyof_schema_6_validator: Optional[Annotated[List[NullableClass], Field(min_length=1)]] = None + if TYPE_CHECKING: + actual_instance: Optional[Union[Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str]] = None + else: + actual_instance: Any = None + any_of_schemas: Set[str] = { "Dict[str, AnyOfPig]", "List[AnyOfPig]", "List[EnumString1]", "List[NullableClass]", "List[int]", "str" } + + model_config = { + "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_anyof(cls, v): + instance = AnyOfContainer.model_construct() + error_messages = [] + # validate data type: str + try: + instance.anyof_schema_1_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[AnyOfPig] + try: + instance.anyof_schema_2_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: Dict[str, AnyOfPig] + try: + instance.anyof_schema_3_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[int] + try: + instance.anyof_schema_4_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[EnumString1] + try: + instance.anyof_schema_5_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[NullableClass] + try: + instance.anyof_schema_6_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + if error_messages: + # no match + raise ValueError("No match found when setting the actual_instance in AnyOfContainer with anyOf schemas: Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: 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 = [] + # deserialize data into str + try: + # validation + instance.anyof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_1_validator + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[AnyOfPig] + try: + data = json.loads(json_str) + data = ([(AnyOfPig.from_dict(_item0) if _item0 is not None else None) for _item0 in data] if isinstance(data, list) else data) + # validation + instance.anyof_schema_2_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_2_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into Dict[str, AnyOfPig] + try: + data = json.loads(json_str) + data = ({_key0: (AnyOfPig.from_dict(_item0) if _item0 is not None else None) for _key0, _item0 in data.items()} if isinstance(data, dict) else data) + # validation + instance.anyof_schema_3_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_3_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[int] + try: + data = json.loads(json_str) + # validation + instance.anyof_schema_4_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_4_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[EnumString1] + try: + data = json.loads(json_str) + # validation + instance.anyof_schema_5_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_5_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[NullableClass] + try: + data = json.loads(json_str) + # validation + instance.anyof_schema_6_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_6_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + + if error_messages: + # no match + raise ValueError("No match found when deserializing the JSON string into AnyOfContainer with anyOf schemas: Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str. 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(to_jsonable_python(self.to_dict())) + + def to_dict(self) -> Optional[Union[Dict[str, Any], Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + return _to_dict(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/petstore_api/models/any_of_pig.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/any_of_pig.py index c949e136f415..752848a7d1aa 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/any_of_pig.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/any_of_pig.py @@ -24,6 +24,17 @@ from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict from typing_extensions import Literal, Self from pydantic import Field +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + ANYOFPIG_ANY_OF_SCHEMAS = ["BasquePig", "DanishPig"] @@ -115,17 +126,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], BasquePig, DanishPig]]: """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: - return self.actual_instance + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/color.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/color.py index bb740fb597d4..a05b275ff594 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/color.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/color.py @@ -21,6 +21,17 @@ from pydantic import StrictStr, Field from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + COLOR_ONE_OF_SCHEMAS = ["List[int]", "str"] @@ -104,21 +115,23 @@ def from_json(cls, json_str: Optional[str]) -> Self: # deserialize data into List[int] try: + data = json.loads(json_str) # validation - instance.oneof_schema_1_validator = json.loads(json_str) + instance.oneof_schema_1_validator = data # assign value to actual_instance instance.actual_instance = instance.oneof_schema_1_validator match += 1 - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) # deserialize data into List[int] try: + data = json.loads(json_str) # validation - instance.oneof_schema_2_validator = json.loads(json_str) + instance.oneof_schema_2_validator = data # assign value to actual_instance instance.actual_instance = instance.oneof_schema_2_validator match += 1 - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) # deserialize data into str try: @@ -147,18 +160,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], List[int], str]]: """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 + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/int_or_string.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/int_or_string.py index f2a5a0a2d4a3..21412adc27c3 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/int_or_string.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/int_or_string.py @@ -21,6 +21,17 @@ from pydantic import StrictStr, Field from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + INTORSTRING_ONE_OF_SCHEMAS = ["int", "str"] @@ -124,18 +135,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], int, str]]: """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 + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/nested_union_container.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/nested_union_container.py new file mode 100644 index 000000000000..932f246f15f3 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/nested_union_container.py @@ -0,0 +1,153 @@ +# 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, Dict, List, Optional +from petstore_api.models.pig import Pig +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + + +NESTEDUNIONCONTAINER_ONE_OF_SCHEMAS = ["List[Dict[str, List[Pig]]]", "str"] + +class NestedUnionContainer(BaseModel): + """ + NestedUnionContainer + """ + # data type: str + oneof_schema_1_validator: Optional[StrictStr] = None + # data type: List[Dict[str, List[Pig]]] + oneof_schema_2_validator: Optional[List[Dict[str, List[Pig]]]] = None + actual_instance: Optional[Union[List[Dict[str, List[Pig]]], str]] = None + one_of_schemas: Set[str] = { "List[Dict[str, List[Pig]]]", "str" } + + 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 = NestedUnionContainer.model_construct() + error_messages = [] + match = 0 + # validate data type: str + try: + instance.oneof_schema_1_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[Dict[str, List[Pig]]] + try: + instance.oneof_schema_2_validator = v + 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 setting `actual_instance` in NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. 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 str + try: + # validation + instance.oneof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_1_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[Dict[str, List[Pig]]] + try: + data = json.loads(json_str) + data = ([({_key1: ([(Pig.from_dict(_item2) if _item2 is not None else None) for _item2 in _item1] if isinstance(_item1, list) else _item1) for _key1, _item1 in _item0.items()} if isinstance(_item0, dict) else _item0) for _item0 in data] if isinstance(data, list) else data) + # validation + instance.oneof_schema_2_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_2_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) 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 NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. 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(to_jsonable_python(self.to_dict())) + + def to_dict(self) -> Optional[Union[Dict[str, Any], List[Dict[str, List[Pig]]], str]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + return _to_dict(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/petstore_api/models/one_of_container.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/one_of_container.py new file mode 100644 index 000000000000..2f4e78d7c261 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/one_of_container.py @@ -0,0 +1,229 @@ +# 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, StrictInt, StrictStr, ValidationError, field_validator +from typing import Any, Dict, List, Optional +from typing_extensions import Annotated +from petstore_api.models.enum_string1 import EnumString1 +from petstore_api.models.nullable_class import NullableClass +from petstore_api.models.pig import Pig +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + + +ONEOFCONTAINER_ONE_OF_SCHEMAS = ["Dict[str, Pig]", "List[EnumString1]", "List[NullableClass]", "List[Pig]", "List[int]", "str"] + +class OneOfContainer(BaseModel): + """ + OneOfContainer + """ + # data type: str + oneof_schema_1_validator: Optional[StrictStr] = None + # data type: List[Pig] + oneof_schema_2_validator: Optional[Annotated[List[Pig], Field(min_length=1)]] = None + # data type: Dict[str, Pig] + oneof_schema_3_validator: Optional[Dict[str, Pig]] = None + # data type: List[int] + oneof_schema_4_validator: Optional[Annotated[List[StrictInt], Field(min_length=1)]] = None + # data type: List[EnumString1] + oneof_schema_5_validator: Optional[Annotated[List[EnumString1], Field(min_length=1)]] = None + # data type: List[NullableClass] + oneof_schema_6_validator: Optional[Annotated[List[NullableClass], Field(min_length=1)]] = None + actual_instance: Optional[Union[Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str]] = None + one_of_schemas: Set[str] = { "Dict[str, Pig]", "List[EnumString1]", "List[NullableClass]", "List[Pig]", "List[int]", "str" } + + 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 = OneOfContainer.model_construct() + error_messages = [] + match = 0 + # validate data type: str + try: + instance.oneof_schema_1_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[Pig] + try: + instance.oneof_schema_2_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: Dict[str, Pig] + try: + instance.oneof_schema_3_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[int] + try: + instance.oneof_schema_4_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[EnumString1] + try: + instance.oneof_schema_5_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[NullableClass] + try: + instance.oneof_schema_6_validator = v + 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 setting `actual_instance` in OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. 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 str + try: + # validation + instance.oneof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_1_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[Pig] + try: + data = json.loads(json_str) + data = ([(Pig.from_dict(_item0) if _item0 is not None else None) for _item0 in data] if isinstance(data, list) else data) + # validation + instance.oneof_schema_2_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_2_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into Dict[str, Pig] + try: + data = json.loads(json_str) + data = ({_key0: (Pig.from_dict(_item0) if _item0 is not None else None) for _key0, _item0 in data.items()} if isinstance(data, dict) else data) + # validation + instance.oneof_schema_3_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_3_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[int] + try: + data = json.loads(json_str) + # validation + instance.oneof_schema_4_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_4_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[EnumString1] + try: + data = json.loads(json_str) + # validation + instance.oneof_schema_5_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_5_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[NullableClass] + try: + data = json.loads(json_str) + # validation + instance.oneof_schema_6_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_6_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) 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 OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. 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(to_jsonable_python(self.to_dict())) + + def to_dict(self) -> Optional[Union[Dict[str, Any], Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + return _to_dict(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/petstore_api/models/pig.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/pig.py index b3a759e89b7b..f7bbd59e8a93 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/pig.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/pig.py @@ -22,6 +22,17 @@ from pydantic import StrictStr, Field from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + PIG_ONE_OF_SCHEMAS = ["BasquePig", "DanishPig"] @@ -120,18 +131,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], BasquePig, DanishPig]]: """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 + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/task_activity.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/task_activity.py index cc1e1fc5a60f..9623b22041ea 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/task_activity.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/task_activity.py @@ -23,6 +23,17 @@ from pydantic import StrictStr, Field from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + TASKACTIVITY_ONE_OF_SCHEMAS = ["Bathing", "Feeding", "PoopCleaning"] @@ -131,18 +142,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], Bathing, Feeding, PoopCleaning]]: """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 + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-aiohttp/test/test_any_of_container.py b/samples/openapi3/client/petstore/python-aiohttp/test/test_any_of_container.py new file mode 100644 index 000000000000..3246e1519768 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/test/test_any_of_container.py @@ -0,0 +1,50 @@ +# 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.any_of_container import AnyOfContainer + +class TestAnyOfContainer(unittest.TestCase): + """AnyOfContainer unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> AnyOfContainer: + """Test AnyOfContainer + 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 `AnyOfContainer` + """ + model = AnyOfContainer() + if include_optional: + return AnyOfContainer( + ) + else: + return AnyOfContainer( + ) + """ + + def testAnyOfContainer(self): + """Test AnyOfContainer""" + # 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_nested_union_container.py b/samples/openapi3/client/petstore/python-aiohttp/test/test_nested_union_container.py new file mode 100644 index 000000000000..44901af90110 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/test/test_nested_union_container.py @@ -0,0 +1,50 @@ +# 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.nested_union_container import NestedUnionContainer + +class TestNestedUnionContainer(unittest.TestCase): + """NestedUnionContainer unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> NestedUnionContainer: + """Test NestedUnionContainer + 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 `NestedUnionContainer` + """ + model = NestedUnionContainer() + if include_optional: + return NestedUnionContainer( + ) + else: + return NestedUnionContainer( + ) + """ + + def testNestedUnionContainer(self): + """Test NestedUnionContainer""" + # 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_one_of_container.py b/samples/openapi3/client/petstore/python-aiohttp/test/test_one_of_container.py new file mode 100644 index 000000000000..12ab6d654e43 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/test/test_one_of_container.py @@ -0,0 +1,50 @@ +# 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.one_of_container import OneOfContainer + +class TestOneOfContainer(unittest.TestCase): + """OneOfContainer unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> OneOfContainer: + """Test OneOfContainer + 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 `OneOfContainer` + """ + model = OneOfContainer() + if include_optional: + return OneOfContainer( + ) + else: + return OneOfContainer( + ) + """ + + def testOneOfContainer(self): + """Test OneOfContainer""" + # 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 463307488f33..2f0e4d89347f 100644 --- a/samples/openapi3/client/petstore/python-httpx-sync/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python-httpx-sync/.openapi-generator/FILES @@ -12,6 +12,7 @@ docs/AllOfWithSingleRef.md docs/Animal.md docs/AnotherFakeApi.md docs/AnyOfColor.md +docs/AnyOfContainer.md docs/AnyOfPig.md docs/ArrayOfArrayOfModel.md docs/ArrayOfArrayOfNumberOnly.md @@ -74,11 +75,13 @@ docs/ModelField.md docs/ModelReturn.md docs/MultiArrays.md docs/Name.md +docs/NestedUnionContainer.md docs/NullableClass.md docs/NullableProperty.md docs/NumberOnly.md docs/ObjectToTestAdditionalProperties.md docs/ObjectWithDeprecatedFields.md +docs/OneOfContainer.md docs/OneOfEnumString.md docs/Order.md docs/OuterComposite.md @@ -149,6 +152,7 @@ petstore_api/models/all_of_super_model.py petstore_api/models/all_of_with_single_ref.py petstore_api/models/animal.py petstore_api/models/any_of_color.py +petstore_api/models/any_of_container.py petstore_api/models/any_of_pig.py petstore_api/models/array_of_array_of_model.py petstore_api/models/array_of_array_of_number_only.py @@ -207,11 +211,13 @@ petstore_api/models/model_field.py petstore_api/models/model_return.py petstore_api/models/multi_arrays.py petstore_api/models/name.py +petstore_api/models/nested_union_container.py petstore_api/models/nullable_class.py petstore_api/models/nullable_property.py petstore_api/models/number_only.py petstore_api/models/object_to_test_additional_properties.py petstore_api/models/object_with_deprecated_fields.py +petstore_api/models/one_of_container.py petstore_api/models/one_of_enum_string.py petstore_api/models/order.py petstore_api/models/outer_composite.py diff --git a/samples/openapi3/client/petstore/python-httpx-sync/README.md b/samples/openapi3/client/petstore/python-httpx-sync/README.md index 2b24af59b591..2f450bd67f65 100644 --- a/samples/openapi3/client/petstore/python-httpx-sync/README.md +++ b/samples/openapi3/client/petstore/python-httpx-sync/README.md @@ -164,6 +164,7 @@ Class | Method | HTTP request | Description - [AllOfWithSingleRef](docs/AllOfWithSingleRef.md) - [Animal](docs/Animal.md) - [AnyOfColor](docs/AnyOfColor.md) + - [AnyOfContainer](docs/AnyOfContainer.md) - [AnyOfPig](docs/AnyOfPig.md) - [ArrayOfArrayOfModel](docs/ArrayOfArrayOfModel.md) - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) @@ -222,11 +223,13 @@ Class | Method | HTTP request | Description - [ModelReturn](docs/ModelReturn.md) - [MultiArrays](docs/MultiArrays.md) - [Name](docs/Name.md) + - [NestedUnionContainer](docs/NestedUnionContainer.md) - [NullableClass](docs/NullableClass.md) - [NullableProperty](docs/NullableProperty.md) - [NumberOnly](docs/NumberOnly.md) - [ObjectToTestAdditionalProperties](docs/ObjectToTestAdditionalProperties.md) - [ObjectWithDeprecatedFields](docs/ObjectWithDeprecatedFields.md) + - [OneOfContainer](docs/OneOfContainer.md) - [OneOfEnumString](docs/OneOfEnumString.md) - [Order](docs/Order.md) - [OuterComposite](docs/OuterComposite.md) diff --git a/samples/openapi3/client/petstore/python-httpx-sync/docs/AnyOfContainer.md b/samples/openapi3/client/petstore/python-httpx-sync/docs/AnyOfContainer.md new file mode 100644 index 000000000000..4644b55530c7 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx-sync/docs/AnyOfContainer.md @@ -0,0 +1,28 @@ +# AnyOfContainer + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +```python +from petstore_api.models.any_of_container import AnyOfContainer + +# TODO update the JSON string below +json = "{}" +# create an instance of AnyOfContainer from a JSON string +any_of_container_instance = AnyOfContainer.from_json(json) +# print the JSON string representation of the object +print(AnyOfContainer.to_json()) + +# convert the object into a dict +any_of_container_dict = any_of_container_instance.to_dict() +# create an instance of AnyOfContainer from a dict +any_of_container_from_dict = AnyOfContainer.from_dict(any_of_container_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/NestedUnionContainer.md b/samples/openapi3/client/petstore/python-httpx-sync/docs/NestedUnionContainer.md new file mode 100644 index 000000000000..9cf24bc0668a --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx-sync/docs/NestedUnionContainer.md @@ -0,0 +1,28 @@ +# NestedUnionContainer + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +```python +from petstore_api.models.nested_union_container import NestedUnionContainer + +# TODO update the JSON string below +json = "{}" +# create an instance of NestedUnionContainer from a JSON string +nested_union_container_instance = NestedUnionContainer.from_json(json) +# print the JSON string representation of the object +print(NestedUnionContainer.to_json()) + +# convert the object into a dict +nested_union_container_dict = nested_union_container_instance.to_dict() +# create an instance of NestedUnionContainer from a dict +nested_union_container_from_dict = NestedUnionContainer.from_dict(nested_union_container_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/OneOfContainer.md b/samples/openapi3/client/petstore/python-httpx-sync/docs/OneOfContainer.md new file mode 100644 index 000000000000..50d13d3399ac --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx-sync/docs/OneOfContainer.md @@ -0,0 +1,28 @@ +# OneOfContainer + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +```python +from petstore_api.models.one_of_container import OneOfContainer + +# TODO update the JSON string below +json = "{}" +# create an instance of OneOfContainer from a JSON string +one_of_container_instance = OneOfContainer.from_json(json) +# print the JSON string representation of the object +print(OneOfContainer.to_json()) + +# convert the object into a dict +one_of_container_dict = one_of_container_instance.to_dict() +# create an instance of OneOfContainer from a dict +one_of_container_from_dict = OneOfContainer.from_dict(one_of_container_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 c7f461775f59..341a3e34513b 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 @@ -44,6 +44,7 @@ "AllOfWithSingleRef", "Animal", "AnyOfColor", + "AnyOfContainer", "AnyOfPig", "ArrayOfArrayOfModel", "ArrayOfArrayOfNumberOnly", @@ -102,11 +103,13 @@ "ModelReturn", "MultiArrays", "Name", + "NestedUnionContainer", "NullableClass", "NullableProperty", "NumberOnly", "ObjectToTestAdditionalProperties", "ObjectWithDeprecatedFields", + "OneOfContainer", "OneOfEnumString", "Order", "OuterComposite", @@ -183,6 +186,7 @@ from petstore_api.models.all_of_with_single_ref import AllOfWithSingleRef as AllOfWithSingleRef from petstore_api.models.animal import Animal as Animal from petstore_api.models.any_of_color import AnyOfColor as AnyOfColor +from petstore_api.models.any_of_container import AnyOfContainer as AnyOfContainer from petstore_api.models.any_of_pig import AnyOfPig as AnyOfPig from petstore_api.models.array_of_array_of_model import ArrayOfArrayOfModel as ArrayOfArrayOfModel from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly as ArrayOfArrayOfNumberOnly @@ -241,11 +245,13 @@ from petstore_api.models.model_return import ModelReturn as ModelReturn from petstore_api.models.multi_arrays import MultiArrays as MultiArrays from petstore_api.models.name import Name as Name +from petstore_api.models.nested_union_container import NestedUnionContainer as NestedUnionContainer from petstore_api.models.nullable_class import NullableClass as NullableClass from petstore_api.models.nullable_property import NullableProperty as NullableProperty from petstore_api.models.number_only import NumberOnly as NumberOnly from petstore_api.models.object_to_test_additional_properties import ObjectToTestAdditionalProperties as ObjectToTestAdditionalProperties from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields as ObjectWithDeprecatedFields +from petstore_api.models.one_of_container import OneOfContainer as OneOfContainer 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.outer_composite import OuterComposite as OuterComposite 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 308e6dfc3ebb..336021dd171d 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 @@ -21,6 +21,7 @@ from petstore_api.models.all_of_with_single_ref import AllOfWithSingleRef from petstore_api.models.animal import Animal from petstore_api.models.any_of_color import AnyOfColor +from petstore_api.models.any_of_container import AnyOfContainer from petstore_api.models.any_of_pig import AnyOfPig from petstore_api.models.array_of_array_of_model import ArrayOfArrayOfModel from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly @@ -79,11 +80,13 @@ from petstore_api.models.model_return import ModelReturn from petstore_api.models.multi_arrays import MultiArrays from petstore_api.models.name import Name +from petstore_api.models.nested_union_container import NestedUnionContainer from petstore_api.models.nullable_class import NullableClass from petstore_api.models.nullable_property import NullableProperty from petstore_api.models.number_only import NumberOnly from petstore_api.models.object_to_test_additional_properties import ObjectToTestAdditionalProperties from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields +from petstore_api.models.one_of_container import OneOfContainer from petstore_api.models.one_of_enum_string import OneOfEnumString from petstore_api.models.order import Order from petstore_api.models.outer_composite import OuterComposite diff --git a/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/any_of_color.py b/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/any_of_color.py index f6d277e79498..80858f210971 100644 --- a/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/any_of_color.py +++ b/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/any_of_color.py @@ -23,6 +23,17 @@ from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict from typing_extensions import Literal, Self from pydantic import Field +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + ANYOFCOLOR_ANY_OF_SCHEMAS = ["List[int]", "str"] @@ -97,21 +108,23 @@ def from_json(cls, json_str: str) -> Self: error_messages = [] # deserialize data into List[int] try: + data = json.loads(json_str) # validation - instance.anyof_schema_1_validator = json.loads(json_str) + instance.anyof_schema_1_validator = data # assign value to actual_instance instance.actual_instance = instance.anyof_schema_1_validator return instance - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) # deserialize data into List[int] try: + data = json.loads(json_str) # validation - instance.anyof_schema_2_validator = json.loads(json_str) + instance.anyof_schema_2_validator = data # assign value to actual_instance instance.actual_instance = instance.anyof_schema_2_validator return instance - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) # deserialize data into str try: @@ -137,17 +150,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], List[int], str]]: """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: - return self.actual_instance + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/any_of_container.py b/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/any_of_container.py new file mode 100644 index 000000000000..534b12f2dbb3 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/any_of_container.py @@ -0,0 +1,225 @@ +# 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 pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr, ValidationError, field_validator +from typing import Dict, List, Optional +from typing_extensions import Annotated +from petstore_api.models.any_of_pig import AnyOfPig +from petstore_api.models.enum_string1 import EnumString1 +from petstore_api.models.nullable_class import NullableClass +from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict +from typing_extensions import Literal, Self +from pydantic import Field +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + + +ANYOFCONTAINER_ANY_OF_SCHEMAS = ["Dict[str, AnyOfPig]", "List[AnyOfPig]", "List[EnumString1]", "List[NullableClass]", "List[int]", "str"] + +class AnyOfContainer(BaseModel): + """ + AnyOfContainer + """ + + # data type: str + anyof_schema_1_validator: Optional[StrictStr] = None + # data type: List[AnyOfPig] + anyof_schema_2_validator: Optional[Annotated[List[AnyOfPig], Field(min_length=1)]] = None + # data type: Dict[str, AnyOfPig] + anyof_schema_3_validator: Optional[Dict[str, AnyOfPig]] = None + # data type: List[int] + anyof_schema_4_validator: Optional[Annotated[List[StrictInt], Field(min_length=1)]] = None + # data type: List[EnumString1] + anyof_schema_5_validator: Optional[Annotated[List[EnumString1], Field(min_length=1)]] = None + # data type: List[NullableClass] + anyof_schema_6_validator: Optional[Annotated[List[NullableClass], Field(min_length=1)]] = None + if TYPE_CHECKING: + actual_instance: Optional[Union[Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str]] = None + else: + actual_instance: Any = None + any_of_schemas: Set[str] = { "Dict[str, AnyOfPig]", "List[AnyOfPig]", "List[EnumString1]", "List[NullableClass]", "List[int]", "str" } + + model_config = { + "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_anyof(cls, v): + instance = AnyOfContainer.model_construct() + error_messages = [] + # validate data type: str + try: + instance.anyof_schema_1_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[AnyOfPig] + try: + instance.anyof_schema_2_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: Dict[str, AnyOfPig] + try: + instance.anyof_schema_3_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[int] + try: + instance.anyof_schema_4_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[EnumString1] + try: + instance.anyof_schema_5_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[NullableClass] + try: + instance.anyof_schema_6_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + if error_messages: + # no match + raise ValueError("No match found when setting the actual_instance in AnyOfContainer with anyOf schemas: Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: 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 = [] + # deserialize data into str + try: + # validation + instance.anyof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_1_validator + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[AnyOfPig] + try: + data = json.loads(json_str) + data = ([(AnyOfPig.from_dict(_item0) if _item0 is not None else None) for _item0 in data] if isinstance(data, list) else data) + # validation + instance.anyof_schema_2_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_2_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into Dict[str, AnyOfPig] + try: + data = json.loads(json_str) + data = ({_key0: (AnyOfPig.from_dict(_item0) if _item0 is not None else None) for _key0, _item0 in data.items()} if isinstance(data, dict) else data) + # validation + instance.anyof_schema_3_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_3_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[int] + try: + data = json.loads(json_str) + # validation + instance.anyof_schema_4_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_4_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[EnumString1] + try: + data = json.loads(json_str) + # validation + instance.anyof_schema_5_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_5_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[NullableClass] + try: + data = json.loads(json_str) + # validation + instance.anyof_schema_6_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_6_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + + if error_messages: + # no match + raise ValueError("No match found when deserializing the JSON string into AnyOfContainer with anyOf schemas: Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str. 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(to_jsonable_python(self.to_dict())) + + def to_dict(self) -> Optional[Union[Dict[str, Any], Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + return _to_dict(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/petstore_api/models/any_of_pig.py b/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/any_of_pig.py index c949e136f415..752848a7d1aa 100644 --- a/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/any_of_pig.py +++ b/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/any_of_pig.py @@ -24,6 +24,17 @@ from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict from typing_extensions import Literal, Self from pydantic import Field +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + ANYOFPIG_ANY_OF_SCHEMAS = ["BasquePig", "DanishPig"] @@ -115,17 +126,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], BasquePig, DanishPig]]: """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: - return self.actual_instance + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/color.py b/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/color.py index bb740fb597d4..a05b275ff594 100644 --- a/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/color.py +++ b/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/color.py @@ -21,6 +21,17 @@ from pydantic import StrictStr, Field from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + COLOR_ONE_OF_SCHEMAS = ["List[int]", "str"] @@ -104,21 +115,23 @@ def from_json(cls, json_str: Optional[str]) -> Self: # deserialize data into List[int] try: + data = json.loads(json_str) # validation - instance.oneof_schema_1_validator = json.loads(json_str) + instance.oneof_schema_1_validator = data # assign value to actual_instance instance.actual_instance = instance.oneof_schema_1_validator match += 1 - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) # deserialize data into List[int] try: + data = json.loads(json_str) # validation - instance.oneof_schema_2_validator = json.loads(json_str) + instance.oneof_schema_2_validator = data # assign value to actual_instance instance.actual_instance = instance.oneof_schema_2_validator match += 1 - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) # deserialize data into str try: @@ -147,18 +160,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], List[int], str]]: """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 + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/int_or_string.py b/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/int_or_string.py index f2a5a0a2d4a3..21412adc27c3 100644 --- a/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/int_or_string.py +++ b/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/int_or_string.py @@ -21,6 +21,17 @@ from pydantic import StrictStr, Field from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + INTORSTRING_ONE_OF_SCHEMAS = ["int", "str"] @@ -124,18 +135,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], int, str]]: """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 + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/nested_union_container.py b/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/nested_union_container.py new file mode 100644 index 000000000000..932f246f15f3 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/nested_union_container.py @@ -0,0 +1,153 @@ +# 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, Dict, List, Optional +from petstore_api.models.pig import Pig +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + + +NESTEDUNIONCONTAINER_ONE_OF_SCHEMAS = ["List[Dict[str, List[Pig]]]", "str"] + +class NestedUnionContainer(BaseModel): + """ + NestedUnionContainer + """ + # data type: str + oneof_schema_1_validator: Optional[StrictStr] = None + # data type: List[Dict[str, List[Pig]]] + oneof_schema_2_validator: Optional[List[Dict[str, List[Pig]]]] = None + actual_instance: Optional[Union[List[Dict[str, List[Pig]]], str]] = None + one_of_schemas: Set[str] = { "List[Dict[str, List[Pig]]]", "str" } + + 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 = NestedUnionContainer.model_construct() + error_messages = [] + match = 0 + # validate data type: str + try: + instance.oneof_schema_1_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[Dict[str, List[Pig]]] + try: + instance.oneof_schema_2_validator = v + 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 setting `actual_instance` in NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. 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 str + try: + # validation + instance.oneof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_1_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[Dict[str, List[Pig]]] + try: + data = json.loads(json_str) + data = ([({_key1: ([(Pig.from_dict(_item2) if _item2 is not None else None) for _item2 in _item1] if isinstance(_item1, list) else _item1) for _key1, _item1 in _item0.items()} if isinstance(_item0, dict) else _item0) for _item0 in data] if isinstance(data, list) else data) + # validation + instance.oneof_schema_2_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_2_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) 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 NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. 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(to_jsonable_python(self.to_dict())) + + def to_dict(self) -> Optional[Union[Dict[str, Any], List[Dict[str, List[Pig]]], str]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + return _to_dict(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/petstore_api/models/one_of_container.py b/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/one_of_container.py new file mode 100644 index 000000000000..2f4e78d7c261 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/one_of_container.py @@ -0,0 +1,229 @@ +# 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, StrictInt, StrictStr, ValidationError, field_validator +from typing import Any, Dict, List, Optional +from typing_extensions import Annotated +from petstore_api.models.enum_string1 import EnumString1 +from petstore_api.models.nullable_class import NullableClass +from petstore_api.models.pig import Pig +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + + +ONEOFCONTAINER_ONE_OF_SCHEMAS = ["Dict[str, Pig]", "List[EnumString1]", "List[NullableClass]", "List[Pig]", "List[int]", "str"] + +class OneOfContainer(BaseModel): + """ + OneOfContainer + """ + # data type: str + oneof_schema_1_validator: Optional[StrictStr] = None + # data type: List[Pig] + oneof_schema_2_validator: Optional[Annotated[List[Pig], Field(min_length=1)]] = None + # data type: Dict[str, Pig] + oneof_schema_3_validator: Optional[Dict[str, Pig]] = None + # data type: List[int] + oneof_schema_4_validator: Optional[Annotated[List[StrictInt], Field(min_length=1)]] = None + # data type: List[EnumString1] + oneof_schema_5_validator: Optional[Annotated[List[EnumString1], Field(min_length=1)]] = None + # data type: List[NullableClass] + oneof_schema_6_validator: Optional[Annotated[List[NullableClass], Field(min_length=1)]] = None + actual_instance: Optional[Union[Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str]] = None + one_of_schemas: Set[str] = { "Dict[str, Pig]", "List[EnumString1]", "List[NullableClass]", "List[Pig]", "List[int]", "str" } + + 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 = OneOfContainer.model_construct() + error_messages = [] + match = 0 + # validate data type: str + try: + instance.oneof_schema_1_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[Pig] + try: + instance.oneof_schema_2_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: Dict[str, Pig] + try: + instance.oneof_schema_3_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[int] + try: + instance.oneof_schema_4_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[EnumString1] + try: + instance.oneof_schema_5_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[NullableClass] + try: + instance.oneof_schema_6_validator = v + 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 setting `actual_instance` in OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. 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 str + try: + # validation + instance.oneof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_1_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[Pig] + try: + data = json.loads(json_str) + data = ([(Pig.from_dict(_item0) if _item0 is not None else None) for _item0 in data] if isinstance(data, list) else data) + # validation + instance.oneof_schema_2_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_2_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into Dict[str, Pig] + try: + data = json.loads(json_str) + data = ({_key0: (Pig.from_dict(_item0) if _item0 is not None else None) for _key0, _item0 in data.items()} if isinstance(data, dict) else data) + # validation + instance.oneof_schema_3_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_3_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[int] + try: + data = json.loads(json_str) + # validation + instance.oneof_schema_4_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_4_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[EnumString1] + try: + data = json.loads(json_str) + # validation + instance.oneof_schema_5_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_5_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[NullableClass] + try: + data = json.loads(json_str) + # validation + instance.oneof_schema_6_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_6_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) 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 OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. 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(to_jsonable_python(self.to_dict())) + + def to_dict(self) -> Optional[Union[Dict[str, Any], Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + return _to_dict(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/petstore_api/models/pig.py b/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/pig.py index b3a759e89b7b..f7bbd59e8a93 100644 --- a/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/pig.py +++ b/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/pig.py @@ -22,6 +22,17 @@ from pydantic import StrictStr, Field from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + PIG_ONE_OF_SCHEMAS = ["BasquePig", "DanishPig"] @@ -120,18 +131,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], BasquePig, DanishPig]]: """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 + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/task_activity.py b/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/task_activity.py index cc1e1fc5a60f..9623b22041ea 100644 --- a/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/task_activity.py +++ b/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/models/task_activity.py @@ -23,6 +23,17 @@ from pydantic import StrictStr, Field from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + TASKACTIVITY_ONE_OF_SCHEMAS = ["Bathing", "Feeding", "PoopCleaning"] @@ -131,18 +142,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], Bathing, Feeding, PoopCleaning]]: """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 + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-httpx-sync/test/test_any_of_container.py b/samples/openapi3/client/petstore/python-httpx-sync/test/test_any_of_container.py new file mode 100644 index 000000000000..3246e1519768 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx-sync/test/test_any_of_container.py @@ -0,0 +1,50 @@ +# 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.any_of_container import AnyOfContainer + +class TestAnyOfContainer(unittest.TestCase): + """AnyOfContainer unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> AnyOfContainer: + """Test AnyOfContainer + 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 `AnyOfContainer` + """ + model = AnyOfContainer() + if include_optional: + return AnyOfContainer( + ) + else: + return AnyOfContainer( + ) + """ + + def testAnyOfContainer(self): + """Test AnyOfContainer""" + # 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_nested_union_container.py b/samples/openapi3/client/petstore/python-httpx-sync/test/test_nested_union_container.py new file mode 100644 index 000000000000..44901af90110 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx-sync/test/test_nested_union_container.py @@ -0,0 +1,50 @@ +# 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.nested_union_container import NestedUnionContainer + +class TestNestedUnionContainer(unittest.TestCase): + """NestedUnionContainer unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> NestedUnionContainer: + """Test NestedUnionContainer + 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 `NestedUnionContainer` + """ + model = NestedUnionContainer() + if include_optional: + return NestedUnionContainer( + ) + else: + return NestedUnionContainer( + ) + """ + + def testNestedUnionContainer(self): + """Test NestedUnionContainer""" + # 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_one_of_container.py b/samples/openapi3/client/petstore/python-httpx-sync/test/test_one_of_container.py new file mode 100644 index 000000000000..12ab6d654e43 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx-sync/test/test_one_of_container.py @@ -0,0 +1,50 @@ +# 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.one_of_container import OneOfContainer + +class TestOneOfContainer(unittest.TestCase): + """OneOfContainer unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> OneOfContainer: + """Test OneOfContainer + 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 `OneOfContainer` + """ + model = OneOfContainer() + if include_optional: + return OneOfContainer( + ) + else: + return OneOfContainer( + ) + """ + + def testOneOfContainer(self): + """Test OneOfContainer""" + # 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 1eb565d74f11..6af8faf4dffe 100644 --- a/samples/openapi3/client/petstore/python-httpx/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python-httpx/.openapi-generator/FILES @@ -12,6 +12,7 @@ docs/AllOfWithSingleRef.md docs/Animal.md docs/AnotherFakeApi.md docs/AnyOfColor.md +docs/AnyOfContainer.md docs/AnyOfPig.md docs/ArrayOfArrayOfModel.md docs/ArrayOfArrayOfNumberOnly.md @@ -74,11 +75,13 @@ docs/ModelField.md docs/ModelReturn.md docs/MultiArrays.md docs/Name.md +docs/NestedUnionContainer.md docs/NullableClass.md docs/NullableProperty.md docs/NumberOnly.md docs/ObjectToTestAdditionalProperties.md docs/ObjectWithDeprecatedFields.md +docs/OneOfContainer.md docs/OneOfEnumString.md docs/Order.md docs/OuterComposite.md @@ -149,6 +152,7 @@ petstore_api/models/all_of_super_model.py petstore_api/models/all_of_with_single_ref.py petstore_api/models/animal.py petstore_api/models/any_of_color.py +petstore_api/models/any_of_container.py petstore_api/models/any_of_pig.py petstore_api/models/array_of_array_of_model.py petstore_api/models/array_of_array_of_number_only.py @@ -207,11 +211,13 @@ petstore_api/models/model_field.py petstore_api/models/model_return.py petstore_api/models/multi_arrays.py petstore_api/models/name.py +petstore_api/models/nested_union_container.py petstore_api/models/nullable_class.py petstore_api/models/nullable_property.py petstore_api/models/number_only.py petstore_api/models/object_to_test_additional_properties.py petstore_api/models/object_with_deprecated_fields.py +petstore_api/models/one_of_container.py petstore_api/models/one_of_enum_string.py petstore_api/models/order.py petstore_api/models/outer_composite.py diff --git a/samples/openapi3/client/petstore/python-httpx/README.md b/samples/openapi3/client/petstore/python-httpx/README.md index 2b24af59b591..2f450bd67f65 100644 --- a/samples/openapi3/client/petstore/python-httpx/README.md +++ b/samples/openapi3/client/petstore/python-httpx/README.md @@ -164,6 +164,7 @@ Class | Method | HTTP request | Description - [AllOfWithSingleRef](docs/AllOfWithSingleRef.md) - [Animal](docs/Animal.md) - [AnyOfColor](docs/AnyOfColor.md) + - [AnyOfContainer](docs/AnyOfContainer.md) - [AnyOfPig](docs/AnyOfPig.md) - [ArrayOfArrayOfModel](docs/ArrayOfArrayOfModel.md) - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) @@ -222,11 +223,13 @@ Class | Method | HTTP request | Description - [ModelReturn](docs/ModelReturn.md) - [MultiArrays](docs/MultiArrays.md) - [Name](docs/Name.md) + - [NestedUnionContainer](docs/NestedUnionContainer.md) - [NullableClass](docs/NullableClass.md) - [NullableProperty](docs/NullableProperty.md) - [NumberOnly](docs/NumberOnly.md) - [ObjectToTestAdditionalProperties](docs/ObjectToTestAdditionalProperties.md) - [ObjectWithDeprecatedFields](docs/ObjectWithDeprecatedFields.md) + - [OneOfContainer](docs/OneOfContainer.md) - [OneOfEnumString](docs/OneOfEnumString.md) - [Order](docs/Order.md) - [OuterComposite](docs/OuterComposite.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/AnyOfContainer.md b/samples/openapi3/client/petstore/python-httpx/docs/AnyOfContainer.md new file mode 100644 index 000000000000..4644b55530c7 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx/docs/AnyOfContainer.md @@ -0,0 +1,28 @@ +# AnyOfContainer + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +```python +from petstore_api.models.any_of_container import AnyOfContainer + +# TODO update the JSON string below +json = "{}" +# create an instance of AnyOfContainer from a JSON string +any_of_container_instance = AnyOfContainer.from_json(json) +# print the JSON string representation of the object +print(AnyOfContainer.to_json()) + +# convert the object into a dict +any_of_container_dict = any_of_container_instance.to_dict() +# create an instance of AnyOfContainer from a dict +any_of_container_from_dict = AnyOfContainer.from_dict(any_of_container_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/NestedUnionContainer.md b/samples/openapi3/client/petstore/python-httpx/docs/NestedUnionContainer.md new file mode 100644 index 000000000000..9cf24bc0668a --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx/docs/NestedUnionContainer.md @@ -0,0 +1,28 @@ +# NestedUnionContainer + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +```python +from petstore_api.models.nested_union_container import NestedUnionContainer + +# TODO update the JSON string below +json = "{}" +# create an instance of NestedUnionContainer from a JSON string +nested_union_container_instance = NestedUnionContainer.from_json(json) +# print the JSON string representation of the object +print(NestedUnionContainer.to_json()) + +# convert the object into a dict +nested_union_container_dict = nested_union_container_instance.to_dict() +# create an instance of NestedUnionContainer from a dict +nested_union_container_from_dict = NestedUnionContainer.from_dict(nested_union_container_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/OneOfContainer.md b/samples/openapi3/client/petstore/python-httpx/docs/OneOfContainer.md new file mode 100644 index 000000000000..50d13d3399ac --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx/docs/OneOfContainer.md @@ -0,0 +1,28 @@ +# OneOfContainer + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +```python +from petstore_api.models.one_of_container import OneOfContainer + +# TODO update the JSON string below +json = "{}" +# create an instance of OneOfContainer from a JSON string +one_of_container_instance = OneOfContainer.from_json(json) +# print the JSON string representation of the object +print(OneOfContainer.to_json()) + +# convert the object into a dict +one_of_container_dict = one_of_container_instance.to_dict() +# create an instance of OneOfContainer from a dict +one_of_container_from_dict = OneOfContainer.from_dict(one_of_container_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 c7f461775f59..341a3e34513b 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/__init__.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/__init__.py @@ -44,6 +44,7 @@ "AllOfWithSingleRef", "Animal", "AnyOfColor", + "AnyOfContainer", "AnyOfPig", "ArrayOfArrayOfModel", "ArrayOfArrayOfNumberOnly", @@ -102,11 +103,13 @@ "ModelReturn", "MultiArrays", "Name", + "NestedUnionContainer", "NullableClass", "NullableProperty", "NumberOnly", "ObjectToTestAdditionalProperties", "ObjectWithDeprecatedFields", + "OneOfContainer", "OneOfEnumString", "Order", "OuterComposite", @@ -183,6 +186,7 @@ from petstore_api.models.all_of_with_single_ref import AllOfWithSingleRef as AllOfWithSingleRef from petstore_api.models.animal import Animal as Animal from petstore_api.models.any_of_color import AnyOfColor as AnyOfColor +from petstore_api.models.any_of_container import AnyOfContainer as AnyOfContainer from petstore_api.models.any_of_pig import AnyOfPig as AnyOfPig from petstore_api.models.array_of_array_of_model import ArrayOfArrayOfModel as ArrayOfArrayOfModel from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly as ArrayOfArrayOfNumberOnly @@ -241,11 +245,13 @@ from petstore_api.models.model_return import ModelReturn as ModelReturn from petstore_api.models.multi_arrays import MultiArrays as MultiArrays from petstore_api.models.name import Name as Name +from petstore_api.models.nested_union_container import NestedUnionContainer as NestedUnionContainer from petstore_api.models.nullable_class import NullableClass as NullableClass from petstore_api.models.nullable_property import NullableProperty as NullableProperty from petstore_api.models.number_only import NumberOnly as NumberOnly from petstore_api.models.object_to_test_additional_properties import ObjectToTestAdditionalProperties as ObjectToTestAdditionalProperties from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields as ObjectWithDeprecatedFields +from petstore_api.models.one_of_container import OneOfContainer as OneOfContainer 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.outer_composite import OuterComposite as OuterComposite 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 308e6dfc3ebb..336021dd171d 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 @@ -21,6 +21,7 @@ from petstore_api.models.all_of_with_single_ref import AllOfWithSingleRef from petstore_api.models.animal import Animal from petstore_api.models.any_of_color import AnyOfColor +from petstore_api.models.any_of_container import AnyOfContainer from petstore_api.models.any_of_pig import AnyOfPig from petstore_api.models.array_of_array_of_model import ArrayOfArrayOfModel from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly @@ -79,11 +80,13 @@ from petstore_api.models.model_return import ModelReturn from petstore_api.models.multi_arrays import MultiArrays from petstore_api.models.name import Name +from petstore_api.models.nested_union_container import NestedUnionContainer from petstore_api.models.nullable_class import NullableClass from petstore_api.models.nullable_property import NullableProperty from petstore_api.models.number_only import NumberOnly from petstore_api.models.object_to_test_additional_properties import ObjectToTestAdditionalProperties from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields +from petstore_api.models.one_of_container import OneOfContainer from petstore_api.models.one_of_enum_string import OneOfEnumString from petstore_api.models.order import Order from petstore_api.models.outer_composite import OuterComposite diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/any_of_color.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/any_of_color.py index f6d277e79498..80858f210971 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/any_of_color.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/any_of_color.py @@ -23,6 +23,17 @@ from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict from typing_extensions import Literal, Self from pydantic import Field +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + ANYOFCOLOR_ANY_OF_SCHEMAS = ["List[int]", "str"] @@ -97,21 +108,23 @@ def from_json(cls, json_str: str) -> Self: error_messages = [] # deserialize data into List[int] try: + data = json.loads(json_str) # validation - instance.anyof_schema_1_validator = json.loads(json_str) + instance.anyof_schema_1_validator = data # assign value to actual_instance instance.actual_instance = instance.anyof_schema_1_validator return instance - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) # deserialize data into List[int] try: + data = json.loads(json_str) # validation - instance.anyof_schema_2_validator = json.loads(json_str) + instance.anyof_schema_2_validator = data # assign value to actual_instance instance.actual_instance = instance.anyof_schema_2_validator return instance - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) # deserialize data into str try: @@ -137,17 +150,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], List[int], str]]: """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: - return self.actual_instance + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/any_of_container.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/any_of_container.py new file mode 100644 index 000000000000..534b12f2dbb3 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/any_of_container.py @@ -0,0 +1,225 @@ +# 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 pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr, ValidationError, field_validator +from typing import Dict, List, Optional +from typing_extensions import Annotated +from petstore_api.models.any_of_pig import AnyOfPig +from petstore_api.models.enum_string1 import EnumString1 +from petstore_api.models.nullable_class import NullableClass +from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict +from typing_extensions import Literal, Self +from pydantic import Field +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + + +ANYOFCONTAINER_ANY_OF_SCHEMAS = ["Dict[str, AnyOfPig]", "List[AnyOfPig]", "List[EnumString1]", "List[NullableClass]", "List[int]", "str"] + +class AnyOfContainer(BaseModel): + """ + AnyOfContainer + """ + + # data type: str + anyof_schema_1_validator: Optional[StrictStr] = None + # data type: List[AnyOfPig] + anyof_schema_2_validator: Optional[Annotated[List[AnyOfPig], Field(min_length=1)]] = None + # data type: Dict[str, AnyOfPig] + anyof_schema_3_validator: Optional[Dict[str, AnyOfPig]] = None + # data type: List[int] + anyof_schema_4_validator: Optional[Annotated[List[StrictInt], Field(min_length=1)]] = None + # data type: List[EnumString1] + anyof_schema_5_validator: Optional[Annotated[List[EnumString1], Field(min_length=1)]] = None + # data type: List[NullableClass] + anyof_schema_6_validator: Optional[Annotated[List[NullableClass], Field(min_length=1)]] = None + if TYPE_CHECKING: + actual_instance: Optional[Union[Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str]] = None + else: + actual_instance: Any = None + any_of_schemas: Set[str] = { "Dict[str, AnyOfPig]", "List[AnyOfPig]", "List[EnumString1]", "List[NullableClass]", "List[int]", "str" } + + model_config = { + "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_anyof(cls, v): + instance = AnyOfContainer.model_construct() + error_messages = [] + # validate data type: str + try: + instance.anyof_schema_1_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[AnyOfPig] + try: + instance.anyof_schema_2_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: Dict[str, AnyOfPig] + try: + instance.anyof_schema_3_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[int] + try: + instance.anyof_schema_4_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[EnumString1] + try: + instance.anyof_schema_5_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[NullableClass] + try: + instance.anyof_schema_6_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + if error_messages: + # no match + raise ValueError("No match found when setting the actual_instance in AnyOfContainer with anyOf schemas: Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: 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 = [] + # deserialize data into str + try: + # validation + instance.anyof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_1_validator + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[AnyOfPig] + try: + data = json.loads(json_str) + data = ([(AnyOfPig.from_dict(_item0) if _item0 is not None else None) for _item0 in data] if isinstance(data, list) else data) + # validation + instance.anyof_schema_2_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_2_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into Dict[str, AnyOfPig] + try: + data = json.loads(json_str) + data = ({_key0: (AnyOfPig.from_dict(_item0) if _item0 is not None else None) for _key0, _item0 in data.items()} if isinstance(data, dict) else data) + # validation + instance.anyof_schema_3_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_3_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[int] + try: + data = json.loads(json_str) + # validation + instance.anyof_schema_4_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_4_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[EnumString1] + try: + data = json.loads(json_str) + # validation + instance.anyof_schema_5_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_5_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[NullableClass] + try: + data = json.loads(json_str) + # validation + instance.anyof_schema_6_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_6_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + + if error_messages: + # no match + raise ValueError("No match found when deserializing the JSON string into AnyOfContainer with anyOf schemas: Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str. 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(to_jsonable_python(self.to_dict())) + + def to_dict(self) -> Optional[Union[Dict[str, Any], Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + return _to_dict(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/petstore_api/models/any_of_pig.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/any_of_pig.py index c949e136f415..752848a7d1aa 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/any_of_pig.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/any_of_pig.py @@ -24,6 +24,17 @@ from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict from typing_extensions import Literal, Self from pydantic import Field +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + ANYOFPIG_ANY_OF_SCHEMAS = ["BasquePig", "DanishPig"] @@ -115,17 +126,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], BasquePig, DanishPig]]: """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: - return self.actual_instance + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/color.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/color.py index bb740fb597d4..a05b275ff594 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/color.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/color.py @@ -21,6 +21,17 @@ from pydantic import StrictStr, Field from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + COLOR_ONE_OF_SCHEMAS = ["List[int]", "str"] @@ -104,21 +115,23 @@ def from_json(cls, json_str: Optional[str]) -> Self: # deserialize data into List[int] try: + data = json.loads(json_str) # validation - instance.oneof_schema_1_validator = json.loads(json_str) + instance.oneof_schema_1_validator = data # assign value to actual_instance instance.actual_instance = instance.oneof_schema_1_validator match += 1 - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) # deserialize data into List[int] try: + data = json.loads(json_str) # validation - instance.oneof_schema_2_validator = json.loads(json_str) + instance.oneof_schema_2_validator = data # assign value to actual_instance instance.actual_instance = instance.oneof_schema_2_validator match += 1 - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) # deserialize data into str try: @@ -147,18 +160,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], List[int], str]]: """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 + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/int_or_string.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/int_or_string.py index f2a5a0a2d4a3..21412adc27c3 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/int_or_string.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/int_or_string.py @@ -21,6 +21,17 @@ from pydantic import StrictStr, Field from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + INTORSTRING_ONE_OF_SCHEMAS = ["int", "str"] @@ -124,18 +135,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], int, str]]: """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 + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/nested_union_container.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/nested_union_container.py new file mode 100644 index 000000000000..932f246f15f3 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/nested_union_container.py @@ -0,0 +1,153 @@ +# 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, Dict, List, Optional +from petstore_api.models.pig import Pig +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + + +NESTEDUNIONCONTAINER_ONE_OF_SCHEMAS = ["List[Dict[str, List[Pig]]]", "str"] + +class NestedUnionContainer(BaseModel): + """ + NestedUnionContainer + """ + # data type: str + oneof_schema_1_validator: Optional[StrictStr] = None + # data type: List[Dict[str, List[Pig]]] + oneof_schema_2_validator: Optional[List[Dict[str, List[Pig]]]] = None + actual_instance: Optional[Union[List[Dict[str, List[Pig]]], str]] = None + one_of_schemas: Set[str] = { "List[Dict[str, List[Pig]]]", "str" } + + 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 = NestedUnionContainer.model_construct() + error_messages = [] + match = 0 + # validate data type: str + try: + instance.oneof_schema_1_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[Dict[str, List[Pig]]] + try: + instance.oneof_schema_2_validator = v + 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 setting `actual_instance` in NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. 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 str + try: + # validation + instance.oneof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_1_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[Dict[str, List[Pig]]] + try: + data = json.loads(json_str) + data = ([({_key1: ([(Pig.from_dict(_item2) if _item2 is not None else None) for _item2 in _item1] if isinstance(_item1, list) else _item1) for _key1, _item1 in _item0.items()} if isinstance(_item0, dict) else _item0) for _item0 in data] if isinstance(data, list) else data) + # validation + instance.oneof_schema_2_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_2_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) 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 NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. 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(to_jsonable_python(self.to_dict())) + + def to_dict(self) -> Optional[Union[Dict[str, Any], List[Dict[str, List[Pig]]], str]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + return _to_dict(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/petstore_api/models/one_of_container.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/one_of_container.py new file mode 100644 index 000000000000..2f4e78d7c261 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/one_of_container.py @@ -0,0 +1,229 @@ +# 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, StrictInt, StrictStr, ValidationError, field_validator +from typing import Any, Dict, List, Optional +from typing_extensions import Annotated +from petstore_api.models.enum_string1 import EnumString1 +from petstore_api.models.nullable_class import NullableClass +from petstore_api.models.pig import Pig +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + + +ONEOFCONTAINER_ONE_OF_SCHEMAS = ["Dict[str, Pig]", "List[EnumString1]", "List[NullableClass]", "List[Pig]", "List[int]", "str"] + +class OneOfContainer(BaseModel): + """ + OneOfContainer + """ + # data type: str + oneof_schema_1_validator: Optional[StrictStr] = None + # data type: List[Pig] + oneof_schema_2_validator: Optional[Annotated[List[Pig], Field(min_length=1)]] = None + # data type: Dict[str, Pig] + oneof_schema_3_validator: Optional[Dict[str, Pig]] = None + # data type: List[int] + oneof_schema_4_validator: Optional[Annotated[List[StrictInt], Field(min_length=1)]] = None + # data type: List[EnumString1] + oneof_schema_5_validator: Optional[Annotated[List[EnumString1], Field(min_length=1)]] = None + # data type: List[NullableClass] + oneof_schema_6_validator: Optional[Annotated[List[NullableClass], Field(min_length=1)]] = None + actual_instance: Optional[Union[Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str]] = None + one_of_schemas: Set[str] = { "Dict[str, Pig]", "List[EnumString1]", "List[NullableClass]", "List[Pig]", "List[int]", "str" } + + 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 = OneOfContainer.model_construct() + error_messages = [] + match = 0 + # validate data type: str + try: + instance.oneof_schema_1_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[Pig] + try: + instance.oneof_schema_2_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: Dict[str, Pig] + try: + instance.oneof_schema_3_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[int] + try: + instance.oneof_schema_4_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[EnumString1] + try: + instance.oneof_schema_5_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[NullableClass] + try: + instance.oneof_schema_6_validator = v + 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 setting `actual_instance` in OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. 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 str + try: + # validation + instance.oneof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_1_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[Pig] + try: + data = json.loads(json_str) + data = ([(Pig.from_dict(_item0) if _item0 is not None else None) for _item0 in data] if isinstance(data, list) else data) + # validation + instance.oneof_schema_2_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_2_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into Dict[str, Pig] + try: + data = json.loads(json_str) + data = ({_key0: (Pig.from_dict(_item0) if _item0 is not None else None) for _key0, _item0 in data.items()} if isinstance(data, dict) else data) + # validation + instance.oneof_schema_3_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_3_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[int] + try: + data = json.loads(json_str) + # validation + instance.oneof_schema_4_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_4_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[EnumString1] + try: + data = json.loads(json_str) + # validation + instance.oneof_schema_5_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_5_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[NullableClass] + try: + data = json.loads(json_str) + # validation + instance.oneof_schema_6_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_6_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) 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 OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. 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(to_jsonable_python(self.to_dict())) + + def to_dict(self) -> Optional[Union[Dict[str, Any], Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + return _to_dict(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/petstore_api/models/pig.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/pig.py index b3a759e89b7b..f7bbd59e8a93 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/pig.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/pig.py @@ -22,6 +22,17 @@ from pydantic import StrictStr, Field from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + PIG_ONE_OF_SCHEMAS = ["BasquePig", "DanishPig"] @@ -120,18 +131,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], BasquePig, DanishPig]]: """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 + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/task_activity.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/task_activity.py index cc1e1fc5a60f..9623b22041ea 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/task_activity.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/task_activity.py @@ -23,6 +23,17 @@ from pydantic import StrictStr, Field from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + TASKACTIVITY_ONE_OF_SCHEMAS = ["Bathing", "Feeding", "PoopCleaning"] @@ -131,18 +142,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], Bathing, Feeding, PoopCleaning]]: """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 + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-httpx/test/test_any_of_container.py b/samples/openapi3/client/petstore/python-httpx/test/test_any_of_container.py new file mode 100644 index 000000000000..3246e1519768 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx/test/test_any_of_container.py @@ -0,0 +1,50 @@ +# 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.any_of_container import AnyOfContainer + +class TestAnyOfContainer(unittest.TestCase): + """AnyOfContainer unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> AnyOfContainer: + """Test AnyOfContainer + 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 `AnyOfContainer` + """ + model = AnyOfContainer() + if include_optional: + return AnyOfContainer( + ) + else: + return AnyOfContainer( + ) + """ + + def testAnyOfContainer(self): + """Test AnyOfContainer""" + # 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_nested_union_container.py b/samples/openapi3/client/petstore/python-httpx/test/test_nested_union_container.py new file mode 100644 index 000000000000..44901af90110 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx/test/test_nested_union_container.py @@ -0,0 +1,50 @@ +# 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.nested_union_container import NestedUnionContainer + +class TestNestedUnionContainer(unittest.TestCase): + """NestedUnionContainer unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> NestedUnionContainer: + """Test NestedUnionContainer + 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 `NestedUnionContainer` + """ + model = NestedUnionContainer() + if include_optional: + return NestedUnionContainer( + ) + else: + return NestedUnionContainer( + ) + """ + + def testNestedUnionContainer(self): + """Test NestedUnionContainer""" + # 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_one_of_container.py b/samples/openapi3/client/petstore/python-httpx/test/test_one_of_container.py new file mode 100644 index 000000000000..12ab6d654e43 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx/test/test_one_of_container.py @@ -0,0 +1,50 @@ +# 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.one_of_container import OneOfContainer + +class TestOneOfContainer(unittest.TestCase): + """OneOfContainer unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> OneOfContainer: + """Test OneOfContainer + 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 `OneOfContainer` + """ + model = OneOfContainer() + if include_optional: + return OneOfContainer( + ) + else: + return OneOfContainer( + ) + """ + + def testOneOfContainer(self): + """Test OneOfContainer""" + # 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 463307488f33..2f0e4d89347f 100644 --- a/samples/openapi3/client/petstore/python-httpx2-sync/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python-httpx2-sync/.openapi-generator/FILES @@ -12,6 +12,7 @@ docs/AllOfWithSingleRef.md docs/Animal.md docs/AnotherFakeApi.md docs/AnyOfColor.md +docs/AnyOfContainer.md docs/AnyOfPig.md docs/ArrayOfArrayOfModel.md docs/ArrayOfArrayOfNumberOnly.md @@ -74,11 +75,13 @@ docs/ModelField.md docs/ModelReturn.md docs/MultiArrays.md docs/Name.md +docs/NestedUnionContainer.md docs/NullableClass.md docs/NullableProperty.md docs/NumberOnly.md docs/ObjectToTestAdditionalProperties.md docs/ObjectWithDeprecatedFields.md +docs/OneOfContainer.md docs/OneOfEnumString.md docs/Order.md docs/OuterComposite.md @@ -149,6 +152,7 @@ petstore_api/models/all_of_super_model.py petstore_api/models/all_of_with_single_ref.py petstore_api/models/animal.py petstore_api/models/any_of_color.py +petstore_api/models/any_of_container.py petstore_api/models/any_of_pig.py petstore_api/models/array_of_array_of_model.py petstore_api/models/array_of_array_of_number_only.py @@ -207,11 +211,13 @@ petstore_api/models/model_field.py petstore_api/models/model_return.py petstore_api/models/multi_arrays.py petstore_api/models/name.py +petstore_api/models/nested_union_container.py petstore_api/models/nullable_class.py petstore_api/models/nullable_property.py petstore_api/models/number_only.py petstore_api/models/object_to_test_additional_properties.py petstore_api/models/object_with_deprecated_fields.py +petstore_api/models/one_of_container.py petstore_api/models/one_of_enum_string.py petstore_api/models/order.py petstore_api/models/outer_composite.py diff --git a/samples/openapi3/client/petstore/python-httpx2-sync/README.md b/samples/openapi3/client/petstore/python-httpx2-sync/README.md index 8a168eafa795..1575fae84798 100644 --- a/samples/openapi3/client/petstore/python-httpx2-sync/README.md +++ b/samples/openapi3/client/petstore/python-httpx2-sync/README.md @@ -167,6 +167,7 @@ Class | Method | HTTP request | Description - [AllOfWithSingleRef](docs/AllOfWithSingleRef.md) - [Animal](docs/Animal.md) - [AnyOfColor](docs/AnyOfColor.md) + - [AnyOfContainer](docs/AnyOfContainer.md) - [AnyOfPig](docs/AnyOfPig.md) - [ArrayOfArrayOfModel](docs/ArrayOfArrayOfModel.md) - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) @@ -225,11 +226,13 @@ Class | Method | HTTP request | Description - [ModelReturn](docs/ModelReturn.md) - [MultiArrays](docs/MultiArrays.md) - [Name](docs/Name.md) + - [NestedUnionContainer](docs/NestedUnionContainer.md) - [NullableClass](docs/NullableClass.md) - [NullableProperty](docs/NullableProperty.md) - [NumberOnly](docs/NumberOnly.md) - [ObjectToTestAdditionalProperties](docs/ObjectToTestAdditionalProperties.md) - [ObjectWithDeprecatedFields](docs/ObjectWithDeprecatedFields.md) + - [OneOfContainer](docs/OneOfContainer.md) - [OneOfEnumString](docs/OneOfEnumString.md) - [Order](docs/Order.md) - [OuterComposite](docs/OuterComposite.md) diff --git a/samples/openapi3/client/petstore/python-httpx2-sync/docs/AnyOfContainer.md b/samples/openapi3/client/petstore/python-httpx2-sync/docs/AnyOfContainer.md new file mode 100644 index 000000000000..4644b55530c7 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2-sync/docs/AnyOfContainer.md @@ -0,0 +1,28 @@ +# AnyOfContainer + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +```python +from petstore_api.models.any_of_container import AnyOfContainer + +# TODO update the JSON string below +json = "{}" +# create an instance of AnyOfContainer from a JSON string +any_of_container_instance = AnyOfContainer.from_json(json) +# print the JSON string representation of the object +print(AnyOfContainer.to_json()) + +# convert the object into a dict +any_of_container_dict = any_of_container_instance.to_dict() +# create an instance of AnyOfContainer from a dict +any_of_container_from_dict = AnyOfContainer.from_dict(any_of_container_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/NestedUnionContainer.md b/samples/openapi3/client/petstore/python-httpx2-sync/docs/NestedUnionContainer.md new file mode 100644 index 000000000000..9cf24bc0668a --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2-sync/docs/NestedUnionContainer.md @@ -0,0 +1,28 @@ +# NestedUnionContainer + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +```python +from petstore_api.models.nested_union_container import NestedUnionContainer + +# TODO update the JSON string below +json = "{}" +# create an instance of NestedUnionContainer from a JSON string +nested_union_container_instance = NestedUnionContainer.from_json(json) +# print the JSON string representation of the object +print(NestedUnionContainer.to_json()) + +# convert the object into a dict +nested_union_container_dict = nested_union_container_instance.to_dict() +# create an instance of NestedUnionContainer from a dict +nested_union_container_from_dict = NestedUnionContainer.from_dict(nested_union_container_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/OneOfContainer.md b/samples/openapi3/client/petstore/python-httpx2-sync/docs/OneOfContainer.md new file mode 100644 index 000000000000..50d13d3399ac --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2-sync/docs/OneOfContainer.md @@ -0,0 +1,28 @@ +# OneOfContainer + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +```python +from petstore_api.models.one_of_container import OneOfContainer + +# TODO update the JSON string below +json = "{}" +# create an instance of OneOfContainer from a JSON string +one_of_container_instance = OneOfContainer.from_json(json) +# print the JSON string representation of the object +print(OneOfContainer.to_json()) + +# convert the object into a dict +one_of_container_dict = one_of_container_instance.to_dict() +# create an instance of OneOfContainer from a dict +one_of_container_from_dict = OneOfContainer.from_dict(one_of_container_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 c7f461775f59..341a3e34513b 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 @@ -44,6 +44,7 @@ "AllOfWithSingleRef", "Animal", "AnyOfColor", + "AnyOfContainer", "AnyOfPig", "ArrayOfArrayOfModel", "ArrayOfArrayOfNumberOnly", @@ -102,11 +103,13 @@ "ModelReturn", "MultiArrays", "Name", + "NestedUnionContainer", "NullableClass", "NullableProperty", "NumberOnly", "ObjectToTestAdditionalProperties", "ObjectWithDeprecatedFields", + "OneOfContainer", "OneOfEnumString", "Order", "OuterComposite", @@ -183,6 +186,7 @@ from petstore_api.models.all_of_with_single_ref import AllOfWithSingleRef as AllOfWithSingleRef from petstore_api.models.animal import Animal as Animal from petstore_api.models.any_of_color import AnyOfColor as AnyOfColor +from petstore_api.models.any_of_container import AnyOfContainer as AnyOfContainer from petstore_api.models.any_of_pig import AnyOfPig as AnyOfPig from petstore_api.models.array_of_array_of_model import ArrayOfArrayOfModel as ArrayOfArrayOfModel from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly as ArrayOfArrayOfNumberOnly @@ -241,11 +245,13 @@ from petstore_api.models.model_return import ModelReturn as ModelReturn from petstore_api.models.multi_arrays import MultiArrays as MultiArrays from petstore_api.models.name import Name as Name +from petstore_api.models.nested_union_container import NestedUnionContainer as NestedUnionContainer from petstore_api.models.nullable_class import NullableClass as NullableClass from petstore_api.models.nullable_property import NullableProperty as NullableProperty from petstore_api.models.number_only import NumberOnly as NumberOnly from petstore_api.models.object_to_test_additional_properties import ObjectToTestAdditionalProperties as ObjectToTestAdditionalProperties from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields as ObjectWithDeprecatedFields +from petstore_api.models.one_of_container import OneOfContainer as OneOfContainer 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.outer_composite import OuterComposite as OuterComposite 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 308e6dfc3ebb..336021dd171d 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 @@ -21,6 +21,7 @@ from petstore_api.models.all_of_with_single_ref import AllOfWithSingleRef from petstore_api.models.animal import Animal from petstore_api.models.any_of_color import AnyOfColor +from petstore_api.models.any_of_container import AnyOfContainer from petstore_api.models.any_of_pig import AnyOfPig from petstore_api.models.array_of_array_of_model import ArrayOfArrayOfModel from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly @@ -79,11 +80,13 @@ from petstore_api.models.model_return import ModelReturn from petstore_api.models.multi_arrays import MultiArrays from petstore_api.models.name import Name +from petstore_api.models.nested_union_container import NestedUnionContainer from petstore_api.models.nullable_class import NullableClass from petstore_api.models.nullable_property import NullableProperty from petstore_api.models.number_only import NumberOnly from petstore_api.models.object_to_test_additional_properties import ObjectToTestAdditionalProperties from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields +from petstore_api.models.one_of_container import OneOfContainer from petstore_api.models.one_of_enum_string import OneOfEnumString from petstore_api.models.order import Order from petstore_api.models.outer_composite import OuterComposite diff --git a/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/any_of_color.py b/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/any_of_color.py index f6d277e79498..80858f210971 100644 --- a/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/any_of_color.py +++ b/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/any_of_color.py @@ -23,6 +23,17 @@ from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict from typing_extensions import Literal, Self from pydantic import Field +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + ANYOFCOLOR_ANY_OF_SCHEMAS = ["List[int]", "str"] @@ -97,21 +108,23 @@ def from_json(cls, json_str: str) -> Self: error_messages = [] # deserialize data into List[int] try: + data = json.loads(json_str) # validation - instance.anyof_schema_1_validator = json.loads(json_str) + instance.anyof_schema_1_validator = data # assign value to actual_instance instance.actual_instance = instance.anyof_schema_1_validator return instance - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) # deserialize data into List[int] try: + data = json.loads(json_str) # validation - instance.anyof_schema_2_validator = json.loads(json_str) + instance.anyof_schema_2_validator = data # assign value to actual_instance instance.actual_instance = instance.anyof_schema_2_validator return instance - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) # deserialize data into str try: @@ -137,17 +150,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], List[int], str]]: """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: - return self.actual_instance + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/any_of_container.py b/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/any_of_container.py new file mode 100644 index 000000000000..534b12f2dbb3 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/any_of_container.py @@ -0,0 +1,225 @@ +# 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 pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr, ValidationError, field_validator +from typing import Dict, List, Optional +from typing_extensions import Annotated +from petstore_api.models.any_of_pig import AnyOfPig +from petstore_api.models.enum_string1 import EnumString1 +from petstore_api.models.nullable_class import NullableClass +from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict +from typing_extensions import Literal, Self +from pydantic import Field +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + + +ANYOFCONTAINER_ANY_OF_SCHEMAS = ["Dict[str, AnyOfPig]", "List[AnyOfPig]", "List[EnumString1]", "List[NullableClass]", "List[int]", "str"] + +class AnyOfContainer(BaseModel): + """ + AnyOfContainer + """ + + # data type: str + anyof_schema_1_validator: Optional[StrictStr] = None + # data type: List[AnyOfPig] + anyof_schema_2_validator: Optional[Annotated[List[AnyOfPig], Field(min_length=1)]] = None + # data type: Dict[str, AnyOfPig] + anyof_schema_3_validator: Optional[Dict[str, AnyOfPig]] = None + # data type: List[int] + anyof_schema_4_validator: Optional[Annotated[List[StrictInt], Field(min_length=1)]] = None + # data type: List[EnumString1] + anyof_schema_5_validator: Optional[Annotated[List[EnumString1], Field(min_length=1)]] = None + # data type: List[NullableClass] + anyof_schema_6_validator: Optional[Annotated[List[NullableClass], Field(min_length=1)]] = None + if TYPE_CHECKING: + actual_instance: Optional[Union[Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str]] = None + else: + actual_instance: Any = None + any_of_schemas: Set[str] = { "Dict[str, AnyOfPig]", "List[AnyOfPig]", "List[EnumString1]", "List[NullableClass]", "List[int]", "str" } + + model_config = { + "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_anyof(cls, v): + instance = AnyOfContainer.model_construct() + error_messages = [] + # validate data type: str + try: + instance.anyof_schema_1_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[AnyOfPig] + try: + instance.anyof_schema_2_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: Dict[str, AnyOfPig] + try: + instance.anyof_schema_3_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[int] + try: + instance.anyof_schema_4_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[EnumString1] + try: + instance.anyof_schema_5_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[NullableClass] + try: + instance.anyof_schema_6_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + if error_messages: + # no match + raise ValueError("No match found when setting the actual_instance in AnyOfContainer with anyOf schemas: Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: 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 = [] + # deserialize data into str + try: + # validation + instance.anyof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_1_validator + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[AnyOfPig] + try: + data = json.loads(json_str) + data = ([(AnyOfPig.from_dict(_item0) if _item0 is not None else None) for _item0 in data] if isinstance(data, list) else data) + # validation + instance.anyof_schema_2_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_2_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into Dict[str, AnyOfPig] + try: + data = json.loads(json_str) + data = ({_key0: (AnyOfPig.from_dict(_item0) if _item0 is not None else None) for _key0, _item0 in data.items()} if isinstance(data, dict) else data) + # validation + instance.anyof_schema_3_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_3_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[int] + try: + data = json.loads(json_str) + # validation + instance.anyof_schema_4_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_4_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[EnumString1] + try: + data = json.loads(json_str) + # validation + instance.anyof_schema_5_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_5_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[NullableClass] + try: + data = json.loads(json_str) + # validation + instance.anyof_schema_6_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_6_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + + if error_messages: + # no match + raise ValueError("No match found when deserializing the JSON string into AnyOfContainer with anyOf schemas: Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str. 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(to_jsonable_python(self.to_dict())) + + def to_dict(self) -> Optional[Union[Dict[str, Any], Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + return _to_dict(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/petstore_api/models/any_of_pig.py b/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/any_of_pig.py index c949e136f415..752848a7d1aa 100644 --- a/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/any_of_pig.py +++ b/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/any_of_pig.py @@ -24,6 +24,17 @@ from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict from typing_extensions import Literal, Self from pydantic import Field +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + ANYOFPIG_ANY_OF_SCHEMAS = ["BasquePig", "DanishPig"] @@ -115,17 +126,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], BasquePig, DanishPig]]: """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: - return self.actual_instance + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/color.py b/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/color.py index bb740fb597d4..a05b275ff594 100644 --- a/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/color.py +++ b/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/color.py @@ -21,6 +21,17 @@ from pydantic import StrictStr, Field from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + COLOR_ONE_OF_SCHEMAS = ["List[int]", "str"] @@ -104,21 +115,23 @@ def from_json(cls, json_str: Optional[str]) -> Self: # deserialize data into List[int] try: + data = json.loads(json_str) # validation - instance.oneof_schema_1_validator = json.loads(json_str) + instance.oneof_schema_1_validator = data # assign value to actual_instance instance.actual_instance = instance.oneof_schema_1_validator match += 1 - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) # deserialize data into List[int] try: + data = json.loads(json_str) # validation - instance.oneof_schema_2_validator = json.loads(json_str) + instance.oneof_schema_2_validator = data # assign value to actual_instance instance.actual_instance = instance.oneof_schema_2_validator match += 1 - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) # deserialize data into str try: @@ -147,18 +160,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], List[int], str]]: """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 + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/int_or_string.py b/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/int_or_string.py index f2a5a0a2d4a3..21412adc27c3 100644 --- a/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/int_or_string.py +++ b/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/int_or_string.py @@ -21,6 +21,17 @@ from pydantic import StrictStr, Field from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + INTORSTRING_ONE_OF_SCHEMAS = ["int", "str"] @@ -124,18 +135,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], int, str]]: """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 + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/nested_union_container.py b/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/nested_union_container.py new file mode 100644 index 000000000000..932f246f15f3 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/nested_union_container.py @@ -0,0 +1,153 @@ +# 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, Dict, List, Optional +from petstore_api.models.pig import Pig +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + + +NESTEDUNIONCONTAINER_ONE_OF_SCHEMAS = ["List[Dict[str, List[Pig]]]", "str"] + +class NestedUnionContainer(BaseModel): + """ + NestedUnionContainer + """ + # data type: str + oneof_schema_1_validator: Optional[StrictStr] = None + # data type: List[Dict[str, List[Pig]]] + oneof_schema_2_validator: Optional[List[Dict[str, List[Pig]]]] = None + actual_instance: Optional[Union[List[Dict[str, List[Pig]]], str]] = None + one_of_schemas: Set[str] = { "List[Dict[str, List[Pig]]]", "str" } + + 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 = NestedUnionContainer.model_construct() + error_messages = [] + match = 0 + # validate data type: str + try: + instance.oneof_schema_1_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[Dict[str, List[Pig]]] + try: + instance.oneof_schema_2_validator = v + 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 setting `actual_instance` in NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. 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 str + try: + # validation + instance.oneof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_1_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[Dict[str, List[Pig]]] + try: + data = json.loads(json_str) + data = ([({_key1: ([(Pig.from_dict(_item2) if _item2 is not None else None) for _item2 in _item1] if isinstance(_item1, list) else _item1) for _key1, _item1 in _item0.items()} if isinstance(_item0, dict) else _item0) for _item0 in data] if isinstance(data, list) else data) + # validation + instance.oneof_schema_2_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_2_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) 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 NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. 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(to_jsonable_python(self.to_dict())) + + def to_dict(self) -> Optional[Union[Dict[str, Any], List[Dict[str, List[Pig]]], str]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + return _to_dict(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/petstore_api/models/one_of_container.py b/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/one_of_container.py new file mode 100644 index 000000000000..2f4e78d7c261 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/one_of_container.py @@ -0,0 +1,229 @@ +# 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, StrictInt, StrictStr, ValidationError, field_validator +from typing import Any, Dict, List, Optional +from typing_extensions import Annotated +from petstore_api.models.enum_string1 import EnumString1 +from petstore_api.models.nullable_class import NullableClass +from petstore_api.models.pig import Pig +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + + +ONEOFCONTAINER_ONE_OF_SCHEMAS = ["Dict[str, Pig]", "List[EnumString1]", "List[NullableClass]", "List[Pig]", "List[int]", "str"] + +class OneOfContainer(BaseModel): + """ + OneOfContainer + """ + # data type: str + oneof_schema_1_validator: Optional[StrictStr] = None + # data type: List[Pig] + oneof_schema_2_validator: Optional[Annotated[List[Pig], Field(min_length=1)]] = None + # data type: Dict[str, Pig] + oneof_schema_3_validator: Optional[Dict[str, Pig]] = None + # data type: List[int] + oneof_schema_4_validator: Optional[Annotated[List[StrictInt], Field(min_length=1)]] = None + # data type: List[EnumString1] + oneof_schema_5_validator: Optional[Annotated[List[EnumString1], Field(min_length=1)]] = None + # data type: List[NullableClass] + oneof_schema_6_validator: Optional[Annotated[List[NullableClass], Field(min_length=1)]] = None + actual_instance: Optional[Union[Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str]] = None + one_of_schemas: Set[str] = { "Dict[str, Pig]", "List[EnumString1]", "List[NullableClass]", "List[Pig]", "List[int]", "str" } + + 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 = OneOfContainer.model_construct() + error_messages = [] + match = 0 + # validate data type: str + try: + instance.oneof_schema_1_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[Pig] + try: + instance.oneof_schema_2_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: Dict[str, Pig] + try: + instance.oneof_schema_3_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[int] + try: + instance.oneof_schema_4_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[EnumString1] + try: + instance.oneof_schema_5_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[NullableClass] + try: + instance.oneof_schema_6_validator = v + 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 setting `actual_instance` in OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. 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 str + try: + # validation + instance.oneof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_1_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[Pig] + try: + data = json.loads(json_str) + data = ([(Pig.from_dict(_item0) if _item0 is not None else None) for _item0 in data] if isinstance(data, list) else data) + # validation + instance.oneof_schema_2_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_2_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into Dict[str, Pig] + try: + data = json.loads(json_str) + data = ({_key0: (Pig.from_dict(_item0) if _item0 is not None else None) for _key0, _item0 in data.items()} if isinstance(data, dict) else data) + # validation + instance.oneof_schema_3_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_3_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[int] + try: + data = json.loads(json_str) + # validation + instance.oneof_schema_4_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_4_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[EnumString1] + try: + data = json.loads(json_str) + # validation + instance.oneof_schema_5_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_5_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[NullableClass] + try: + data = json.loads(json_str) + # validation + instance.oneof_schema_6_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_6_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) 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 OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. 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(to_jsonable_python(self.to_dict())) + + def to_dict(self) -> Optional[Union[Dict[str, Any], Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + return _to_dict(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/petstore_api/models/pig.py b/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/pig.py index b3a759e89b7b..f7bbd59e8a93 100644 --- a/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/pig.py +++ b/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/pig.py @@ -22,6 +22,17 @@ from pydantic import StrictStr, Field from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + PIG_ONE_OF_SCHEMAS = ["BasquePig", "DanishPig"] @@ -120,18 +131,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], BasquePig, DanishPig]]: """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 + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/task_activity.py b/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/task_activity.py index cc1e1fc5a60f..9623b22041ea 100644 --- a/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/task_activity.py +++ b/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/models/task_activity.py @@ -23,6 +23,17 @@ from pydantic import StrictStr, Field from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + TASKACTIVITY_ONE_OF_SCHEMAS = ["Bathing", "Feeding", "PoopCleaning"] @@ -131,18 +142,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], Bathing, Feeding, PoopCleaning]]: """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 + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-httpx2-sync/test/test_any_of_container.py b/samples/openapi3/client/petstore/python-httpx2-sync/test/test_any_of_container.py new file mode 100644 index 000000000000..3246e1519768 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2-sync/test/test_any_of_container.py @@ -0,0 +1,50 @@ +# 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.any_of_container import AnyOfContainer + +class TestAnyOfContainer(unittest.TestCase): + """AnyOfContainer unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> AnyOfContainer: + """Test AnyOfContainer + 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 `AnyOfContainer` + """ + model = AnyOfContainer() + if include_optional: + return AnyOfContainer( + ) + else: + return AnyOfContainer( + ) + """ + + def testAnyOfContainer(self): + """Test AnyOfContainer""" + # 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_nested_union_container.py b/samples/openapi3/client/petstore/python-httpx2-sync/test/test_nested_union_container.py new file mode 100644 index 000000000000..44901af90110 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2-sync/test/test_nested_union_container.py @@ -0,0 +1,50 @@ +# 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.nested_union_container import NestedUnionContainer + +class TestNestedUnionContainer(unittest.TestCase): + """NestedUnionContainer unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> NestedUnionContainer: + """Test NestedUnionContainer + 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 `NestedUnionContainer` + """ + model = NestedUnionContainer() + if include_optional: + return NestedUnionContainer( + ) + else: + return NestedUnionContainer( + ) + """ + + def testNestedUnionContainer(self): + """Test NestedUnionContainer""" + # 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_one_of_container.py b/samples/openapi3/client/petstore/python-httpx2-sync/test/test_one_of_container.py new file mode 100644 index 000000000000..12ab6d654e43 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2-sync/test/test_one_of_container.py @@ -0,0 +1,50 @@ +# 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.one_of_container import OneOfContainer + +class TestOneOfContainer(unittest.TestCase): + """OneOfContainer unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> OneOfContainer: + """Test OneOfContainer + 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 `OneOfContainer` + """ + model = OneOfContainer() + if include_optional: + return OneOfContainer( + ) + else: + return OneOfContainer( + ) + """ + + def testOneOfContainer(self): + """Test OneOfContainer""" + # 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 1eb565d74f11..6af8faf4dffe 100644 --- a/samples/openapi3/client/petstore/python-httpx2/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python-httpx2/.openapi-generator/FILES @@ -12,6 +12,7 @@ docs/AllOfWithSingleRef.md docs/Animal.md docs/AnotherFakeApi.md docs/AnyOfColor.md +docs/AnyOfContainer.md docs/AnyOfPig.md docs/ArrayOfArrayOfModel.md docs/ArrayOfArrayOfNumberOnly.md @@ -74,11 +75,13 @@ docs/ModelField.md docs/ModelReturn.md docs/MultiArrays.md docs/Name.md +docs/NestedUnionContainer.md docs/NullableClass.md docs/NullableProperty.md docs/NumberOnly.md docs/ObjectToTestAdditionalProperties.md docs/ObjectWithDeprecatedFields.md +docs/OneOfContainer.md docs/OneOfEnumString.md docs/Order.md docs/OuterComposite.md @@ -149,6 +152,7 @@ petstore_api/models/all_of_super_model.py petstore_api/models/all_of_with_single_ref.py petstore_api/models/animal.py petstore_api/models/any_of_color.py +petstore_api/models/any_of_container.py petstore_api/models/any_of_pig.py petstore_api/models/array_of_array_of_model.py petstore_api/models/array_of_array_of_number_only.py @@ -207,11 +211,13 @@ petstore_api/models/model_field.py petstore_api/models/model_return.py petstore_api/models/multi_arrays.py petstore_api/models/name.py +petstore_api/models/nested_union_container.py petstore_api/models/nullable_class.py petstore_api/models/nullable_property.py petstore_api/models/number_only.py petstore_api/models/object_to_test_additional_properties.py petstore_api/models/object_with_deprecated_fields.py +petstore_api/models/one_of_container.py petstore_api/models/one_of_enum_string.py petstore_api/models/order.py petstore_api/models/outer_composite.py diff --git a/samples/openapi3/client/petstore/python-httpx2/README.md b/samples/openapi3/client/petstore/python-httpx2/README.md index 01215bdf5f9a..f0f11e1c7e9b 100644 --- a/samples/openapi3/client/petstore/python-httpx2/README.md +++ b/samples/openapi3/client/petstore/python-httpx2/README.md @@ -166,6 +166,7 @@ Class | Method | HTTP request | Description - [AllOfWithSingleRef](docs/AllOfWithSingleRef.md) - [Animal](docs/Animal.md) - [AnyOfColor](docs/AnyOfColor.md) + - [AnyOfContainer](docs/AnyOfContainer.md) - [AnyOfPig](docs/AnyOfPig.md) - [ArrayOfArrayOfModel](docs/ArrayOfArrayOfModel.md) - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) @@ -224,11 +225,13 @@ Class | Method | HTTP request | Description - [ModelReturn](docs/ModelReturn.md) - [MultiArrays](docs/MultiArrays.md) - [Name](docs/Name.md) + - [NestedUnionContainer](docs/NestedUnionContainer.md) - [NullableClass](docs/NullableClass.md) - [NullableProperty](docs/NullableProperty.md) - [NumberOnly](docs/NumberOnly.md) - [ObjectToTestAdditionalProperties](docs/ObjectToTestAdditionalProperties.md) - [ObjectWithDeprecatedFields](docs/ObjectWithDeprecatedFields.md) + - [OneOfContainer](docs/OneOfContainer.md) - [OneOfEnumString](docs/OneOfEnumString.md) - [Order](docs/Order.md) - [OuterComposite](docs/OuterComposite.md) diff --git a/samples/openapi3/client/petstore/python-httpx2/docs/AnyOfContainer.md b/samples/openapi3/client/petstore/python-httpx2/docs/AnyOfContainer.md new file mode 100644 index 000000000000..4644b55530c7 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2/docs/AnyOfContainer.md @@ -0,0 +1,28 @@ +# AnyOfContainer + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +```python +from petstore_api.models.any_of_container import AnyOfContainer + +# TODO update the JSON string below +json = "{}" +# create an instance of AnyOfContainer from a JSON string +any_of_container_instance = AnyOfContainer.from_json(json) +# print the JSON string representation of the object +print(AnyOfContainer.to_json()) + +# convert the object into a dict +any_of_container_dict = any_of_container_instance.to_dict() +# create an instance of AnyOfContainer from a dict +any_of_container_from_dict = AnyOfContainer.from_dict(any_of_container_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/NestedUnionContainer.md b/samples/openapi3/client/petstore/python-httpx2/docs/NestedUnionContainer.md new file mode 100644 index 000000000000..9cf24bc0668a --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2/docs/NestedUnionContainer.md @@ -0,0 +1,28 @@ +# NestedUnionContainer + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +```python +from petstore_api.models.nested_union_container import NestedUnionContainer + +# TODO update the JSON string below +json = "{}" +# create an instance of NestedUnionContainer from a JSON string +nested_union_container_instance = NestedUnionContainer.from_json(json) +# print the JSON string representation of the object +print(NestedUnionContainer.to_json()) + +# convert the object into a dict +nested_union_container_dict = nested_union_container_instance.to_dict() +# create an instance of NestedUnionContainer from a dict +nested_union_container_from_dict = NestedUnionContainer.from_dict(nested_union_container_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/OneOfContainer.md b/samples/openapi3/client/petstore/python-httpx2/docs/OneOfContainer.md new file mode 100644 index 000000000000..50d13d3399ac --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2/docs/OneOfContainer.md @@ -0,0 +1,28 @@ +# OneOfContainer + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +```python +from petstore_api.models.one_of_container import OneOfContainer + +# TODO update the JSON string below +json = "{}" +# create an instance of OneOfContainer from a JSON string +one_of_container_instance = OneOfContainer.from_json(json) +# print the JSON string representation of the object +print(OneOfContainer.to_json()) + +# convert the object into a dict +one_of_container_dict = one_of_container_instance.to_dict() +# create an instance of OneOfContainer from a dict +one_of_container_from_dict = OneOfContainer.from_dict(one_of_container_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 c7f461775f59..341a3e34513b 100644 --- a/samples/openapi3/client/petstore/python-httpx2/petstore_api/__init__.py +++ b/samples/openapi3/client/petstore/python-httpx2/petstore_api/__init__.py @@ -44,6 +44,7 @@ "AllOfWithSingleRef", "Animal", "AnyOfColor", + "AnyOfContainer", "AnyOfPig", "ArrayOfArrayOfModel", "ArrayOfArrayOfNumberOnly", @@ -102,11 +103,13 @@ "ModelReturn", "MultiArrays", "Name", + "NestedUnionContainer", "NullableClass", "NullableProperty", "NumberOnly", "ObjectToTestAdditionalProperties", "ObjectWithDeprecatedFields", + "OneOfContainer", "OneOfEnumString", "Order", "OuterComposite", @@ -183,6 +186,7 @@ from petstore_api.models.all_of_with_single_ref import AllOfWithSingleRef as AllOfWithSingleRef from petstore_api.models.animal import Animal as Animal from petstore_api.models.any_of_color import AnyOfColor as AnyOfColor +from petstore_api.models.any_of_container import AnyOfContainer as AnyOfContainer from petstore_api.models.any_of_pig import AnyOfPig as AnyOfPig from petstore_api.models.array_of_array_of_model import ArrayOfArrayOfModel as ArrayOfArrayOfModel from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly as ArrayOfArrayOfNumberOnly @@ -241,11 +245,13 @@ from petstore_api.models.model_return import ModelReturn as ModelReturn from petstore_api.models.multi_arrays import MultiArrays as MultiArrays from petstore_api.models.name import Name as Name +from petstore_api.models.nested_union_container import NestedUnionContainer as NestedUnionContainer from petstore_api.models.nullable_class import NullableClass as NullableClass from petstore_api.models.nullable_property import NullableProperty as NullableProperty from petstore_api.models.number_only import NumberOnly as NumberOnly from petstore_api.models.object_to_test_additional_properties import ObjectToTestAdditionalProperties as ObjectToTestAdditionalProperties from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields as ObjectWithDeprecatedFields +from petstore_api.models.one_of_container import OneOfContainer as OneOfContainer 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.outer_composite import OuterComposite as OuterComposite 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 308e6dfc3ebb..336021dd171d 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 @@ -21,6 +21,7 @@ from petstore_api.models.all_of_with_single_ref import AllOfWithSingleRef from petstore_api.models.animal import Animal from petstore_api.models.any_of_color import AnyOfColor +from petstore_api.models.any_of_container import AnyOfContainer from petstore_api.models.any_of_pig import AnyOfPig from petstore_api.models.array_of_array_of_model import ArrayOfArrayOfModel from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly @@ -79,11 +80,13 @@ from petstore_api.models.model_return import ModelReturn from petstore_api.models.multi_arrays import MultiArrays from petstore_api.models.name import Name +from petstore_api.models.nested_union_container import NestedUnionContainer from petstore_api.models.nullable_class import NullableClass from petstore_api.models.nullable_property import NullableProperty from petstore_api.models.number_only import NumberOnly from petstore_api.models.object_to_test_additional_properties import ObjectToTestAdditionalProperties from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields +from petstore_api.models.one_of_container import OneOfContainer from petstore_api.models.one_of_enum_string import OneOfEnumString from petstore_api.models.order import Order from petstore_api.models.outer_composite import OuterComposite diff --git a/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/any_of_color.py b/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/any_of_color.py index f6d277e79498..80858f210971 100644 --- a/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/any_of_color.py +++ b/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/any_of_color.py @@ -23,6 +23,17 @@ from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict from typing_extensions import Literal, Self from pydantic import Field +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + ANYOFCOLOR_ANY_OF_SCHEMAS = ["List[int]", "str"] @@ -97,21 +108,23 @@ def from_json(cls, json_str: str) -> Self: error_messages = [] # deserialize data into List[int] try: + data = json.loads(json_str) # validation - instance.anyof_schema_1_validator = json.loads(json_str) + instance.anyof_schema_1_validator = data # assign value to actual_instance instance.actual_instance = instance.anyof_schema_1_validator return instance - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) # deserialize data into List[int] try: + data = json.loads(json_str) # validation - instance.anyof_schema_2_validator = json.loads(json_str) + instance.anyof_schema_2_validator = data # assign value to actual_instance instance.actual_instance = instance.anyof_schema_2_validator return instance - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) # deserialize data into str try: @@ -137,17 +150,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], List[int], str]]: """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: - return self.actual_instance + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/any_of_container.py b/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/any_of_container.py new file mode 100644 index 000000000000..534b12f2dbb3 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/any_of_container.py @@ -0,0 +1,225 @@ +# 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 pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr, ValidationError, field_validator +from typing import Dict, List, Optional +from typing_extensions import Annotated +from petstore_api.models.any_of_pig import AnyOfPig +from petstore_api.models.enum_string1 import EnumString1 +from petstore_api.models.nullable_class import NullableClass +from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict +from typing_extensions import Literal, Self +from pydantic import Field +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + + +ANYOFCONTAINER_ANY_OF_SCHEMAS = ["Dict[str, AnyOfPig]", "List[AnyOfPig]", "List[EnumString1]", "List[NullableClass]", "List[int]", "str"] + +class AnyOfContainer(BaseModel): + """ + AnyOfContainer + """ + + # data type: str + anyof_schema_1_validator: Optional[StrictStr] = None + # data type: List[AnyOfPig] + anyof_schema_2_validator: Optional[Annotated[List[AnyOfPig], Field(min_length=1)]] = None + # data type: Dict[str, AnyOfPig] + anyof_schema_3_validator: Optional[Dict[str, AnyOfPig]] = None + # data type: List[int] + anyof_schema_4_validator: Optional[Annotated[List[StrictInt], Field(min_length=1)]] = None + # data type: List[EnumString1] + anyof_schema_5_validator: Optional[Annotated[List[EnumString1], Field(min_length=1)]] = None + # data type: List[NullableClass] + anyof_schema_6_validator: Optional[Annotated[List[NullableClass], Field(min_length=1)]] = None + if TYPE_CHECKING: + actual_instance: Optional[Union[Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str]] = None + else: + actual_instance: Any = None + any_of_schemas: Set[str] = { "Dict[str, AnyOfPig]", "List[AnyOfPig]", "List[EnumString1]", "List[NullableClass]", "List[int]", "str" } + + model_config = { + "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_anyof(cls, v): + instance = AnyOfContainer.model_construct() + error_messages = [] + # validate data type: str + try: + instance.anyof_schema_1_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[AnyOfPig] + try: + instance.anyof_schema_2_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: Dict[str, AnyOfPig] + try: + instance.anyof_schema_3_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[int] + try: + instance.anyof_schema_4_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[EnumString1] + try: + instance.anyof_schema_5_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[NullableClass] + try: + instance.anyof_schema_6_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + if error_messages: + # no match + raise ValueError("No match found when setting the actual_instance in AnyOfContainer with anyOf schemas: Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: 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 = [] + # deserialize data into str + try: + # validation + instance.anyof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_1_validator + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[AnyOfPig] + try: + data = json.loads(json_str) + data = ([(AnyOfPig.from_dict(_item0) if _item0 is not None else None) for _item0 in data] if isinstance(data, list) else data) + # validation + instance.anyof_schema_2_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_2_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into Dict[str, AnyOfPig] + try: + data = json.loads(json_str) + data = ({_key0: (AnyOfPig.from_dict(_item0) if _item0 is not None else None) for _key0, _item0 in data.items()} if isinstance(data, dict) else data) + # validation + instance.anyof_schema_3_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_3_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[int] + try: + data = json.loads(json_str) + # validation + instance.anyof_schema_4_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_4_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[EnumString1] + try: + data = json.loads(json_str) + # validation + instance.anyof_schema_5_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_5_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[NullableClass] + try: + data = json.loads(json_str) + # validation + instance.anyof_schema_6_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_6_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + + if error_messages: + # no match + raise ValueError("No match found when deserializing the JSON string into AnyOfContainer with anyOf schemas: Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str. 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(to_jsonable_python(self.to_dict())) + + def to_dict(self) -> Optional[Union[Dict[str, Any], Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + return _to_dict(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/petstore_api/models/any_of_pig.py b/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/any_of_pig.py index c949e136f415..752848a7d1aa 100644 --- a/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/any_of_pig.py +++ b/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/any_of_pig.py @@ -24,6 +24,17 @@ from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict from typing_extensions import Literal, Self from pydantic import Field +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + ANYOFPIG_ANY_OF_SCHEMAS = ["BasquePig", "DanishPig"] @@ -115,17 +126,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], BasquePig, DanishPig]]: """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: - return self.actual_instance + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/color.py b/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/color.py index bb740fb597d4..a05b275ff594 100644 --- a/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/color.py +++ b/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/color.py @@ -21,6 +21,17 @@ from pydantic import StrictStr, Field from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + COLOR_ONE_OF_SCHEMAS = ["List[int]", "str"] @@ -104,21 +115,23 @@ def from_json(cls, json_str: Optional[str]) -> Self: # deserialize data into List[int] try: + data = json.loads(json_str) # validation - instance.oneof_schema_1_validator = json.loads(json_str) + instance.oneof_schema_1_validator = data # assign value to actual_instance instance.actual_instance = instance.oneof_schema_1_validator match += 1 - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) # deserialize data into List[int] try: + data = json.loads(json_str) # validation - instance.oneof_schema_2_validator = json.loads(json_str) + instance.oneof_schema_2_validator = data # assign value to actual_instance instance.actual_instance = instance.oneof_schema_2_validator match += 1 - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) # deserialize data into str try: @@ -147,18 +160,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], List[int], str]]: """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 + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/int_or_string.py b/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/int_or_string.py index f2a5a0a2d4a3..21412adc27c3 100644 --- a/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/int_or_string.py +++ b/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/int_or_string.py @@ -21,6 +21,17 @@ from pydantic import StrictStr, Field from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + INTORSTRING_ONE_OF_SCHEMAS = ["int", "str"] @@ -124,18 +135,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], int, str]]: """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 + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/nested_union_container.py b/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/nested_union_container.py new file mode 100644 index 000000000000..932f246f15f3 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/nested_union_container.py @@ -0,0 +1,153 @@ +# 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, Dict, List, Optional +from petstore_api.models.pig import Pig +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + + +NESTEDUNIONCONTAINER_ONE_OF_SCHEMAS = ["List[Dict[str, List[Pig]]]", "str"] + +class NestedUnionContainer(BaseModel): + """ + NestedUnionContainer + """ + # data type: str + oneof_schema_1_validator: Optional[StrictStr] = None + # data type: List[Dict[str, List[Pig]]] + oneof_schema_2_validator: Optional[List[Dict[str, List[Pig]]]] = None + actual_instance: Optional[Union[List[Dict[str, List[Pig]]], str]] = None + one_of_schemas: Set[str] = { "List[Dict[str, List[Pig]]]", "str" } + + 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 = NestedUnionContainer.model_construct() + error_messages = [] + match = 0 + # validate data type: str + try: + instance.oneof_schema_1_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[Dict[str, List[Pig]]] + try: + instance.oneof_schema_2_validator = v + 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 setting `actual_instance` in NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. 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 str + try: + # validation + instance.oneof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_1_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[Dict[str, List[Pig]]] + try: + data = json.loads(json_str) + data = ([({_key1: ([(Pig.from_dict(_item2) if _item2 is not None else None) for _item2 in _item1] if isinstance(_item1, list) else _item1) for _key1, _item1 in _item0.items()} if isinstance(_item0, dict) else _item0) for _item0 in data] if isinstance(data, list) else data) + # validation + instance.oneof_schema_2_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_2_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) 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 NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. 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(to_jsonable_python(self.to_dict())) + + def to_dict(self) -> Optional[Union[Dict[str, Any], List[Dict[str, List[Pig]]], str]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + return _to_dict(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/petstore_api/models/one_of_container.py b/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/one_of_container.py new file mode 100644 index 000000000000..2f4e78d7c261 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/one_of_container.py @@ -0,0 +1,229 @@ +# 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, StrictInt, StrictStr, ValidationError, field_validator +from typing import Any, Dict, List, Optional +from typing_extensions import Annotated +from petstore_api.models.enum_string1 import EnumString1 +from petstore_api.models.nullable_class import NullableClass +from petstore_api.models.pig import Pig +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + + +ONEOFCONTAINER_ONE_OF_SCHEMAS = ["Dict[str, Pig]", "List[EnumString1]", "List[NullableClass]", "List[Pig]", "List[int]", "str"] + +class OneOfContainer(BaseModel): + """ + OneOfContainer + """ + # data type: str + oneof_schema_1_validator: Optional[StrictStr] = None + # data type: List[Pig] + oneof_schema_2_validator: Optional[Annotated[List[Pig], Field(min_length=1)]] = None + # data type: Dict[str, Pig] + oneof_schema_3_validator: Optional[Dict[str, Pig]] = None + # data type: List[int] + oneof_schema_4_validator: Optional[Annotated[List[StrictInt], Field(min_length=1)]] = None + # data type: List[EnumString1] + oneof_schema_5_validator: Optional[Annotated[List[EnumString1], Field(min_length=1)]] = None + # data type: List[NullableClass] + oneof_schema_6_validator: Optional[Annotated[List[NullableClass], Field(min_length=1)]] = None + actual_instance: Optional[Union[Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str]] = None + one_of_schemas: Set[str] = { "Dict[str, Pig]", "List[EnumString1]", "List[NullableClass]", "List[Pig]", "List[int]", "str" } + + 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 = OneOfContainer.model_construct() + error_messages = [] + match = 0 + # validate data type: str + try: + instance.oneof_schema_1_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[Pig] + try: + instance.oneof_schema_2_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: Dict[str, Pig] + try: + instance.oneof_schema_3_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[int] + try: + instance.oneof_schema_4_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[EnumString1] + try: + instance.oneof_schema_5_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[NullableClass] + try: + instance.oneof_schema_6_validator = v + 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 setting `actual_instance` in OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. 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 str + try: + # validation + instance.oneof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_1_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[Pig] + try: + data = json.loads(json_str) + data = ([(Pig.from_dict(_item0) if _item0 is not None else None) for _item0 in data] if isinstance(data, list) else data) + # validation + instance.oneof_schema_2_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_2_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into Dict[str, Pig] + try: + data = json.loads(json_str) + data = ({_key0: (Pig.from_dict(_item0) if _item0 is not None else None) for _key0, _item0 in data.items()} if isinstance(data, dict) else data) + # validation + instance.oneof_schema_3_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_3_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[int] + try: + data = json.loads(json_str) + # validation + instance.oneof_schema_4_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_4_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[EnumString1] + try: + data = json.loads(json_str) + # validation + instance.oneof_schema_5_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_5_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[NullableClass] + try: + data = json.loads(json_str) + # validation + instance.oneof_schema_6_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_6_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) 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 OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. 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(to_jsonable_python(self.to_dict())) + + def to_dict(self) -> Optional[Union[Dict[str, Any], Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + return _to_dict(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/petstore_api/models/pig.py b/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/pig.py index b3a759e89b7b..f7bbd59e8a93 100644 --- a/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/pig.py +++ b/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/pig.py @@ -22,6 +22,17 @@ from pydantic import StrictStr, Field from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + PIG_ONE_OF_SCHEMAS = ["BasquePig", "DanishPig"] @@ -120,18 +131,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], BasquePig, DanishPig]]: """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 + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/task_activity.py b/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/task_activity.py index cc1e1fc5a60f..9623b22041ea 100644 --- a/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/task_activity.py +++ b/samples/openapi3/client/petstore/python-httpx2/petstore_api/models/task_activity.py @@ -23,6 +23,17 @@ from pydantic import StrictStr, Field from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + TASKACTIVITY_ONE_OF_SCHEMAS = ["Bathing", "Feeding", "PoopCleaning"] @@ -131,18 +142,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], Bathing, Feeding, PoopCleaning]]: """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 + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-httpx2/test/test_any_of_container.py b/samples/openapi3/client/petstore/python-httpx2/test/test_any_of_container.py new file mode 100644 index 000000000000..3246e1519768 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2/test/test_any_of_container.py @@ -0,0 +1,50 @@ +# 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.any_of_container import AnyOfContainer + +class TestAnyOfContainer(unittest.TestCase): + """AnyOfContainer unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> AnyOfContainer: + """Test AnyOfContainer + 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 `AnyOfContainer` + """ + model = AnyOfContainer() + if include_optional: + return AnyOfContainer( + ) + else: + return AnyOfContainer( + ) + """ + + def testAnyOfContainer(self): + """Test AnyOfContainer""" + # 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_nested_union_container.py b/samples/openapi3/client/petstore/python-httpx2/test/test_nested_union_container.py new file mode 100644 index 000000000000..44901af90110 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2/test/test_nested_union_container.py @@ -0,0 +1,50 @@ +# 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.nested_union_container import NestedUnionContainer + +class TestNestedUnionContainer(unittest.TestCase): + """NestedUnionContainer unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> NestedUnionContainer: + """Test NestedUnionContainer + 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 `NestedUnionContainer` + """ + model = NestedUnionContainer() + if include_optional: + return NestedUnionContainer( + ) + else: + return NestedUnionContainer( + ) + """ + + def testNestedUnionContainer(self): + """Test NestedUnionContainer""" + # 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_one_of_container.py b/samples/openapi3/client/petstore/python-httpx2/test/test_one_of_container.py new file mode 100644 index 000000000000..12ab6d654e43 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2/test/test_one_of_container.py @@ -0,0 +1,50 @@ +# 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.one_of_container import OneOfContainer + +class TestOneOfContainer(unittest.TestCase): + """OneOfContainer unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> OneOfContainer: + """Test OneOfContainer + 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 `OneOfContainer` + """ + model = OneOfContainer() + if include_optional: + return OneOfContainer( + ) + else: + return OneOfContainer( + ) + """ + + def testOneOfContainer(self): + """Test OneOfContainer""" + # 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 1eb565d74f11..6af8faf4dffe 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python-lazyImports/.openapi-generator/FILES @@ -12,6 +12,7 @@ docs/AllOfWithSingleRef.md docs/Animal.md docs/AnotherFakeApi.md docs/AnyOfColor.md +docs/AnyOfContainer.md docs/AnyOfPig.md docs/ArrayOfArrayOfModel.md docs/ArrayOfArrayOfNumberOnly.md @@ -74,11 +75,13 @@ docs/ModelField.md docs/ModelReturn.md docs/MultiArrays.md docs/Name.md +docs/NestedUnionContainer.md docs/NullableClass.md docs/NullableProperty.md docs/NumberOnly.md docs/ObjectToTestAdditionalProperties.md docs/ObjectWithDeprecatedFields.md +docs/OneOfContainer.md docs/OneOfEnumString.md docs/Order.md docs/OuterComposite.md @@ -149,6 +152,7 @@ petstore_api/models/all_of_super_model.py petstore_api/models/all_of_with_single_ref.py petstore_api/models/animal.py petstore_api/models/any_of_color.py +petstore_api/models/any_of_container.py petstore_api/models/any_of_pig.py petstore_api/models/array_of_array_of_model.py petstore_api/models/array_of_array_of_number_only.py @@ -207,11 +211,13 @@ petstore_api/models/model_field.py petstore_api/models/model_return.py petstore_api/models/multi_arrays.py petstore_api/models/name.py +petstore_api/models/nested_union_container.py petstore_api/models/nullable_class.py petstore_api/models/nullable_property.py petstore_api/models/number_only.py petstore_api/models/object_to_test_additional_properties.py petstore_api/models/object_with_deprecated_fields.py +petstore_api/models/one_of_container.py petstore_api/models/one_of_enum_string.py petstore_api/models/order.py petstore_api/models/outer_composite.py diff --git a/samples/openapi3/client/petstore/python-lazyImports/README.md b/samples/openapi3/client/petstore/python-lazyImports/README.md index fdaf54802dff..386a8055b875 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/README.md +++ b/samples/openapi3/client/petstore/python-lazyImports/README.md @@ -187,6 +187,7 @@ Class | Method | HTTP request | Description - [AllOfWithSingleRef](docs/AllOfWithSingleRef.md) - [Animal](docs/Animal.md) - [AnyOfColor](docs/AnyOfColor.md) + - [AnyOfContainer](docs/AnyOfContainer.md) - [AnyOfPig](docs/AnyOfPig.md) - [ArrayOfArrayOfModel](docs/ArrayOfArrayOfModel.md) - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) @@ -245,11 +246,13 @@ Class | Method | HTTP request | Description - [ModelReturn](docs/ModelReturn.md) - [MultiArrays](docs/MultiArrays.md) - [Name](docs/Name.md) + - [NestedUnionContainer](docs/NestedUnionContainer.md) - [NullableClass](docs/NullableClass.md) - [NullableProperty](docs/NullableProperty.md) - [NumberOnly](docs/NumberOnly.md) - [ObjectToTestAdditionalProperties](docs/ObjectToTestAdditionalProperties.md) - [ObjectWithDeprecatedFields](docs/ObjectWithDeprecatedFields.md) + - [OneOfContainer](docs/OneOfContainer.md) - [OneOfEnumString](docs/OneOfEnumString.md) - [Order](docs/Order.md) - [OuterComposite](docs/OuterComposite.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/AnyOfContainer.md b/samples/openapi3/client/petstore/python-lazyImports/docs/AnyOfContainer.md new file mode 100644 index 000000000000..4644b55530c7 --- /dev/null +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/AnyOfContainer.md @@ -0,0 +1,28 @@ +# AnyOfContainer + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +```python +from petstore_api.models.any_of_container import AnyOfContainer + +# TODO update the JSON string below +json = "{}" +# create an instance of AnyOfContainer from a JSON string +any_of_container_instance = AnyOfContainer.from_json(json) +# print the JSON string representation of the object +print(AnyOfContainer.to_json()) + +# convert the object into a dict +any_of_container_dict = any_of_container_instance.to_dict() +# create an instance of AnyOfContainer from a dict +any_of_container_from_dict = AnyOfContainer.from_dict(any_of_container_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/NestedUnionContainer.md b/samples/openapi3/client/petstore/python-lazyImports/docs/NestedUnionContainer.md new file mode 100644 index 000000000000..9cf24bc0668a --- /dev/null +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/NestedUnionContainer.md @@ -0,0 +1,28 @@ +# NestedUnionContainer + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +```python +from petstore_api.models.nested_union_container import NestedUnionContainer + +# TODO update the JSON string below +json = "{}" +# create an instance of NestedUnionContainer from a JSON string +nested_union_container_instance = NestedUnionContainer.from_json(json) +# print the JSON string representation of the object +print(NestedUnionContainer.to_json()) + +# convert the object into a dict +nested_union_container_dict = nested_union_container_instance.to_dict() +# create an instance of NestedUnionContainer from a dict +nested_union_container_from_dict = NestedUnionContainer.from_dict(nested_union_container_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/OneOfContainer.md b/samples/openapi3/client/petstore/python-lazyImports/docs/OneOfContainer.md new file mode 100644 index 000000000000..50d13d3399ac --- /dev/null +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/OneOfContainer.md @@ -0,0 +1,28 @@ +# OneOfContainer + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +```python +from petstore_api.models.one_of_container import OneOfContainer + +# TODO update the JSON string below +json = "{}" +# create an instance of OneOfContainer from a JSON string +one_of_container_instance = OneOfContainer.from_json(json) +# print the JSON string representation of the object +print(OneOfContainer.to_json()) + +# convert the object into a dict +one_of_container_dict = one_of_container_instance.to_dict() +# create an instance of OneOfContainer from a dict +one_of_container_from_dict = OneOfContainer.from_dict(one_of_container_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 619a79ecf490..2dad9940c58e 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/__init__.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/__init__.py @@ -44,6 +44,7 @@ "AllOfWithSingleRef", "Animal", "AnyOfColor", + "AnyOfContainer", "AnyOfPig", "ArrayOfArrayOfModel", "ArrayOfArrayOfNumberOnly", @@ -102,11 +103,13 @@ "ModelReturn", "MultiArrays", "Name", + "NestedUnionContainer", "NullableClass", "NullableProperty", "NumberOnly", "ObjectToTestAdditionalProperties", "ObjectWithDeprecatedFields", + "OneOfContainer", "OneOfEnumString", "Order", "OuterComposite", @@ -186,6 +189,7 @@ from petstore_api.models.all_of_with_single_ref import AllOfWithSingleRef as AllOfWithSingleRef from petstore_api.models.animal import Animal as Animal from petstore_api.models.any_of_color import AnyOfColor as AnyOfColor + from petstore_api.models.any_of_container import AnyOfContainer as AnyOfContainer from petstore_api.models.any_of_pig import AnyOfPig as AnyOfPig from petstore_api.models.array_of_array_of_model import ArrayOfArrayOfModel as ArrayOfArrayOfModel from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly as ArrayOfArrayOfNumberOnly @@ -244,11 +248,13 @@ from petstore_api.models.model_return import ModelReturn as ModelReturn from petstore_api.models.multi_arrays import MultiArrays as MultiArrays from petstore_api.models.name import Name as Name + from petstore_api.models.nested_union_container import NestedUnionContainer as NestedUnionContainer from petstore_api.models.nullable_class import NullableClass as NullableClass from petstore_api.models.nullable_property import NullableProperty as NullableProperty from petstore_api.models.number_only import NumberOnly as NumberOnly from petstore_api.models.object_to_test_additional_properties import ObjectToTestAdditionalProperties as ObjectToTestAdditionalProperties from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields as ObjectWithDeprecatedFields + from petstore_api.models.one_of_container import OneOfContainer as OneOfContainer 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.outer_composite import OuterComposite as OuterComposite @@ -323,6 +329,7 @@ "AllOfWithSingleRef": ".models.all_of_with_single_ref", "Animal": ".models.animal", "AnyOfColor": ".models.any_of_color", + "AnyOfContainer": ".models.any_of_container", "AnyOfPig": ".models.any_of_pig", "ArrayOfArrayOfModel": ".models.array_of_array_of_model", "ArrayOfArrayOfNumberOnly": ".models.array_of_array_of_number_only", @@ -381,11 +388,13 @@ "ModelReturn": ".models.model_return", "MultiArrays": ".models.multi_arrays", "Name": ".models.name", + "NestedUnionContainer": ".models.nested_union_container", "NullableClass": ".models.nullable_class", "NullableProperty": ".models.nullable_property", "NumberOnly": ".models.number_only", "ObjectToTestAdditionalProperties": ".models.object_to_test_additional_properties", "ObjectWithDeprecatedFields": ".models.object_with_deprecated_fields", + "OneOfContainer": ".models.one_of_container", "OneOfEnumString": ".models.one_of_enum_string", "Order": ".models.order", "OuterComposite": ".models.outer_composite", 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 407cbf7cee53..921cfc30b1a1 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 @@ -21,6 +21,7 @@ "AllOfWithSingleRef", "Animal", "AnyOfColor", + "AnyOfContainer", "AnyOfPig", "ArrayOfArrayOfModel", "ArrayOfArrayOfNumberOnly", @@ -79,11 +80,13 @@ "ModelReturn", "MultiArrays", "Name", + "NestedUnionContainer", "NullableClass", "NullableProperty", "NumberOnly", "ObjectToTestAdditionalProperties", "ObjectWithDeprecatedFields", + "OneOfContainer", "OneOfEnumString", "Order", "OuterComposite", @@ -141,6 +144,7 @@ from petstore_api.models.all_of_with_single_ref import AllOfWithSingleRef from petstore_api.models.animal import Animal from petstore_api.models.any_of_color import AnyOfColor + from petstore_api.models.any_of_container import AnyOfContainer from petstore_api.models.any_of_pig import AnyOfPig from petstore_api.models.array_of_array_of_model import ArrayOfArrayOfModel from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly @@ -199,11 +203,13 @@ from petstore_api.models.model_return import ModelReturn from petstore_api.models.multi_arrays import MultiArrays from petstore_api.models.name import Name + from petstore_api.models.nested_union_container import NestedUnionContainer from petstore_api.models.nullable_class import NullableClass from petstore_api.models.nullable_property import NullableProperty from petstore_api.models.number_only import NumberOnly from petstore_api.models.object_to_test_additional_properties import ObjectToTestAdditionalProperties from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields + from petstore_api.models.one_of_container import OneOfContainer from petstore_api.models.one_of_enum_string import OneOfEnumString from petstore_api.models.order import Order from petstore_api.models.outer_composite import OuterComposite @@ -260,6 +266,7 @@ "AllOfWithSingleRef": ".all_of_with_single_ref", "Animal": ".animal", "AnyOfColor": ".any_of_color", + "AnyOfContainer": ".any_of_container", "AnyOfPig": ".any_of_pig", "ArrayOfArrayOfModel": ".array_of_array_of_model", "ArrayOfArrayOfNumberOnly": ".array_of_array_of_number_only", @@ -318,11 +325,13 @@ "ModelReturn": ".model_return", "MultiArrays": ".multi_arrays", "Name": ".name", + "NestedUnionContainer": ".nested_union_container", "NullableClass": ".nullable_class", "NullableProperty": ".nullable_property", "NumberOnly": ".number_only", "ObjectToTestAdditionalProperties": ".object_to_test_additional_properties", "ObjectWithDeprecatedFields": ".object_with_deprecated_fields", + "OneOfContainer": ".one_of_container", "OneOfEnumString": ".one_of_enum_string", "Order": ".order", "OuterComposite": ".outer_composite", diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/any_of_color.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/any_of_color.py index f6d277e79498..80858f210971 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/any_of_color.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/any_of_color.py @@ -23,6 +23,17 @@ from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict from typing_extensions import Literal, Self from pydantic import Field +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + ANYOFCOLOR_ANY_OF_SCHEMAS = ["List[int]", "str"] @@ -97,21 +108,23 @@ def from_json(cls, json_str: str) -> Self: error_messages = [] # deserialize data into List[int] try: + data = json.loads(json_str) # validation - instance.anyof_schema_1_validator = json.loads(json_str) + instance.anyof_schema_1_validator = data # assign value to actual_instance instance.actual_instance = instance.anyof_schema_1_validator return instance - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) # deserialize data into List[int] try: + data = json.loads(json_str) # validation - instance.anyof_schema_2_validator = json.loads(json_str) + instance.anyof_schema_2_validator = data # assign value to actual_instance instance.actual_instance = instance.anyof_schema_2_validator return instance - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) # deserialize data into str try: @@ -137,17 +150,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], List[int], str]]: """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: - return self.actual_instance + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/any_of_container.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/any_of_container.py new file mode 100644 index 000000000000..534b12f2dbb3 --- /dev/null +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/any_of_container.py @@ -0,0 +1,225 @@ +# 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 pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr, ValidationError, field_validator +from typing import Dict, List, Optional +from typing_extensions import Annotated +from petstore_api.models.any_of_pig import AnyOfPig +from petstore_api.models.enum_string1 import EnumString1 +from petstore_api.models.nullable_class import NullableClass +from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict +from typing_extensions import Literal, Self +from pydantic import Field +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + + +ANYOFCONTAINER_ANY_OF_SCHEMAS = ["Dict[str, AnyOfPig]", "List[AnyOfPig]", "List[EnumString1]", "List[NullableClass]", "List[int]", "str"] + +class AnyOfContainer(BaseModel): + """ + AnyOfContainer + """ + + # data type: str + anyof_schema_1_validator: Optional[StrictStr] = None + # data type: List[AnyOfPig] + anyof_schema_2_validator: Optional[Annotated[List[AnyOfPig], Field(min_length=1)]] = None + # data type: Dict[str, AnyOfPig] + anyof_schema_3_validator: Optional[Dict[str, AnyOfPig]] = None + # data type: List[int] + anyof_schema_4_validator: Optional[Annotated[List[StrictInt], Field(min_length=1)]] = None + # data type: List[EnumString1] + anyof_schema_5_validator: Optional[Annotated[List[EnumString1], Field(min_length=1)]] = None + # data type: List[NullableClass] + anyof_schema_6_validator: Optional[Annotated[List[NullableClass], Field(min_length=1)]] = None + if TYPE_CHECKING: + actual_instance: Optional[Union[Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str]] = None + else: + actual_instance: Any = None + any_of_schemas: Set[str] = { "Dict[str, AnyOfPig]", "List[AnyOfPig]", "List[EnumString1]", "List[NullableClass]", "List[int]", "str" } + + model_config = { + "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_anyof(cls, v): + instance = AnyOfContainer.model_construct() + error_messages = [] + # validate data type: str + try: + instance.anyof_schema_1_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[AnyOfPig] + try: + instance.anyof_schema_2_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: Dict[str, AnyOfPig] + try: + instance.anyof_schema_3_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[int] + try: + instance.anyof_schema_4_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[EnumString1] + try: + instance.anyof_schema_5_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[NullableClass] + try: + instance.anyof_schema_6_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + if error_messages: + # no match + raise ValueError("No match found when setting the actual_instance in AnyOfContainer with anyOf schemas: Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: 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 = [] + # deserialize data into str + try: + # validation + instance.anyof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_1_validator + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[AnyOfPig] + try: + data = json.loads(json_str) + data = ([(AnyOfPig.from_dict(_item0) if _item0 is not None else None) for _item0 in data] if isinstance(data, list) else data) + # validation + instance.anyof_schema_2_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_2_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into Dict[str, AnyOfPig] + try: + data = json.loads(json_str) + data = ({_key0: (AnyOfPig.from_dict(_item0) if _item0 is not None else None) for _key0, _item0 in data.items()} if isinstance(data, dict) else data) + # validation + instance.anyof_schema_3_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_3_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[int] + try: + data = json.loads(json_str) + # validation + instance.anyof_schema_4_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_4_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[EnumString1] + try: + data = json.loads(json_str) + # validation + instance.anyof_schema_5_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_5_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[NullableClass] + try: + data = json.loads(json_str) + # validation + instance.anyof_schema_6_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_6_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + + if error_messages: + # no match + raise ValueError("No match found when deserializing the JSON string into AnyOfContainer with anyOf schemas: Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str. 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(to_jsonable_python(self.to_dict())) + + def to_dict(self) -> Optional[Union[Dict[str, Any], Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + return _to_dict(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/petstore_api/models/any_of_pig.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/any_of_pig.py index c949e136f415..752848a7d1aa 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/any_of_pig.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/any_of_pig.py @@ -24,6 +24,17 @@ from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict from typing_extensions import Literal, Self from pydantic import Field +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + ANYOFPIG_ANY_OF_SCHEMAS = ["BasquePig", "DanishPig"] @@ -115,17 +126,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], BasquePig, DanishPig]]: """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: - return self.actual_instance + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/color.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/color.py index bb740fb597d4..a05b275ff594 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/color.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/color.py @@ -21,6 +21,17 @@ from pydantic import StrictStr, Field from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + COLOR_ONE_OF_SCHEMAS = ["List[int]", "str"] @@ -104,21 +115,23 @@ def from_json(cls, json_str: Optional[str]) -> Self: # deserialize data into List[int] try: + data = json.loads(json_str) # validation - instance.oneof_schema_1_validator = json.loads(json_str) + instance.oneof_schema_1_validator = data # assign value to actual_instance instance.actual_instance = instance.oneof_schema_1_validator match += 1 - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) # deserialize data into List[int] try: + data = json.loads(json_str) # validation - instance.oneof_schema_2_validator = json.loads(json_str) + instance.oneof_schema_2_validator = data # assign value to actual_instance instance.actual_instance = instance.oneof_schema_2_validator match += 1 - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) # deserialize data into str try: @@ -147,18 +160,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], List[int], str]]: """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 + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/int_or_string.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/int_or_string.py index f2a5a0a2d4a3..21412adc27c3 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/int_or_string.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/int_or_string.py @@ -21,6 +21,17 @@ from pydantic import StrictStr, Field from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + INTORSTRING_ONE_OF_SCHEMAS = ["int", "str"] @@ -124,18 +135,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], int, str]]: """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 + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/nested_union_container.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/nested_union_container.py new file mode 100644 index 000000000000..932f246f15f3 --- /dev/null +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/nested_union_container.py @@ -0,0 +1,153 @@ +# 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, Dict, List, Optional +from petstore_api.models.pig import Pig +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + + +NESTEDUNIONCONTAINER_ONE_OF_SCHEMAS = ["List[Dict[str, List[Pig]]]", "str"] + +class NestedUnionContainer(BaseModel): + """ + NestedUnionContainer + """ + # data type: str + oneof_schema_1_validator: Optional[StrictStr] = None + # data type: List[Dict[str, List[Pig]]] + oneof_schema_2_validator: Optional[List[Dict[str, List[Pig]]]] = None + actual_instance: Optional[Union[List[Dict[str, List[Pig]]], str]] = None + one_of_schemas: Set[str] = { "List[Dict[str, List[Pig]]]", "str" } + + 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 = NestedUnionContainer.model_construct() + error_messages = [] + match = 0 + # validate data type: str + try: + instance.oneof_schema_1_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[Dict[str, List[Pig]]] + try: + instance.oneof_schema_2_validator = v + 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 setting `actual_instance` in NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. 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 str + try: + # validation + instance.oneof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_1_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[Dict[str, List[Pig]]] + try: + data = json.loads(json_str) + data = ([({_key1: ([(Pig.from_dict(_item2) if _item2 is not None else None) for _item2 in _item1] if isinstance(_item1, list) else _item1) for _key1, _item1 in _item0.items()} if isinstance(_item0, dict) else _item0) for _item0 in data] if isinstance(data, list) else data) + # validation + instance.oneof_schema_2_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_2_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) 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 NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. 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(to_jsonable_python(self.to_dict())) + + def to_dict(self) -> Optional[Union[Dict[str, Any], List[Dict[str, List[Pig]]], str]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + return _to_dict(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/petstore_api/models/one_of_container.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/one_of_container.py new file mode 100644 index 000000000000..2f4e78d7c261 --- /dev/null +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/one_of_container.py @@ -0,0 +1,229 @@ +# 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, StrictInt, StrictStr, ValidationError, field_validator +from typing import Any, Dict, List, Optional +from typing_extensions import Annotated +from petstore_api.models.enum_string1 import EnumString1 +from petstore_api.models.nullable_class import NullableClass +from petstore_api.models.pig import Pig +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + + +ONEOFCONTAINER_ONE_OF_SCHEMAS = ["Dict[str, Pig]", "List[EnumString1]", "List[NullableClass]", "List[Pig]", "List[int]", "str"] + +class OneOfContainer(BaseModel): + """ + OneOfContainer + """ + # data type: str + oneof_schema_1_validator: Optional[StrictStr] = None + # data type: List[Pig] + oneof_schema_2_validator: Optional[Annotated[List[Pig], Field(min_length=1)]] = None + # data type: Dict[str, Pig] + oneof_schema_3_validator: Optional[Dict[str, Pig]] = None + # data type: List[int] + oneof_schema_4_validator: Optional[Annotated[List[StrictInt], Field(min_length=1)]] = None + # data type: List[EnumString1] + oneof_schema_5_validator: Optional[Annotated[List[EnumString1], Field(min_length=1)]] = None + # data type: List[NullableClass] + oneof_schema_6_validator: Optional[Annotated[List[NullableClass], Field(min_length=1)]] = None + actual_instance: Optional[Union[Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str]] = None + one_of_schemas: Set[str] = { "Dict[str, Pig]", "List[EnumString1]", "List[NullableClass]", "List[Pig]", "List[int]", "str" } + + 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 = OneOfContainer.model_construct() + error_messages = [] + match = 0 + # validate data type: str + try: + instance.oneof_schema_1_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[Pig] + try: + instance.oneof_schema_2_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: Dict[str, Pig] + try: + instance.oneof_schema_3_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[int] + try: + instance.oneof_schema_4_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[EnumString1] + try: + instance.oneof_schema_5_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[NullableClass] + try: + instance.oneof_schema_6_validator = v + 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 setting `actual_instance` in OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. 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 str + try: + # validation + instance.oneof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_1_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[Pig] + try: + data = json.loads(json_str) + data = ([(Pig.from_dict(_item0) if _item0 is not None else None) for _item0 in data] if isinstance(data, list) else data) + # validation + instance.oneof_schema_2_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_2_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into Dict[str, Pig] + try: + data = json.loads(json_str) + data = ({_key0: (Pig.from_dict(_item0) if _item0 is not None else None) for _key0, _item0 in data.items()} if isinstance(data, dict) else data) + # validation + instance.oneof_schema_3_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_3_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[int] + try: + data = json.loads(json_str) + # validation + instance.oneof_schema_4_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_4_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[EnumString1] + try: + data = json.loads(json_str) + # validation + instance.oneof_schema_5_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_5_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[NullableClass] + try: + data = json.loads(json_str) + # validation + instance.oneof_schema_6_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_6_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) 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 OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. 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(to_jsonable_python(self.to_dict())) + + def to_dict(self) -> Optional[Union[Dict[str, Any], Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + return _to_dict(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/petstore_api/models/one_of_enum_string.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/one_of_enum_string.py index f180178737db..da15aedf5355 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/one_of_enum_string.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/one_of_enum_string.py @@ -22,6 +22,17 @@ from pydantic import StrictStr, Field from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + ONEOFENUMSTRING_ONE_OF_SCHEMAS = ["EnumString1", "EnumString2"] @@ -117,18 +128,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], EnumString1, EnumString2]]: """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 + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/pig.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/pig.py index 8f9306304c66..dd76a1b28da2 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/pig.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/pig.py @@ -22,6 +22,17 @@ from pydantic import StrictStr, Field from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + PIG_ONE_OF_SCHEMAS = ["BasquePig", "DanishPig"] @@ -136,18 +147,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], BasquePig, DanishPig]]: """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 + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/task_activity.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/task_activity.py index cc1e1fc5a60f..9623b22041ea 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/task_activity.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/task_activity.py @@ -23,6 +23,17 @@ from pydantic import StrictStr, Field from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + TASKACTIVITY_ONE_OF_SCHEMAS = ["Bathing", "Feeding", "PoopCleaning"] @@ -131,18 +142,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], Bathing, Feeding, PoopCleaning]]: """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 + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-lazyImports/test/test_any_of_container.py b/samples/openapi3/client/petstore/python-lazyImports/test/test_any_of_container.py new file mode 100644 index 000000000000..3246e1519768 --- /dev/null +++ b/samples/openapi3/client/petstore/python-lazyImports/test/test_any_of_container.py @@ -0,0 +1,50 @@ +# 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.any_of_container import AnyOfContainer + +class TestAnyOfContainer(unittest.TestCase): + """AnyOfContainer unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> AnyOfContainer: + """Test AnyOfContainer + 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 `AnyOfContainer` + """ + model = AnyOfContainer() + if include_optional: + return AnyOfContainer( + ) + else: + return AnyOfContainer( + ) + """ + + def testAnyOfContainer(self): + """Test AnyOfContainer""" + # 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_nested_union_container.py b/samples/openapi3/client/petstore/python-lazyImports/test/test_nested_union_container.py new file mode 100644 index 000000000000..44901af90110 --- /dev/null +++ b/samples/openapi3/client/petstore/python-lazyImports/test/test_nested_union_container.py @@ -0,0 +1,50 @@ +# 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.nested_union_container import NestedUnionContainer + +class TestNestedUnionContainer(unittest.TestCase): + """NestedUnionContainer unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> NestedUnionContainer: + """Test NestedUnionContainer + 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 `NestedUnionContainer` + """ + model = NestedUnionContainer() + if include_optional: + return NestedUnionContainer( + ) + else: + return NestedUnionContainer( + ) + """ + + def testNestedUnionContainer(self): + """Test NestedUnionContainer""" + # 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_one_of_container.py b/samples/openapi3/client/petstore/python-lazyImports/test/test_one_of_container.py new file mode 100644 index 000000000000..12ab6d654e43 --- /dev/null +++ b/samples/openapi3/client/petstore/python-lazyImports/test/test_one_of_container.py @@ -0,0 +1,50 @@ +# 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.one_of_container import OneOfContainer + +class TestOneOfContainer(unittest.TestCase): + """OneOfContainer unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> OneOfContainer: + """Test OneOfContainer + 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 `OneOfContainer` + """ + model = OneOfContainer() + if include_optional: + return OneOfContainer( + ) + else: + return OneOfContainer( + ) + """ + + def testOneOfContainer(self): + """Test OneOfContainer""" + # 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 3bdfdd3eebd9..23cf7fac7971 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 @@ -12,6 +12,7 @@ docs/AllOfWithSingleRef.md docs/Animal.md docs/AnotherFakeApi.md docs/AnyOfColor.md +docs/AnyOfContainer.md docs/AnyOfPig.md docs/ApiResponse.md docs/ArrayOfArrayOfModel.md @@ -74,11 +75,13 @@ docs/Model200Response.md docs/ModelReturn.md docs/MultiArrays.md docs/Name.md +docs/NestedUnionContainer.md docs/NullableClass.md docs/NullableProperty.md docs/NumberOnly.md docs/ObjectToTestAdditionalProperties.md docs/ObjectWithDeprecatedFields.md +docs/OneOfContainer.md docs/OneOfEnumString.md docs/Order.md docs/OuterComposite.md @@ -149,6 +152,7 @@ petstore_api/models/all_of_super_model.py petstore_api/models/all_of_with_single_ref.py petstore_api/models/animal.py petstore_api/models/any_of_color.py +petstore_api/models/any_of_container.py petstore_api/models/any_of_pig.py petstore_api/models/api_response.py petstore_api/models/array_of_array_of_model.py @@ -207,11 +211,13 @@ petstore_api/models/model200_response.py petstore_api/models/model_return.py petstore_api/models/multi_arrays.py petstore_api/models/name.py +petstore_api/models/nested_union_container.py petstore_api/models/nullable_class.py petstore_api/models/nullable_property.py petstore_api/models/number_only.py petstore_api/models/object_to_test_additional_properties.py petstore_api/models/object_with_deprecated_fields.py +petstore_api/models/one_of_container.py petstore_api/models/one_of_enum_string.py petstore_api/models/order.py petstore_api/models/outer_composite.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 91f5fddf86c1..18689883ca2b 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/README.md +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/README.md @@ -160,6 +160,7 @@ Class | Method | HTTP request | Description - [AllOfWithSingleRef](docs/AllOfWithSingleRef.md) - [Animal](docs/Animal.md) - [AnyOfColor](docs/AnyOfColor.md) + - [AnyOfContainer](docs/AnyOfContainer.md) - [AnyOfPig](docs/AnyOfPig.md) - [ApiResponse](docs/ApiResponse.md) - [ArrayOfArrayOfModel](docs/ArrayOfArrayOfModel.md) @@ -218,11 +219,13 @@ Class | Method | HTTP request | Description - [ModelReturn](docs/ModelReturn.md) - [MultiArrays](docs/MultiArrays.md) - [Name](docs/Name.md) + - [NestedUnionContainer](docs/NestedUnionContainer.md) - [NullableClass](docs/NullableClass.md) - [NullableProperty](docs/NullableProperty.md) - [NumberOnly](docs/NumberOnly.md) - [ObjectToTestAdditionalProperties](docs/ObjectToTestAdditionalProperties.md) - [ObjectWithDeprecatedFields](docs/ObjectWithDeprecatedFields.md) + - [OneOfContainer](docs/OneOfContainer.md) - [OneOfEnumString](docs/OneOfEnumString.md) - [Order](docs/Order.md) - [OuterComposite](docs/OuterComposite.md) diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/AnyOfContainer.md b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/AnyOfContainer.md new file mode 100644 index 000000000000..7ecbf2b9ec25 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/AnyOfContainer.md @@ -0,0 +1,27 @@ +# AnyOfContainer + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +```python +from petstore_api.models.any_of_container import AnyOfContainer + +# TODO update the JSON string below +json = "{}" +# create an instance of AnyOfContainer from a JSON string +any_of_container_instance = AnyOfContainer.from_json(json) +# print the JSON string representation of the object +print AnyOfContainer.to_json() + +# convert the object into a dict +any_of_container_dict = any_of_container_instance.to_dict() +# create an instance of AnyOfContainer from a dict +any_of_container_from_dict = AnyOfContainer.from_dict(any_of_container_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/NestedUnionContainer.md b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/NestedUnionContainer.md new file mode 100644 index 000000000000..532ef1a6a8c5 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/NestedUnionContainer.md @@ -0,0 +1,27 @@ +# NestedUnionContainer + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +```python +from petstore_api.models.nested_union_container import NestedUnionContainer + +# TODO update the JSON string below +json = "{}" +# create an instance of NestedUnionContainer from a JSON string +nested_union_container_instance = NestedUnionContainer.from_json(json) +# print the JSON string representation of the object +print NestedUnionContainer.to_json() + +# convert the object into a dict +nested_union_container_dict = nested_union_container_instance.to_dict() +# create an instance of NestedUnionContainer from a dict +nested_union_container_from_dict = NestedUnionContainer.from_dict(nested_union_container_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/OneOfContainer.md b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/OneOfContainer.md new file mode 100644 index 000000000000..999134b44e73 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/OneOfContainer.md @@ -0,0 +1,27 @@ +# OneOfContainer + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +```python +from petstore_api.models.one_of_container import OneOfContainer + +# TODO update the JSON string below +json = "{}" +# create an instance of OneOfContainer from a JSON string +one_of_container_instance = OneOfContainer.from_json(json) +# print the JSON string representation of the object +print OneOfContainer.to_json() + +# convert the object into a dict +one_of_container_dict = one_of_container_instance.to_dict() +# create an instance of OneOfContainer from a dict +one_of_container_from_dict = OneOfContainer.from_dict(one_of_container_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 e89049d66426..acbd82969571 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 @@ -44,6 +44,7 @@ "AllOfWithSingleRef", "Animal", "AnyOfColor", + "AnyOfContainer", "AnyOfPig", "ApiResponse", "ArrayOfArrayOfModel", @@ -102,11 +103,13 @@ "ModelReturn", "MultiArrays", "Name", + "NestedUnionContainer", "NullableClass", "NullableProperty", "NumberOnly", "ObjectToTestAdditionalProperties", "ObjectWithDeprecatedFields", + "OneOfContainer", "OneOfEnumString", "Order", "OuterComposite", @@ -183,6 +186,7 @@ from petstore_api.models.all_of_with_single_ref import AllOfWithSingleRef as AllOfWithSingleRef from petstore_api.models.animal import Animal as Animal from petstore_api.models.any_of_color import AnyOfColor as AnyOfColor +from petstore_api.models.any_of_container import AnyOfContainer as AnyOfContainer from petstore_api.models.any_of_pig import AnyOfPig as AnyOfPig from petstore_api.models.api_response import ApiResponse as ApiResponse from petstore_api.models.array_of_array_of_model import ArrayOfArrayOfModel as ArrayOfArrayOfModel @@ -241,11 +245,13 @@ from petstore_api.models.model_return import ModelReturn as ModelReturn from petstore_api.models.multi_arrays import MultiArrays as MultiArrays from petstore_api.models.name import Name as Name +from petstore_api.models.nested_union_container import NestedUnionContainer as NestedUnionContainer from petstore_api.models.nullable_class import NullableClass as NullableClass from petstore_api.models.nullable_property import NullableProperty as NullableProperty from petstore_api.models.number_only import NumberOnly as NumberOnly from petstore_api.models.object_to_test_additional_properties import ObjectToTestAdditionalProperties as ObjectToTestAdditionalProperties from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields as ObjectWithDeprecatedFields +from petstore_api.models.one_of_container import OneOfContainer as OneOfContainer 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.outer_composite import OuterComposite as OuterComposite 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 51cf981e4b26..a16173fa0b2d 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 @@ -22,6 +22,7 @@ from petstore_api.models.all_of_with_single_ref import AllOfWithSingleRef from petstore_api.models.animal import Animal from petstore_api.models.any_of_color import AnyOfColor +from petstore_api.models.any_of_container import AnyOfContainer from petstore_api.models.any_of_pig import AnyOfPig from petstore_api.models.api_response import ApiResponse from petstore_api.models.array_of_array_of_model import ArrayOfArrayOfModel @@ -80,11 +81,13 @@ from petstore_api.models.model_return import ModelReturn from petstore_api.models.multi_arrays import MultiArrays from petstore_api.models.name import Name +from petstore_api.models.nested_union_container import NestedUnionContainer from petstore_api.models.nullable_class import NullableClass from petstore_api.models.nullable_property import NullableProperty from petstore_api.models.number_only import NumberOnly from petstore_api.models.object_to_test_additional_properties import ObjectToTestAdditionalProperties from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields +from petstore_api.models.one_of_container import OneOfContainer from petstore_api.models.one_of_enum_string import OneOfEnumString from petstore_api.models.order import Order from petstore_api.models.outer_composite import OuterComposite diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/any_of_container.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/any_of_container.py new file mode 100644 index 000000000000..d64ad5797413 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/any_of_container.py @@ -0,0 +1,210 @@ +# 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 Dict, List, Optional +from pydantic import BaseModel, Field, StrictInt, StrictStr, ValidationError, conlist, validator +from petstore_api.models.any_of_pig import AnyOfPig +from petstore_api.models.enum_string1 import EnumString1 +from petstore_api.models.nullable_class import NullableClass +from typing import Union, Any, List, TYPE_CHECKING +from pydantic import StrictStr, Field + +ANYOFCONTAINER_ANY_OF_SCHEMAS = ["Dict[str, AnyOfPig]", "List[AnyOfPig]", "List[EnumString1]", "List[NullableClass]", "List[int]", "str"] + +class AnyOfContainer(BaseModel): + """ + AnyOfContainer + """ + + # data type: str + anyof_schema_1_validator: Optional[StrictStr] = None + # data type: List[AnyOfPig] + anyof_schema_2_validator: Optional[conlist(AnyOfPig, min_items=1)] = None + # data type: Dict[str, AnyOfPig] + anyof_schema_3_validator: Optional[Dict[str, AnyOfPig]] = None + # data type: List[int] + anyof_schema_4_validator: Optional[conlist(StrictInt, min_items=1)] = None + # data type: List[EnumString1] + anyof_schema_5_validator: Optional[conlist(EnumString1, min_items=1)] = None + # data type: List[NullableClass] + anyof_schema_6_validator: Optional[conlist(NullableClass, min_items=1)] = None + if TYPE_CHECKING: + actual_instance: Union[Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str] + else: + actual_instance: Any + any_of_schemas: List[str] = Field(ANYOFCONTAINER_ANY_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_anyof(cls, v): + instance = AnyOfContainer.construct() + error_messages = [] + # validate data type: str + try: + instance.anyof_schema_1_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[AnyOfPig] + try: + instance.anyof_schema_2_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: Dict[str, AnyOfPig] + try: + instance.anyof_schema_3_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[int] + try: + instance.anyof_schema_4_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[EnumString1] + try: + instance.anyof_schema_5_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[NullableClass] + try: + instance.anyof_schema_6_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + if error_messages: + # no match + raise ValueError("No match found when setting the actual_instance in AnyOfContainer with anyOf schemas: Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: dict) -> AnyOfContainer: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> AnyOfContainer: + """Returns the object represented by the json string""" + instance = AnyOfContainer.construct() + error_messages = [] + # deserialize data into str + try: + # validation + instance.anyof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_1_validator + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[AnyOfPig] + try: + # validation + instance.anyof_schema_2_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_2_validator + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into Dict[str, AnyOfPig] + try: + # validation + instance.anyof_schema_3_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_3_validator + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[int] + try: + # validation + instance.anyof_schema_4_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_4_validator + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[EnumString1] + try: + # validation + instance.anyof_schema_5_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_5_validator + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[NullableClass] + try: + # validation + instance.anyof_schema_6_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_6_validator + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if error_messages: + # no match + raise ValueError("No match found when deserializing the JSON string into AnyOfContainer with anyOf schemas: Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str. 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 "null" + + to_json = getattr(self.actual_instance, "to_json", None) + if callable(to_json): + 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/petstore_api/models/nested_union_container.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/nested_union_container.py new file mode 100644 index 000000000000..da38958378c5 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/nested_union_container.py @@ -0,0 +1,148 @@ +# 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, Dict, List, Optional +from pydantic import BaseModel, Field, StrictStr, ValidationError, conlist, validator +from petstore_api.models.pig import Pig +from typing import Union, Any, List, TYPE_CHECKING +from pydantic import StrictStr, Field + +NESTEDUNIONCONTAINER_ONE_OF_SCHEMAS = ["List[Dict[str, List[Pig]]]", "str"] + +class NestedUnionContainer(BaseModel): + """ + NestedUnionContainer + """ + # data type: str + oneof_schema_1_validator: Optional[StrictStr] = None + # data type: List[Dict[str, List[Pig]]] + oneof_schema_2_validator: Optional[conlist(Dict[str, conlist(Pig)])] = None + if TYPE_CHECKING: + actual_instance: Union[List[Dict[str, List[Pig]]], str] + else: + actual_instance: Any + one_of_schemas: List[str] = Field(NESTEDUNIONCONTAINER_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 = NestedUnionContainer.construct() + error_messages = [] + match = 0 + # validate data type: str + try: + instance.oneof_schema_1_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[Dict[str, List[Pig]]] + try: + instance.oneof_schema_2_validator = v + 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 setting `actual_instance` in NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: dict) -> NestedUnionContainer: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> NestedUnionContainer: + """Returns the object represented by the json string""" + instance = NestedUnionContainer.construct() + error_messages = [] + match = 0 + + # deserialize data into str + try: + # validation + instance.oneof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_1_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[Dict[str, List[Pig]]] + try: + # validation + instance.oneof_schema_2_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_2_validator + 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 NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. 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/petstore_api/models/one_of_container.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/one_of_container.py new file mode 100644 index 000000000000..3c401495b193 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/one_of_container.py @@ -0,0 +1,218 @@ +# 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, Dict, List, Optional +from pydantic import BaseModel, Field, StrictInt, StrictStr, ValidationError, conlist, validator +from petstore_api.models.enum_string1 import EnumString1 +from petstore_api.models.nullable_class import NullableClass +from petstore_api.models.pig import Pig +from typing import Union, Any, List, TYPE_CHECKING +from pydantic import StrictStr, Field + +ONEOFCONTAINER_ONE_OF_SCHEMAS = ["Dict[str, Pig]", "List[EnumString1]", "List[NullableClass]", "List[Pig]", "List[int]", "str"] + +class OneOfContainer(BaseModel): + """ + OneOfContainer + """ + # data type: str + oneof_schema_1_validator: Optional[StrictStr] = None + # data type: List[Pig] + oneof_schema_2_validator: Optional[conlist(Pig, min_items=1)] = None + # data type: Dict[str, Pig] + oneof_schema_3_validator: Optional[Dict[str, Pig]] = None + # data type: List[int] + oneof_schema_4_validator: Optional[conlist(StrictInt, min_items=1)] = None + # data type: List[EnumString1] + oneof_schema_5_validator: Optional[conlist(EnumString1, min_items=1)] = None + # data type: List[NullableClass] + oneof_schema_6_validator: Optional[conlist(NullableClass, min_items=1)] = None + if TYPE_CHECKING: + actual_instance: Union[Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str] + else: + actual_instance: Any + one_of_schemas: List[str] = Field(ONEOFCONTAINER_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 = OneOfContainer.construct() + error_messages = [] + match = 0 + # validate data type: str + try: + instance.oneof_schema_1_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[Pig] + try: + instance.oneof_schema_2_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: Dict[str, Pig] + try: + instance.oneof_schema_3_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[int] + try: + instance.oneof_schema_4_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[EnumString1] + try: + instance.oneof_schema_5_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[NullableClass] + try: + instance.oneof_schema_6_validator = v + 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 setting `actual_instance` in OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: dict) -> OneOfContainer: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> OneOfContainer: + """Returns the object represented by the json string""" + instance = OneOfContainer.construct() + error_messages = [] + match = 0 + + # deserialize data into str + try: + # validation + instance.oneof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_1_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[Pig] + try: + # validation + instance.oneof_schema_2_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_2_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into Dict[str, Pig] + try: + # validation + instance.oneof_schema_3_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_3_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[int] + try: + # validation + instance.oneof_schema_4_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_4_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[EnumString1] + try: + # validation + instance.oneof_schema_5_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_5_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[NullableClass] + try: + # validation + instance.oneof_schema_6_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_6_validator + 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 OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. 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_any_of_container.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_any_of_container.py new file mode 100644 index 000000000000..bd3baa94089d --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_any_of_container.py @@ -0,0 +1,51 @@ +# 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.any_of_container import AnyOfContainer # noqa: E501 + +class TestAnyOfContainer(unittest.TestCase): + """AnyOfContainer unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> AnyOfContainer: + """Test AnyOfContainer + 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 `AnyOfContainer` + """ + model = AnyOfContainer() # noqa: E501 + if include_optional: + return AnyOfContainer( + ) + else: + return AnyOfContainer( + ) + """ + + def testAnyOfContainer(self): + """Test AnyOfContainer""" + # 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_nested_union_container.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_nested_union_container.py new file mode 100644 index 000000000000..4ace97ea8fcb --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_nested_union_container.py @@ -0,0 +1,51 @@ +# 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.nested_union_container import NestedUnionContainer # noqa: E501 + +class TestNestedUnionContainer(unittest.TestCase): + """NestedUnionContainer unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> NestedUnionContainer: + """Test NestedUnionContainer + 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 `NestedUnionContainer` + """ + model = NestedUnionContainer() # noqa: E501 + if include_optional: + return NestedUnionContainer( + ) + else: + return NestedUnionContainer( + ) + """ + + def testNestedUnionContainer(self): + """Test NestedUnionContainer""" + # 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_one_of_container.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_one_of_container.py new file mode 100644 index 000000000000..97209da4f723 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_one_of_container.py @@ -0,0 +1,51 @@ +# 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.one_of_container import OneOfContainer # noqa: E501 + +class TestOneOfContainer(unittest.TestCase): + """OneOfContainer unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> OneOfContainer: + """Test OneOfContainer + 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 `OneOfContainer` + """ + model = OneOfContainer() # noqa: E501 + if include_optional: + return OneOfContainer( + ) + else: + return OneOfContainer( + ) + """ + + def testOneOfContainer(self): + """Test OneOfContainer""" + # 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 3bdfdd3eebd9..23cf7fac7971 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python-pydantic-v1/.openapi-generator/FILES @@ -12,6 +12,7 @@ docs/AllOfWithSingleRef.md docs/Animal.md docs/AnotherFakeApi.md docs/AnyOfColor.md +docs/AnyOfContainer.md docs/AnyOfPig.md docs/ApiResponse.md docs/ArrayOfArrayOfModel.md @@ -74,11 +75,13 @@ docs/Model200Response.md docs/ModelReturn.md docs/MultiArrays.md docs/Name.md +docs/NestedUnionContainer.md docs/NullableClass.md docs/NullableProperty.md docs/NumberOnly.md docs/ObjectToTestAdditionalProperties.md docs/ObjectWithDeprecatedFields.md +docs/OneOfContainer.md docs/OneOfEnumString.md docs/Order.md docs/OuterComposite.md @@ -149,6 +152,7 @@ petstore_api/models/all_of_super_model.py petstore_api/models/all_of_with_single_ref.py petstore_api/models/animal.py petstore_api/models/any_of_color.py +petstore_api/models/any_of_container.py petstore_api/models/any_of_pig.py petstore_api/models/api_response.py petstore_api/models/array_of_array_of_model.py @@ -207,11 +211,13 @@ petstore_api/models/model200_response.py petstore_api/models/model_return.py petstore_api/models/multi_arrays.py petstore_api/models/name.py +petstore_api/models/nested_union_container.py petstore_api/models/nullable_class.py petstore_api/models/nullable_property.py petstore_api/models/number_only.py petstore_api/models/object_to_test_additional_properties.py petstore_api/models/object_with_deprecated_fields.py +petstore_api/models/one_of_container.py petstore_api/models/one_of_enum_string.py petstore_api/models/order.py petstore_api/models/outer_composite.py diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/README.md b/samples/openapi3/client/petstore/python-pydantic-v1/README.md index df20391210ef..958b5a902451 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/README.md +++ b/samples/openapi3/client/petstore/python-pydantic-v1/README.md @@ -160,6 +160,7 @@ Class | Method | HTTP request | Description - [AllOfWithSingleRef](docs/AllOfWithSingleRef.md) - [Animal](docs/Animal.md) - [AnyOfColor](docs/AnyOfColor.md) + - [AnyOfContainer](docs/AnyOfContainer.md) - [AnyOfPig](docs/AnyOfPig.md) - [ApiResponse](docs/ApiResponse.md) - [ArrayOfArrayOfModel](docs/ArrayOfArrayOfModel.md) @@ -218,11 +219,13 @@ Class | Method | HTTP request | Description - [ModelReturn](docs/ModelReturn.md) - [MultiArrays](docs/MultiArrays.md) - [Name](docs/Name.md) + - [NestedUnionContainer](docs/NestedUnionContainer.md) - [NullableClass](docs/NullableClass.md) - [NullableProperty](docs/NullableProperty.md) - [NumberOnly](docs/NumberOnly.md) - [ObjectToTestAdditionalProperties](docs/ObjectToTestAdditionalProperties.md) - [ObjectWithDeprecatedFields](docs/ObjectWithDeprecatedFields.md) + - [OneOfContainer](docs/OneOfContainer.md) - [OneOfEnumString](docs/OneOfEnumString.md) - [Order](docs/Order.md) - [OuterComposite](docs/OuterComposite.md) diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/docs/AnyOfContainer.md b/samples/openapi3/client/petstore/python-pydantic-v1/docs/AnyOfContainer.md new file mode 100644 index 000000000000..7ecbf2b9ec25 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/docs/AnyOfContainer.md @@ -0,0 +1,27 @@ +# AnyOfContainer + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +```python +from petstore_api.models.any_of_container import AnyOfContainer + +# TODO update the JSON string below +json = "{}" +# create an instance of AnyOfContainer from a JSON string +any_of_container_instance = AnyOfContainer.from_json(json) +# print the JSON string representation of the object +print AnyOfContainer.to_json() + +# convert the object into a dict +any_of_container_dict = any_of_container_instance.to_dict() +# create an instance of AnyOfContainer from a dict +any_of_container_from_dict = AnyOfContainer.from_dict(any_of_container_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/NestedUnionContainer.md b/samples/openapi3/client/petstore/python-pydantic-v1/docs/NestedUnionContainer.md new file mode 100644 index 000000000000..532ef1a6a8c5 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/docs/NestedUnionContainer.md @@ -0,0 +1,27 @@ +# NestedUnionContainer + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +```python +from petstore_api.models.nested_union_container import NestedUnionContainer + +# TODO update the JSON string below +json = "{}" +# create an instance of NestedUnionContainer from a JSON string +nested_union_container_instance = NestedUnionContainer.from_json(json) +# print the JSON string representation of the object +print NestedUnionContainer.to_json() + +# convert the object into a dict +nested_union_container_dict = nested_union_container_instance.to_dict() +# create an instance of NestedUnionContainer from a dict +nested_union_container_from_dict = NestedUnionContainer.from_dict(nested_union_container_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/OneOfContainer.md b/samples/openapi3/client/petstore/python-pydantic-v1/docs/OneOfContainer.md new file mode 100644 index 000000000000..999134b44e73 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/docs/OneOfContainer.md @@ -0,0 +1,27 @@ +# OneOfContainer + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +```python +from petstore_api.models.one_of_container import OneOfContainer + +# TODO update the JSON string below +json = "{}" +# create an instance of OneOfContainer from a JSON string +one_of_container_instance = OneOfContainer.from_json(json) +# print the JSON string representation of the object +print OneOfContainer.to_json() + +# convert the object into a dict +one_of_container_dict = one_of_container_instance.to_dict() +# create an instance of OneOfContainer from a dict +one_of_container_from_dict = OneOfContainer.from_dict(one_of_container_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 e89049d66426..acbd82969571 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 @@ -44,6 +44,7 @@ "AllOfWithSingleRef", "Animal", "AnyOfColor", + "AnyOfContainer", "AnyOfPig", "ApiResponse", "ArrayOfArrayOfModel", @@ -102,11 +103,13 @@ "ModelReturn", "MultiArrays", "Name", + "NestedUnionContainer", "NullableClass", "NullableProperty", "NumberOnly", "ObjectToTestAdditionalProperties", "ObjectWithDeprecatedFields", + "OneOfContainer", "OneOfEnumString", "Order", "OuterComposite", @@ -183,6 +186,7 @@ from petstore_api.models.all_of_with_single_ref import AllOfWithSingleRef as AllOfWithSingleRef from petstore_api.models.animal import Animal as Animal from petstore_api.models.any_of_color import AnyOfColor as AnyOfColor +from petstore_api.models.any_of_container import AnyOfContainer as AnyOfContainer from petstore_api.models.any_of_pig import AnyOfPig as AnyOfPig from petstore_api.models.api_response import ApiResponse as ApiResponse from petstore_api.models.array_of_array_of_model import ArrayOfArrayOfModel as ArrayOfArrayOfModel @@ -241,11 +245,13 @@ from petstore_api.models.model_return import ModelReturn as ModelReturn from petstore_api.models.multi_arrays import MultiArrays as MultiArrays from petstore_api.models.name import Name as Name +from petstore_api.models.nested_union_container import NestedUnionContainer as NestedUnionContainer from petstore_api.models.nullable_class import NullableClass as NullableClass from petstore_api.models.nullable_property import NullableProperty as NullableProperty from petstore_api.models.number_only import NumberOnly as NumberOnly from petstore_api.models.object_to_test_additional_properties import ObjectToTestAdditionalProperties as ObjectToTestAdditionalProperties from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields as ObjectWithDeprecatedFields +from petstore_api.models.one_of_container import OneOfContainer as OneOfContainer 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.outer_composite import OuterComposite as OuterComposite 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 51cf981e4b26..a16173fa0b2d 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 @@ -22,6 +22,7 @@ from petstore_api.models.all_of_with_single_ref import AllOfWithSingleRef from petstore_api.models.animal import Animal from petstore_api.models.any_of_color import AnyOfColor +from petstore_api.models.any_of_container import AnyOfContainer from petstore_api.models.any_of_pig import AnyOfPig from petstore_api.models.api_response import ApiResponse from petstore_api.models.array_of_array_of_model import ArrayOfArrayOfModel @@ -80,11 +81,13 @@ from petstore_api.models.model_return import ModelReturn from petstore_api.models.multi_arrays import MultiArrays from petstore_api.models.name import Name +from petstore_api.models.nested_union_container import NestedUnionContainer from petstore_api.models.nullable_class import NullableClass from petstore_api.models.nullable_property import NullableProperty from petstore_api.models.number_only import NumberOnly from petstore_api.models.object_to_test_additional_properties import ObjectToTestAdditionalProperties from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields +from petstore_api.models.one_of_container import OneOfContainer from petstore_api.models.one_of_enum_string import OneOfEnumString from petstore_api.models.order import Order from petstore_api.models.outer_composite import OuterComposite diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/any_of_container.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/any_of_container.py new file mode 100644 index 000000000000..d64ad5797413 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/any_of_container.py @@ -0,0 +1,210 @@ +# 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 Dict, List, Optional +from pydantic import BaseModel, Field, StrictInt, StrictStr, ValidationError, conlist, validator +from petstore_api.models.any_of_pig import AnyOfPig +from petstore_api.models.enum_string1 import EnumString1 +from petstore_api.models.nullable_class import NullableClass +from typing import Union, Any, List, TYPE_CHECKING +from pydantic import StrictStr, Field + +ANYOFCONTAINER_ANY_OF_SCHEMAS = ["Dict[str, AnyOfPig]", "List[AnyOfPig]", "List[EnumString1]", "List[NullableClass]", "List[int]", "str"] + +class AnyOfContainer(BaseModel): + """ + AnyOfContainer + """ + + # data type: str + anyof_schema_1_validator: Optional[StrictStr] = None + # data type: List[AnyOfPig] + anyof_schema_2_validator: Optional[conlist(AnyOfPig, min_items=1)] = None + # data type: Dict[str, AnyOfPig] + anyof_schema_3_validator: Optional[Dict[str, AnyOfPig]] = None + # data type: List[int] + anyof_schema_4_validator: Optional[conlist(StrictInt, min_items=1)] = None + # data type: List[EnumString1] + anyof_schema_5_validator: Optional[conlist(EnumString1, min_items=1)] = None + # data type: List[NullableClass] + anyof_schema_6_validator: Optional[conlist(NullableClass, min_items=1)] = None + if TYPE_CHECKING: + actual_instance: Union[Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str] + else: + actual_instance: Any + any_of_schemas: List[str] = Field(ANYOFCONTAINER_ANY_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_anyof(cls, v): + instance = AnyOfContainer.construct() + error_messages = [] + # validate data type: str + try: + instance.anyof_schema_1_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[AnyOfPig] + try: + instance.anyof_schema_2_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: Dict[str, AnyOfPig] + try: + instance.anyof_schema_3_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[int] + try: + instance.anyof_schema_4_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[EnumString1] + try: + instance.anyof_schema_5_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[NullableClass] + try: + instance.anyof_schema_6_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + if error_messages: + # no match + raise ValueError("No match found when setting the actual_instance in AnyOfContainer with anyOf schemas: Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: dict) -> AnyOfContainer: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> AnyOfContainer: + """Returns the object represented by the json string""" + instance = AnyOfContainer.construct() + error_messages = [] + # deserialize data into str + try: + # validation + instance.anyof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_1_validator + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[AnyOfPig] + try: + # validation + instance.anyof_schema_2_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_2_validator + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into Dict[str, AnyOfPig] + try: + # validation + instance.anyof_schema_3_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_3_validator + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[int] + try: + # validation + instance.anyof_schema_4_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_4_validator + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[EnumString1] + try: + # validation + instance.anyof_schema_5_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_5_validator + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[NullableClass] + try: + # validation + instance.anyof_schema_6_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_6_validator + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if error_messages: + # no match + raise ValueError("No match found when deserializing the JSON string into AnyOfContainer with anyOf schemas: Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str. 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 "null" + + to_json = getattr(self.actual_instance, "to_json", None) + if callable(to_json): + 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/petstore_api/models/nested_union_container.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/nested_union_container.py new file mode 100644 index 000000000000..da38958378c5 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/nested_union_container.py @@ -0,0 +1,148 @@ +# 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, Dict, List, Optional +from pydantic import BaseModel, Field, StrictStr, ValidationError, conlist, validator +from petstore_api.models.pig import Pig +from typing import Union, Any, List, TYPE_CHECKING +from pydantic import StrictStr, Field + +NESTEDUNIONCONTAINER_ONE_OF_SCHEMAS = ["List[Dict[str, List[Pig]]]", "str"] + +class NestedUnionContainer(BaseModel): + """ + NestedUnionContainer + """ + # data type: str + oneof_schema_1_validator: Optional[StrictStr] = None + # data type: List[Dict[str, List[Pig]]] + oneof_schema_2_validator: Optional[conlist(Dict[str, conlist(Pig)])] = None + if TYPE_CHECKING: + actual_instance: Union[List[Dict[str, List[Pig]]], str] + else: + actual_instance: Any + one_of_schemas: List[str] = Field(NESTEDUNIONCONTAINER_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 = NestedUnionContainer.construct() + error_messages = [] + match = 0 + # validate data type: str + try: + instance.oneof_schema_1_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[Dict[str, List[Pig]]] + try: + instance.oneof_schema_2_validator = v + 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 setting `actual_instance` in NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: dict) -> NestedUnionContainer: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> NestedUnionContainer: + """Returns the object represented by the json string""" + instance = NestedUnionContainer.construct() + error_messages = [] + match = 0 + + # deserialize data into str + try: + # validation + instance.oneof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_1_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[Dict[str, List[Pig]]] + try: + # validation + instance.oneof_schema_2_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_2_validator + 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 NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. 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/petstore_api/models/one_of_container.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/one_of_container.py new file mode 100644 index 000000000000..3c401495b193 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/one_of_container.py @@ -0,0 +1,218 @@ +# 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, Dict, List, Optional +from pydantic import BaseModel, Field, StrictInt, StrictStr, ValidationError, conlist, validator +from petstore_api.models.enum_string1 import EnumString1 +from petstore_api.models.nullable_class import NullableClass +from petstore_api.models.pig import Pig +from typing import Union, Any, List, TYPE_CHECKING +from pydantic import StrictStr, Field + +ONEOFCONTAINER_ONE_OF_SCHEMAS = ["Dict[str, Pig]", "List[EnumString1]", "List[NullableClass]", "List[Pig]", "List[int]", "str"] + +class OneOfContainer(BaseModel): + """ + OneOfContainer + """ + # data type: str + oneof_schema_1_validator: Optional[StrictStr] = None + # data type: List[Pig] + oneof_schema_2_validator: Optional[conlist(Pig, min_items=1)] = None + # data type: Dict[str, Pig] + oneof_schema_3_validator: Optional[Dict[str, Pig]] = None + # data type: List[int] + oneof_schema_4_validator: Optional[conlist(StrictInt, min_items=1)] = None + # data type: List[EnumString1] + oneof_schema_5_validator: Optional[conlist(EnumString1, min_items=1)] = None + # data type: List[NullableClass] + oneof_schema_6_validator: Optional[conlist(NullableClass, min_items=1)] = None + if TYPE_CHECKING: + actual_instance: Union[Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str] + else: + actual_instance: Any + one_of_schemas: List[str] = Field(ONEOFCONTAINER_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 = OneOfContainer.construct() + error_messages = [] + match = 0 + # validate data type: str + try: + instance.oneof_schema_1_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[Pig] + try: + instance.oneof_schema_2_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: Dict[str, Pig] + try: + instance.oneof_schema_3_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[int] + try: + instance.oneof_schema_4_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[EnumString1] + try: + instance.oneof_schema_5_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[NullableClass] + try: + instance.oneof_schema_6_validator = v + 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 setting `actual_instance` in OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: dict) -> OneOfContainer: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> OneOfContainer: + """Returns the object represented by the json string""" + instance = OneOfContainer.construct() + error_messages = [] + match = 0 + + # deserialize data into str + try: + # validation + instance.oneof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_1_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[Pig] + try: + # validation + instance.oneof_schema_2_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_2_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into Dict[str, Pig] + try: + # validation + instance.oneof_schema_3_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_3_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[int] + try: + # validation + instance.oneof_schema_4_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_4_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[EnumString1] + try: + # validation + instance.oneof_schema_5_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_5_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[NullableClass] + try: + # validation + instance.oneof_schema_6_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_6_validator + 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 OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. 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_any_of_container.py b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_any_of_container.py new file mode 100644 index 000000000000..bd3baa94089d --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_any_of_container.py @@ -0,0 +1,51 @@ +# 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.any_of_container import AnyOfContainer # noqa: E501 + +class TestAnyOfContainer(unittest.TestCase): + """AnyOfContainer unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> AnyOfContainer: + """Test AnyOfContainer + 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 `AnyOfContainer` + """ + model = AnyOfContainer() # noqa: E501 + if include_optional: + return AnyOfContainer( + ) + else: + return AnyOfContainer( + ) + """ + + def testAnyOfContainer(self): + """Test AnyOfContainer""" + # 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_nested_union_container.py b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_nested_union_container.py new file mode 100644 index 000000000000..4ace97ea8fcb --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_nested_union_container.py @@ -0,0 +1,51 @@ +# 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.nested_union_container import NestedUnionContainer # noqa: E501 + +class TestNestedUnionContainer(unittest.TestCase): + """NestedUnionContainer unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> NestedUnionContainer: + """Test NestedUnionContainer + 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 `NestedUnionContainer` + """ + model = NestedUnionContainer() # noqa: E501 + if include_optional: + return NestedUnionContainer( + ) + else: + return NestedUnionContainer( + ) + """ + + def testNestedUnionContainer(self): + """Test NestedUnionContainer""" + # 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_one_of_container.py b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_one_of_container.py new file mode 100644 index 000000000000..97209da4f723 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_one_of_container.py @@ -0,0 +1,51 @@ +# 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.one_of_container import OneOfContainer # noqa: E501 + +class TestOneOfContainer(unittest.TestCase): + """OneOfContainer unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> OneOfContainer: + """Test OneOfContainer + 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 `OneOfContainer` + """ + model = OneOfContainer() # noqa: E501 + if include_optional: + return OneOfContainer( + ) + else: + return OneOfContainer( + ) + """ + + def testOneOfContainer(self): + """Test OneOfContainer""" + # 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 1eb565d74f11..6af8faf4dffe 100755 --- a/samples/openapi3/client/petstore/python/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python/.openapi-generator/FILES @@ -12,6 +12,7 @@ docs/AllOfWithSingleRef.md docs/Animal.md docs/AnotherFakeApi.md docs/AnyOfColor.md +docs/AnyOfContainer.md docs/AnyOfPig.md docs/ArrayOfArrayOfModel.md docs/ArrayOfArrayOfNumberOnly.md @@ -74,11 +75,13 @@ docs/ModelField.md docs/ModelReturn.md docs/MultiArrays.md docs/Name.md +docs/NestedUnionContainer.md docs/NullableClass.md docs/NullableProperty.md docs/NumberOnly.md docs/ObjectToTestAdditionalProperties.md docs/ObjectWithDeprecatedFields.md +docs/OneOfContainer.md docs/OneOfEnumString.md docs/Order.md docs/OuterComposite.md @@ -149,6 +152,7 @@ petstore_api/models/all_of_super_model.py petstore_api/models/all_of_with_single_ref.py petstore_api/models/animal.py petstore_api/models/any_of_color.py +petstore_api/models/any_of_container.py petstore_api/models/any_of_pig.py petstore_api/models/array_of_array_of_model.py petstore_api/models/array_of_array_of_number_only.py @@ -207,11 +211,13 @@ petstore_api/models/model_field.py petstore_api/models/model_return.py petstore_api/models/multi_arrays.py petstore_api/models/name.py +petstore_api/models/nested_union_container.py petstore_api/models/nullable_class.py petstore_api/models/nullable_property.py petstore_api/models/number_only.py petstore_api/models/object_to_test_additional_properties.py petstore_api/models/object_with_deprecated_fields.py +petstore_api/models/one_of_container.py petstore_api/models/one_of_enum_string.py petstore_api/models/order.py petstore_api/models/outer_composite.py diff --git a/samples/openapi3/client/petstore/python/README.md b/samples/openapi3/client/petstore/python/README.md index 5a3798c1b20a..ec3e046da1a2 100755 --- a/samples/openapi3/client/petstore/python/README.md +++ b/samples/openapi3/client/petstore/python/README.md @@ -164,6 +164,7 @@ Class | Method | HTTP request | Description - [AllOfWithSingleRef](docs/AllOfWithSingleRef.md) - [Animal](docs/Animal.md) - [AnyOfColor](docs/AnyOfColor.md) + - [AnyOfContainer](docs/AnyOfContainer.md) - [AnyOfPig](docs/AnyOfPig.md) - [ArrayOfArrayOfModel](docs/ArrayOfArrayOfModel.md) - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) @@ -222,11 +223,13 @@ Class | Method | HTTP request | Description - [ModelReturn](docs/ModelReturn.md) - [MultiArrays](docs/MultiArrays.md) - [Name](docs/Name.md) + - [NestedUnionContainer](docs/NestedUnionContainer.md) - [NullableClass](docs/NullableClass.md) - [NullableProperty](docs/NullableProperty.md) - [NumberOnly](docs/NumberOnly.md) - [ObjectToTestAdditionalProperties](docs/ObjectToTestAdditionalProperties.md) - [ObjectWithDeprecatedFields](docs/ObjectWithDeprecatedFields.md) + - [OneOfContainer](docs/OneOfContainer.md) - [OneOfEnumString](docs/OneOfEnumString.md) - [Order](docs/Order.md) - [OuterComposite](docs/OuterComposite.md) diff --git a/samples/openapi3/client/petstore/python/docs/AnyOfContainer.md b/samples/openapi3/client/petstore/python/docs/AnyOfContainer.md new file mode 100644 index 000000000000..4644b55530c7 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/AnyOfContainer.md @@ -0,0 +1,28 @@ +# AnyOfContainer + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +```python +from petstore_api.models.any_of_container import AnyOfContainer + +# TODO update the JSON string below +json = "{}" +# create an instance of AnyOfContainer from a JSON string +any_of_container_instance = AnyOfContainer.from_json(json) +# print the JSON string representation of the object +print(AnyOfContainer.to_json()) + +# convert the object into a dict +any_of_container_dict = any_of_container_instance.to_dict() +# create an instance of AnyOfContainer from a dict +any_of_container_from_dict = AnyOfContainer.from_dict(any_of_container_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/NestedUnionContainer.md b/samples/openapi3/client/petstore/python/docs/NestedUnionContainer.md new file mode 100644 index 000000000000..9cf24bc0668a --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/NestedUnionContainer.md @@ -0,0 +1,28 @@ +# NestedUnionContainer + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +```python +from petstore_api.models.nested_union_container import NestedUnionContainer + +# TODO update the JSON string below +json = "{}" +# create an instance of NestedUnionContainer from a JSON string +nested_union_container_instance = NestedUnionContainer.from_json(json) +# print the JSON string representation of the object +print(NestedUnionContainer.to_json()) + +# convert the object into a dict +nested_union_container_dict = nested_union_container_instance.to_dict() +# create an instance of NestedUnionContainer from a dict +nested_union_container_from_dict = NestedUnionContainer.from_dict(nested_union_container_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/OneOfContainer.md b/samples/openapi3/client/petstore/python/docs/OneOfContainer.md new file mode 100644 index 000000000000..50d13d3399ac --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/OneOfContainer.md @@ -0,0 +1,28 @@ +# OneOfContainer + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +```python +from petstore_api.models.one_of_container import OneOfContainer + +# TODO update the JSON string below +json = "{}" +# create an instance of OneOfContainer from a JSON string +one_of_container_instance = OneOfContainer.from_json(json) +# print the JSON string representation of the object +print(OneOfContainer.to_json()) + +# convert the object into a dict +one_of_container_dict = one_of_container_instance.to_dict() +# create an instance of OneOfContainer from a dict +one_of_container_from_dict = OneOfContainer.from_dict(one_of_container_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 c7f461775f59..341a3e34513b 100755 --- a/samples/openapi3/client/petstore/python/petstore_api/__init__.py +++ b/samples/openapi3/client/petstore/python/petstore_api/__init__.py @@ -44,6 +44,7 @@ "AllOfWithSingleRef", "Animal", "AnyOfColor", + "AnyOfContainer", "AnyOfPig", "ArrayOfArrayOfModel", "ArrayOfArrayOfNumberOnly", @@ -102,11 +103,13 @@ "ModelReturn", "MultiArrays", "Name", + "NestedUnionContainer", "NullableClass", "NullableProperty", "NumberOnly", "ObjectToTestAdditionalProperties", "ObjectWithDeprecatedFields", + "OneOfContainer", "OneOfEnumString", "Order", "OuterComposite", @@ -183,6 +186,7 @@ from petstore_api.models.all_of_with_single_ref import AllOfWithSingleRef as AllOfWithSingleRef from petstore_api.models.animal import Animal as Animal from petstore_api.models.any_of_color import AnyOfColor as AnyOfColor +from petstore_api.models.any_of_container import AnyOfContainer as AnyOfContainer from petstore_api.models.any_of_pig import AnyOfPig as AnyOfPig from petstore_api.models.array_of_array_of_model import ArrayOfArrayOfModel as ArrayOfArrayOfModel from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly as ArrayOfArrayOfNumberOnly @@ -241,11 +245,13 @@ from petstore_api.models.model_return import ModelReturn as ModelReturn from petstore_api.models.multi_arrays import MultiArrays as MultiArrays from petstore_api.models.name import Name as Name +from petstore_api.models.nested_union_container import NestedUnionContainer as NestedUnionContainer from petstore_api.models.nullable_class import NullableClass as NullableClass from petstore_api.models.nullable_property import NullableProperty as NullableProperty from petstore_api.models.number_only import NumberOnly as NumberOnly from petstore_api.models.object_to_test_additional_properties import ObjectToTestAdditionalProperties as ObjectToTestAdditionalProperties from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields as ObjectWithDeprecatedFields +from petstore_api.models.one_of_container import OneOfContainer as OneOfContainer 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.outer_composite import OuterComposite as OuterComposite 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 308e6dfc3ebb..336021dd171d 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py @@ -21,6 +21,7 @@ from petstore_api.models.all_of_with_single_ref import AllOfWithSingleRef from petstore_api.models.animal import Animal from petstore_api.models.any_of_color import AnyOfColor +from petstore_api.models.any_of_container import AnyOfContainer from petstore_api.models.any_of_pig import AnyOfPig from petstore_api.models.array_of_array_of_model import ArrayOfArrayOfModel from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly @@ -79,11 +80,13 @@ from petstore_api.models.model_return import ModelReturn from petstore_api.models.multi_arrays import MultiArrays from petstore_api.models.name import Name +from petstore_api.models.nested_union_container import NestedUnionContainer from petstore_api.models.nullable_class import NullableClass from petstore_api.models.nullable_property import NullableProperty from petstore_api.models.number_only import NumberOnly from petstore_api.models.object_to_test_additional_properties import ObjectToTestAdditionalProperties from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecatedFields +from petstore_api.models.one_of_container import OneOfContainer from petstore_api.models.one_of_enum_string import OneOfEnumString from petstore_api.models.order import Order from petstore_api.models.outer_composite import OuterComposite diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/any_of_color.py b/samples/openapi3/client/petstore/python/petstore_api/models/any_of_color.py index f6d277e79498..80858f210971 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/any_of_color.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/any_of_color.py @@ -23,6 +23,17 @@ from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict from typing_extensions import Literal, Self from pydantic import Field +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + ANYOFCOLOR_ANY_OF_SCHEMAS = ["List[int]", "str"] @@ -97,21 +108,23 @@ def from_json(cls, json_str: str) -> Self: error_messages = [] # deserialize data into List[int] try: + data = json.loads(json_str) # validation - instance.anyof_schema_1_validator = json.loads(json_str) + instance.anyof_schema_1_validator = data # assign value to actual_instance instance.actual_instance = instance.anyof_schema_1_validator return instance - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) # deserialize data into List[int] try: + data = json.loads(json_str) # validation - instance.anyof_schema_2_validator = json.loads(json_str) + instance.anyof_schema_2_validator = data # assign value to actual_instance instance.actual_instance = instance.anyof_schema_2_validator return instance - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) # deserialize data into str try: @@ -137,17 +150,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], List[int], str]]: """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: - return self.actual_instance + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/any_of_container.py b/samples/openapi3/client/petstore/python/petstore_api/models/any_of_container.py new file mode 100644 index 000000000000..534b12f2dbb3 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/models/any_of_container.py @@ -0,0 +1,225 @@ +# 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 pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr, ValidationError, field_validator +from typing import Dict, List, Optional +from typing_extensions import Annotated +from petstore_api.models.any_of_pig import AnyOfPig +from petstore_api.models.enum_string1 import EnumString1 +from petstore_api.models.nullable_class import NullableClass +from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict +from typing_extensions import Literal, Self +from pydantic import Field +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + + +ANYOFCONTAINER_ANY_OF_SCHEMAS = ["Dict[str, AnyOfPig]", "List[AnyOfPig]", "List[EnumString1]", "List[NullableClass]", "List[int]", "str"] + +class AnyOfContainer(BaseModel): + """ + AnyOfContainer + """ + + # data type: str + anyof_schema_1_validator: Optional[StrictStr] = None + # data type: List[AnyOfPig] + anyof_schema_2_validator: Optional[Annotated[List[AnyOfPig], Field(min_length=1)]] = None + # data type: Dict[str, AnyOfPig] + anyof_schema_3_validator: Optional[Dict[str, AnyOfPig]] = None + # data type: List[int] + anyof_schema_4_validator: Optional[Annotated[List[StrictInt], Field(min_length=1)]] = None + # data type: List[EnumString1] + anyof_schema_5_validator: Optional[Annotated[List[EnumString1], Field(min_length=1)]] = None + # data type: List[NullableClass] + anyof_schema_6_validator: Optional[Annotated[List[NullableClass], Field(min_length=1)]] = None + if TYPE_CHECKING: + actual_instance: Optional[Union[Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str]] = None + else: + actual_instance: Any = None + any_of_schemas: Set[str] = { "Dict[str, AnyOfPig]", "List[AnyOfPig]", "List[EnumString1]", "List[NullableClass]", "List[int]", "str" } + + model_config = { + "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_anyof(cls, v): + instance = AnyOfContainer.model_construct() + error_messages = [] + # validate data type: str + try: + instance.anyof_schema_1_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[AnyOfPig] + try: + instance.anyof_schema_2_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: Dict[str, AnyOfPig] + try: + instance.anyof_schema_3_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[int] + try: + instance.anyof_schema_4_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[EnumString1] + try: + instance.anyof_schema_5_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[NullableClass] + try: + instance.anyof_schema_6_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + if error_messages: + # no match + raise ValueError("No match found when setting the actual_instance in AnyOfContainer with anyOf schemas: Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: 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 = [] + # deserialize data into str + try: + # validation + instance.anyof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_1_validator + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[AnyOfPig] + try: + data = json.loads(json_str) + data = ([(AnyOfPig.from_dict(_item0) if _item0 is not None else None) for _item0 in data] if isinstance(data, list) else data) + # validation + instance.anyof_schema_2_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_2_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into Dict[str, AnyOfPig] + try: + data = json.loads(json_str) + data = ({_key0: (AnyOfPig.from_dict(_item0) if _item0 is not None else None) for _key0, _item0 in data.items()} if isinstance(data, dict) else data) + # validation + instance.anyof_schema_3_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_3_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[int] + try: + data = json.loads(json_str) + # validation + instance.anyof_schema_4_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_4_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[EnumString1] + try: + data = json.loads(json_str) + # validation + instance.anyof_schema_5_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_5_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[NullableClass] + try: + data = json.loads(json_str) + # validation + instance.anyof_schema_6_validator = data + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_6_validator + return instance + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + + if error_messages: + # no match + raise ValueError("No match found when deserializing the JSON string into AnyOfContainer with anyOf schemas: Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str. 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(to_jsonable_python(self.to_dict())) + + def to_dict(self) -> Optional[Union[Dict[str, Any], Dict[str, AnyOfPig], List[AnyOfPig], List[EnumString1], List[NullableClass], List[int], str]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + return _to_dict(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/petstore_api/models/any_of_pig.py b/samples/openapi3/client/petstore/python/petstore_api/models/any_of_pig.py index c949e136f415..752848a7d1aa 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/any_of_pig.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/any_of_pig.py @@ -24,6 +24,17 @@ from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict from typing_extensions import Literal, Self from pydantic import Field +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + ANYOFPIG_ANY_OF_SCHEMAS = ["BasquePig", "DanishPig"] @@ -115,17 +126,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], BasquePig, DanishPig]]: """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: - return self.actual_instance + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/color.py b/samples/openapi3/client/petstore/python/petstore_api/models/color.py index bb740fb597d4..a05b275ff594 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/color.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/color.py @@ -21,6 +21,17 @@ from pydantic import StrictStr, Field from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + COLOR_ONE_OF_SCHEMAS = ["List[int]", "str"] @@ -104,21 +115,23 @@ def from_json(cls, json_str: Optional[str]) -> Self: # deserialize data into List[int] try: + data = json.loads(json_str) # validation - instance.oneof_schema_1_validator = json.loads(json_str) + instance.oneof_schema_1_validator = data # assign value to actual_instance instance.actual_instance = instance.oneof_schema_1_validator match += 1 - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) # deserialize data into List[int] try: + data = json.loads(json_str) # validation - instance.oneof_schema_2_validator = json.loads(json_str) + instance.oneof_schema_2_validator = data # assign value to actual_instance instance.actual_instance = instance.oneof_schema_2_validator match += 1 - except (ValidationError, ValueError) as e: + except (ValidationError, ValueError, TypeError, AttributeError) as e: error_messages.append(str(e)) # deserialize data into str try: @@ -147,18 +160,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], List[int], str]]: """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 + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/int_or_string.py b/samples/openapi3/client/petstore/python/petstore_api/models/int_or_string.py index f2a5a0a2d4a3..21412adc27c3 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/int_or_string.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/int_or_string.py @@ -21,6 +21,17 @@ from pydantic import StrictStr, Field from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + INTORSTRING_ONE_OF_SCHEMAS = ["int", "str"] @@ -124,18 +135,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], int, str]]: """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 + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/nested_union_container.py b/samples/openapi3/client/petstore/python/petstore_api/models/nested_union_container.py new file mode 100644 index 000000000000..932f246f15f3 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/models/nested_union_container.py @@ -0,0 +1,153 @@ +# 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, Dict, List, Optional +from petstore_api.models.pig import Pig +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + + +NESTEDUNIONCONTAINER_ONE_OF_SCHEMAS = ["List[Dict[str, List[Pig]]]", "str"] + +class NestedUnionContainer(BaseModel): + """ + NestedUnionContainer + """ + # data type: str + oneof_schema_1_validator: Optional[StrictStr] = None + # data type: List[Dict[str, List[Pig]]] + oneof_schema_2_validator: Optional[List[Dict[str, List[Pig]]]] = None + actual_instance: Optional[Union[List[Dict[str, List[Pig]]], str]] = None + one_of_schemas: Set[str] = { "List[Dict[str, List[Pig]]]", "str" } + + 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 = NestedUnionContainer.model_construct() + error_messages = [] + match = 0 + # validate data type: str + try: + instance.oneof_schema_1_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[Dict[str, List[Pig]]] + try: + instance.oneof_schema_2_validator = v + 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 setting `actual_instance` in NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. 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 str + try: + # validation + instance.oneof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_1_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[Dict[str, List[Pig]]] + try: + data = json.loads(json_str) + data = ([({_key1: ([(Pig.from_dict(_item2) if _item2 is not None else None) for _item2 in _item1] if isinstance(_item1, list) else _item1) for _key1, _item1 in _item0.items()} if isinstance(_item0, dict) else _item0) for _item0 in data] if isinstance(data, list) else data) + # validation + instance.oneof_schema_2_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_2_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) 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 NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into NestedUnionContainer with oneOf schemas: List[Dict[str, List[Pig]]], str. 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(to_jsonable_python(self.to_dict())) + + def to_dict(self) -> Optional[Union[Dict[str, Any], List[Dict[str, List[Pig]]], str]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + return _to_dict(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/petstore_api/models/one_of_container.py b/samples/openapi3/client/petstore/python/petstore_api/models/one_of_container.py new file mode 100644 index 000000000000..2f4e78d7c261 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/models/one_of_container.py @@ -0,0 +1,229 @@ +# 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, StrictInt, StrictStr, ValidationError, field_validator +from typing import Any, Dict, List, Optional +from typing_extensions import Annotated +from petstore_api.models.enum_string1 import EnumString1 +from petstore_api.models.nullable_class import NullableClass +from petstore_api.models.pig import Pig +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + + +ONEOFCONTAINER_ONE_OF_SCHEMAS = ["Dict[str, Pig]", "List[EnumString1]", "List[NullableClass]", "List[Pig]", "List[int]", "str"] + +class OneOfContainer(BaseModel): + """ + OneOfContainer + """ + # data type: str + oneof_schema_1_validator: Optional[StrictStr] = None + # data type: List[Pig] + oneof_schema_2_validator: Optional[Annotated[List[Pig], Field(min_length=1)]] = None + # data type: Dict[str, Pig] + oneof_schema_3_validator: Optional[Dict[str, Pig]] = None + # data type: List[int] + oneof_schema_4_validator: Optional[Annotated[List[StrictInt], Field(min_length=1)]] = None + # data type: List[EnumString1] + oneof_schema_5_validator: Optional[Annotated[List[EnumString1], Field(min_length=1)]] = None + # data type: List[NullableClass] + oneof_schema_6_validator: Optional[Annotated[List[NullableClass], Field(min_length=1)]] = None + actual_instance: Optional[Union[Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str]] = None + one_of_schemas: Set[str] = { "Dict[str, Pig]", "List[EnumString1]", "List[NullableClass]", "List[Pig]", "List[int]", "str" } + + 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 = OneOfContainer.model_construct() + error_messages = [] + match = 0 + # validate data type: str + try: + instance.oneof_schema_1_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[Pig] + try: + instance.oneof_schema_2_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: Dict[str, Pig] + try: + instance.oneof_schema_3_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[int] + try: + instance.oneof_schema_4_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[EnumString1] + try: + instance.oneof_schema_5_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[NullableClass] + try: + instance.oneof_schema_6_validator = v + 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 setting `actual_instance` in OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. 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 str + try: + # validation + instance.oneof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_1_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[Pig] + try: + data = json.loads(json_str) + data = ([(Pig.from_dict(_item0) if _item0 is not None else None) for _item0 in data] if isinstance(data, list) else data) + # validation + instance.oneof_schema_2_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_2_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into Dict[str, Pig] + try: + data = json.loads(json_str) + data = ({_key0: (Pig.from_dict(_item0) if _item0 is not None else None) for _key0, _item0 in data.items()} if isinstance(data, dict) else data) + # validation + instance.oneof_schema_3_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_3_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[int] + try: + data = json.loads(json_str) + # validation + instance.oneof_schema_4_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_4_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[EnumString1] + try: + data = json.loads(json_str) + # validation + instance.oneof_schema_5_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_5_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) as e: + error_messages.append(str(e)) + # deserialize data into List[NullableClass] + try: + data = json.loads(json_str) + # validation + instance.oneof_schema_6_validator = data + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_6_validator + match += 1 + except (ValidationError, ValueError, TypeError, AttributeError) 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 OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into OneOfContainer with oneOf schemas: Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str. 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(to_jsonable_python(self.to_dict())) + + def to_dict(self) -> Optional[Union[Dict[str, Any], Dict[str, Pig], List[EnumString1], List[NullableClass], List[Pig], List[int], str]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + return _to_dict(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/petstore_api/models/one_of_enum_string.py b/samples/openapi3/client/petstore/python/petstore_api/models/one_of_enum_string.py index f180178737db..da15aedf5355 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/one_of_enum_string.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/one_of_enum_string.py @@ -22,6 +22,17 @@ from pydantic import StrictStr, Field from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + ONEOFENUMSTRING_ONE_OF_SCHEMAS = ["EnumString1", "EnumString2"] @@ -117,18 +128,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], EnumString1, EnumString2]]: """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 + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/pig.py b/samples/openapi3/client/petstore/python/petstore_api/models/pig.py index 8f9306304c66..dd76a1b28da2 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/pig.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/pig.py @@ -22,6 +22,17 @@ from pydantic import StrictStr, Field from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + PIG_ONE_OF_SCHEMAS = ["BasquePig", "DanishPig"] @@ -136,18 +147,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], BasquePig, DanishPig]]: """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 + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/task_activity.py b/samples/openapi3/client/petstore/python/petstore_api/models/task_activity.py index cc1e1fc5a60f..9623b22041ea 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/task_activity.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/task_activity.py @@ -23,6 +23,17 @@ from pydantic import StrictStr, Field from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self +from pydantic_core import to_jsonable_python + +def _to_dict(value: Any) -> Any: + if isinstance(value, list): + return [_to_dict(item) for item in value] + if isinstance(value, dict): + return {key: _to_dict(item) for key, item in value.items()} + if hasattr(value, "to_dict") and callable(value.to_dict): + return value.to_dict() + return value + TASKACTIVITY_ONE_OF_SCHEMAS = ["Bathing", "Feeding", "PoopCleaning"] @@ -131,18 +142,14 @@ def to_json(self) -> str: 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) + return json.dumps(to_jsonable_python(self.to_dict())) def to_dict(self) -> Optional[Union[Dict[str, Any], Bathing, Feeding, PoopCleaning]]: """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 + return _to_dict(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python/test/test_any_of_container.py b/samples/openapi3/client/petstore/python/test/test_any_of_container.py new file mode 100644 index 000000000000..3246e1519768 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_any_of_container.py @@ -0,0 +1,50 @@ +# 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.any_of_container import AnyOfContainer + +class TestAnyOfContainer(unittest.TestCase): + """AnyOfContainer unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> AnyOfContainer: + """Test AnyOfContainer + 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 `AnyOfContainer` + """ + model = AnyOfContainer() + if include_optional: + return AnyOfContainer( + ) + else: + return AnyOfContainer( + ) + """ + + def testAnyOfContainer(self): + """Test AnyOfContainer""" + # 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_nested_union_container.py b/samples/openapi3/client/petstore/python/test/test_nested_union_container.py new file mode 100644 index 000000000000..44901af90110 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_nested_union_container.py @@ -0,0 +1,50 @@ +# 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.nested_union_container import NestedUnionContainer + +class TestNestedUnionContainer(unittest.TestCase): + """NestedUnionContainer unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> NestedUnionContainer: + """Test NestedUnionContainer + 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 `NestedUnionContainer` + """ + model = NestedUnionContainer() + if include_optional: + return NestedUnionContainer( + ) + else: + return NestedUnionContainer( + ) + """ + + def testNestedUnionContainer(self): + """Test NestedUnionContainer""" + # 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_one_of_container.py b/samples/openapi3/client/petstore/python/test/test_one_of_container.py new file mode 100644 index 000000000000..12ab6d654e43 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_one_of_container.py @@ -0,0 +1,50 @@ +# 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.one_of_container import OneOfContainer + +class TestOneOfContainer(unittest.TestCase): + """OneOfContainer unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> OneOfContainer: + """Test OneOfContainer + 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 `OneOfContainer` + """ + model = OneOfContainer() + if include_optional: + return OneOfContainer( + ) + else: + return OneOfContainer( + ) + """ + + def testOneOfContainer(self): + """Test OneOfContainer""" + # 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/tests/test_union_containers.py b/samples/openapi3/client/petstore/python/tests/test_union_containers.py new file mode 100644 index 000000000000..66ebe3e65742 --- /dev/null +++ b/samples/openapi3/client/petstore/python/tests/test_union_containers.py @@ -0,0 +1,72 @@ +import json +from typing import Any + +import pytest + +from petstore_api import ( + AnyOfContainer, + AnyOfPig, + ApiClient, + BasquePig, + NestedUnionContainer, + OneOfContainer, + Pig, +) + + +PIG = {"class'\"\\Name": "basque'\"\\pig\nkind", "color": "red"} + + +@pytest.mark.parametrize("model", [OneOfContainer, AnyOfContainer]) +@pytest.mark.parametrize("value", [[PIG], {"pig": PIG}, "plain string", [1, 2], ["a"]]) +def test_union_container_round_trip(model, value): + for instance in (model.from_dict(value), model.from_json(json.dumps(value))): + assert instance.to_dict() == value + assert json.loads(instance.to_json()) == value + assert ApiClient().sanitize_for_serialization(instance) == value + + +@pytest.mark.parametrize( + "model,part", [(OneOfContainer, Pig), (AnyOfContainer, AnyOfPig)] +) +def test_union_container_explicit_models(model, part): + item = part.from_dict(PIG) + instance = model([item]) + assert instance.actual_instance[0] is item + assert instance.to_dict() == [PIG] + assert json.loads(instance.to_json()) == [PIG] + + +def test_nested_union_container_round_trip(): + value: Any = [{"pigs": [PIG]}] + instance = NestedUnionContainer.from_dict(value) + assert isinstance(instance.actual_instance, list) + assert isinstance(instance.actual_instance[0]["pigs"][0], Pig) + assert instance.to_dict() == value + assert json.loads(instance.to_json()) == value + assert ApiClient().sanitize_for_serialization(instance) == value + + +def test_anyof_container_preserves_first_match(): + instance = AnyOfContainer.from_json(json.dumps([{**PIG, "size": 1}])) + assert isinstance(instance.actual_instance, list) + assert isinstance(instance.actual_instance[0], AnyOfPig) + assert isinstance(instance.actual_instance[0].actual_instance, BasquePig) + + +@pytest.mark.parametrize("model", [OneOfContainer, AnyOfContainer]) +@pytest.mark.parametrize( + "item", [{"required_integer_prop": 1}, {"required_integer_prop": 1, "string_prop": None}] +) +def test_union_container_ordinary_model_field_presence(model, item): + instance = model.from_dict([item]) + assert instance.actual_instance[0].model_fields_set == set(item) + assert instance.to_dict() == [item] + assert ApiClient().sanitize_for_serialization(instance) == [item] + + +@pytest.mark.parametrize("model", [OneOfContainer, AnyOfContainer]) +@pytest.mark.parametrize("value", [[], [None], {"pig": {}}, 42, True]) +def test_union_container_validation(model, value): + with pytest.raises(ValueError): + model.from_dict(value)