[python-nextgen] Better oneOf, anyOf support (#14743)

* better oneof, anyof support

* improve anyof support

* fix deprecation warning

* fix anyof, add tests

* add nullable support, add test
This commit is contained in:
William Cheng
2023-02-19 17:16:15 +08:00
committed by GitHub
parent 0891b6056f
commit 1bd3ce7ce2
34 changed files with 1185 additions and 46 deletions

View File

@@ -7,6 +7,7 @@ docs/AdditionalPropertiesClass.md
docs/AllOfWithSingleRef.md
docs/Animal.md
docs/AnotherFakeApi.md
docs/AnyOfColor.md
docs/AnyOfPig.md
docs/ApiResponse.md
docs/ArrayOfArrayOfNumberOnly.md
@@ -19,6 +20,7 @@ docs/CatAllOf.md
docs/Category.md
docs/ClassModel.md
docs/Client.md
docs/Color.md
docs/DanishPig.md
docs/DefaultApi.md
docs/DeprecatedObject.md
@@ -83,6 +85,7 @@ petstore_api/models/__init__.py
petstore_api/models/additional_properties_class.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_pig.py
petstore_api/models/api_response.py
petstore_api/models/array_of_array_of_number_only.py
@@ -95,6 +98,7 @@ petstore_api/models/cat_all_of.py
petstore_api/models/category.py
petstore_api/models/class_model.py
petstore_api/models/client.py
petstore_api/models/color.py
petstore_api/models/danish_pig.py
petstore_api/models/deprecated_object.py
petstore_api/models/dog.py

View File

@@ -130,6 +130,7 @@ Class | Method | HTTP request | Description
- [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md)
- [AllOfWithSingleRef](docs/AllOfWithSingleRef.md)
- [Animal](docs/Animal.md)
- [AnyOfColor](docs/AnyOfColor.md)
- [AnyOfPig](docs/AnyOfPig.md)
- [ApiResponse](docs/ApiResponse.md)
- [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md)
@@ -142,6 +143,7 @@ Class | Method | HTTP request | Description
- [Category](docs/Category.md)
- [ClassModel](docs/ClassModel.md)
- [Client](docs/Client.md)
- [Color](docs/Color.md)
- [DanishPig](docs/DanishPig.md)
- [DeprecatedObject](docs/DeprecatedObject.md)
- [Dog](docs/Dog.md)

View File

@@ -0,0 +1,28 @@
# AnyOfColor
Any of RGB array, RGBA array, or hex string.
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
## Example
```python
from petstore_api.models.any_of_color import AnyOfColor
# TODO update the JSON string below
json = "{}"
# create an instance of AnyOfColor from a JSON string
any_of_color_instance = AnyOfColor.from_json(json)
# print the JSON string representation of the object
print AnyOfColor.to_json()
# convert the object into a dict
any_of_color_dict = any_of_color_instance.to_dict()
# create an instance of AnyOfColor from a dict
any_of_color_form_dict = any_of_color.from_dict(any_of_color_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)

View File

@@ -0,0 +1,28 @@
# Color
RGB array, RGBA array, or hex string.
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
## Example
```python
from petstore_api.models.color import Color
# TODO update the JSON string below
json = "{}"
# create an instance of Color from a JSON string
color_instance = Color.from_json(json)
# print the JSON string representation of the object
print Color.to_json()
# convert the object into a dict
color_dict = color_instance.to_dict()
# create an instance of Color from a dict
color_form_dict = color.from_dict(color_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)

View File

@@ -38,6 +38,7 @@ from petstore_api.exceptions import ApiException
from petstore_api.models.additional_properties_class import AdditionalPropertiesClass
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_pig import AnyOfPig
from petstore_api.models.api_response import ApiResponse
from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly
@@ -50,6 +51,7 @@ from petstore_api.models.cat_all_of import CatAllOf
from petstore_api.models.category import Category
from petstore_api.models.class_model import ClassModel
from petstore_api.models.client import Client
from petstore_api.models.color import Color
from petstore_api.models.danish_pig import DanishPig
from petstore_api.models.deprecated_object import DeprecatedObject
from petstore_api.models.dog import Dog

View File

@@ -17,6 +17,7 @@ from __future__ import absolute_import
from petstore_api.models.additional_properties_class import AdditionalPropertiesClass
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_pig import AnyOfPig
from petstore_api.models.api_response import ApiResponse
from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly
@@ -29,6 +30,7 @@ from petstore_api.models.cat_all_of import CatAllOf
from petstore_api.models.category import Category
from petstore_api.models.class_model import ClassModel
from petstore_api.models.client import Client
from petstore_api.models.color import Color
from petstore_api.models.danish_pig import DanishPig
from petstore_api.models.deprecated_object import DeprecatedObject
from petstore_api.models.dog import Dog

View File

@@ -0,0 +1,128 @@
# 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: \" \\ # noqa: E501
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
"""
from __future__ import annotations
from inspect import getfullargspec
import json
import pprint
import re # noqa: F401
from typing import Optional
from pydantic import BaseModel, Field, StrictStr, ValidationError, conint, conlist, constr, validator
from typing import Any, List
from pydantic import StrictStr, Field
ANYOFCOLOR_ANY_OF_SCHEMAS = ["List[int]", "str"]
class AnyOfColor(BaseModel):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
# data type: List[int]
anyof_schema_1_validator: Optional[conlist(conint(strict=True, le=255, ge=0), max_items=3, min_items=3)] = Field(None, description="RGB three element array with values 0-255.")
# data type: List[int]
anyof_schema_2_validator: Optional[conlist(conint(strict=True, le=255, ge=0), max_items=4, min_items=4)] = Field(None, description="RGBA four element array with values 0-255.")
# data type: str
anyof_schema_3_validator: Optional[constr(strict=True, max_length=7, min_length=7)] = Field(None, description="Hex color string, such as #00FF00.")
actual_instance: Any
any_of_schemas: List[str] = Field(ANYOFCOLOR_ANY_OF_SCHEMAS, const=True)
class Config:
validate_assignment = True
@validator('actual_instance')
def actual_instance_must_validate_anyof(cls, v):
instance = cls()
error_messages = []
# validate data type: List[int]
try:
instance.anyof_schema_1_validator = v
return v
except ValidationError as e:
error_messages.append(str(e))
# validate data type: List[int]
try:
instance.anyof_schema_2_validator = v
return v
except ValidationError as e:
error_messages.append(str(e))
# validate data type: str
try:
instance.anyof_schema_3_validator = v
return v
except ValidationError as e:
error_messages.append(str(e))
if error_messages:
# no match
raise ValueError("No match found when deserializing the JSON string into AnyOfColor with anyOf schemas: List[int], str. Details: " + ", ".join(error_messages))
else:
return v
@classmethod
def from_json(cls, json_str: str) -> AnyOfColor:
"""Returns the object represented by the json string"""
instance = cls()
error_messages = []
# deserialize data into List[int]
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 as e:
error_messages.append(str(e))
# deserialize data into List[int]
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 as e:
error_messages.append(str(e))
# deserialize data into str
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 as e:
error_messages.append(str(e))
if error_messages:
# no match
raise ValueError("No match found when deserializing the JSON string into AnyOfColor with anyOf schemas: 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 not None:
return self.actual_instance.to_json()
else:
return "null"
def to_dict(self) -> dict:
"""Returns the dict representation of the actual instance"""
if self.actual_instance is not None:
return self.actual_instance.to_dict()
else:
return dict()
def to_str(self) -> str:
"""Returns the string representation of the actual instance"""
return pprint.pformat(self.dict())

View File

@@ -12,6 +12,7 @@
from __future__ import annotations
from inspect import getfullargspec
import json
import pprint
import re # noqa: F401
@@ -31,9 +32,9 @@ class AnyOfPig(BaseModel):
Do not edit the class manually.
"""
# data type: BasquePig
__anyof_schema_1: Optional[BasquePig] = None
anyof_schema_1_validator: Optional[BasquePig] = None
# data type: DanishPig
__anyof_schema_2: Optional[DanishPig] = None
anyof_schema_2_validator: Optional[DanishPig] = None
actual_instance: Any
any_of_schemas: List[str] = Field(ANYOFPIG_ANY_OF_SCHEMAS, const=True)
@@ -42,6 +43,7 @@ class AnyOfPig(BaseModel):
@validator('actual_instance')
def actual_instance_must_validate_anyof(cls, v):
instance = cls()
error_messages = []
# validate data type: BasquePig
if type(v) is not BasquePig:
@@ -66,13 +68,13 @@ class AnyOfPig(BaseModel):
"""Returns the object represented by the json string"""
instance = cls()
error_messages = []
# __anyof_schema_1: Optional[BasquePig] = None
# anyof_schema_1_validator: Optional[BasquePig] = None
try:
instance.actual_instance = BasquePig.from_json(json_str)
return instance
except ValidationError as e:
error_messages.append(str(e))
# __anyof_schema_2: Optional[DanishPig] = None
# anyof_schema_2_validator: Optional[DanishPig] = None
try:
instance.actual_instance = DanishPig.from_json(json_str)
return instance

View File

@@ -18,7 +18,7 @@ import json
from typing import List, Optional
from pydantic import BaseModel, StrictInt, StrictStr
from pydantic import BaseModel, StrictInt, StrictStr, conlist
from petstore_api.models.read_only_first import ReadOnlyFirst
class ArrayTest(BaseModel):
@@ -27,7 +27,7 @@ class ArrayTest(BaseModel):
Do not edit the class manually.
"""
array_of_string: Optional[List[StrictStr]] = None
array_of_string: Optional[conlist(StrictStr, max_items=3, min_items=0)] = None
array_array_of_integer: Optional[List[List[StrictInt]]] = None
array_array_of_model: Optional[List[List[ReadOnlyFirst]]] = None
__properties = ["array_of_string", "array_array_of_integer", "array_array_of_model"]

View File

@@ -0,0 +1,147 @@
# 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: \" \\ # noqa: E501
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
"""
from __future__ import annotations
from inspect import getfullargspec
import json
import pprint
import re # noqa: F401
from typing import Any, List, Optional
from pydantic import BaseModel, Field, StrictStr, ValidationError, conint, conlist, constr, validator
from typing import Any, List
from pydantic import StrictStr, Field
COLOR_ONE_OF_SCHEMAS = ["List[int]", "str"]
class Color(BaseModel):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
# data type: List[int]
oneof_schema_1_validator: Optional[conlist(conint(strict=True, le=255, ge=0), max_items=3, min_items=3)] = Field(None, description="RGB three element array with values 0-255.")
# data type: List[int]
oneof_schema_2_validator: Optional[conlist(conint(strict=True, le=255, ge=0), max_items=4, min_items=4)] = Field(None, description="RGBA four element array with values 0-255.")
# data type: str
oneof_schema_3_validator: Optional[constr(strict=True, max_length=7, min_length=7)] = Field(None, description="Hex color string, such as #00FF00.")
actual_instance: Any
one_of_schemas: List[str] = Field(COLOR_ONE_OF_SCHEMAS, const=True)
class Config:
validate_assignment = True
@validator('actual_instance')
def actual_instance_must_validate_oneof(cls, v):
if v is None:
return v
instance = cls()
error_messages = []
match = 0
# validate data type: List[int]
try:
instance.oneof_schema_1_validator = v
match += 1
except ValidationError as e:
error_messages.append(str(e))
# validate data type: List[int]
try:
instance.oneof_schema_2_validator = v
match += 1
except ValidationError as e:
error_messages.append(str(e))
# validate data type: str
try:
instance.oneof_schema_3_validator = v
match += 1
except ValidationError 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 Color with oneOf schemas: List[int], str. Details: " + ", ".join(error_messages))
elif match == 0:
# no match
raise ValueError("No match found when deserializing the JSON string into Color with oneOf schemas: List[int], str. Details: " + ", ".join(error_messages))
else:
return v
@classmethod
def from_dict(cls, obj: dict) -> Color:
return cls.from_json(json.dumps(obj))
@classmethod
def from_json(cls, json_str: str) -> Color:
"""Returns the object represented by the json string"""
instance = cls()
if json_str is None:
return instance
error_messages = []
match = 0
# deserialize data into List[int]
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 as e:
error_messages.append(str(e))
# deserialize data into List[int]
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 as e:
error_messages.append(str(e))
# deserialize data into str
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 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 Color with oneOf schemas: List[int], str. Details: " + ", ".join(error_messages))
elif match == 0:
# no match
raise ValueError("No match found when deserializing the JSON string into Color with oneOf schemas: 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 not None:
return self.actual_instance.to_json()
else:
return "null"
def to_dict(self) -> dict:
"""Returns the dict representation of the actual instance"""
if self.actual_instance is not None:
return self.actual_instance.to_dict()
else:
return dict()
def to_str(self) -> str:
"""Returns the string representation of the actual instance"""
return pprint.pformat(self.dict())

View File

@@ -12,8 +12,8 @@
from __future__ import annotations
from inspect import getfullargspec
import pprint
import json
import pprint
import re # noqa: F401
from typing import Any, List, Optional
@@ -32,9 +32,9 @@ class Pig(BaseModel):
Do not edit the class manually.
"""
# data type: BasquePig
__oneof_schema_1: Optional[BasquePig] = None
oneof_schema_1_validator: Optional[BasquePig] = None
# data type: DanishPig
__oneof_schema_2: Optional[DanishPig] = None
oneof_schema_2_validator: Optional[DanishPig] = None
actual_instance: Any
one_of_schemas: List[str] = Field(PIG_ONE_OF_SCHEMAS, const=True)
@@ -46,6 +46,7 @@ class Pig(BaseModel):
@validator('actual_instance')
def actual_instance_must_validate_oneof(cls, v):
instance = cls()
error_messages = []
match = 0
# validate data type: BasquePig
@@ -120,7 +121,3 @@ class Pig(BaseModel):
"""Returns the string representation of the actual instance"""
return pprint.pformat(self.dict())

View File

@@ -0,0 +1,53 @@
# coding: utf-8
"""
OpenAPI Petstore
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import datetime
import petstore_api
from petstore_api.models.any_of_color import AnyOfColor # noqa: E501
from petstore_api.rest import ApiException
class TestAnyOfColor(unittest.TestCase):
"""AnyOfColor unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional):
"""Test AnyOfColor
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 `AnyOfColor`
"""
model = petstore_api.models.any_of_color.AnyOfColor() # noqa: E501
if include_optional :
return AnyOfColor(
)
else :
return AnyOfColor(
)
"""
def testAnyOfColor(self):
"""Test AnyOfColor"""
# inst_req_only = self.make_instance(include_optional=False)
# inst_req_and_optional = self.make_instance(include_optional=True)
if __name__ == '__main__':
unittest.main()

View File

@@ -0,0 +1,53 @@
# coding: utf-8
"""
OpenAPI Petstore
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import datetime
import petstore_api
from petstore_api.models.color import Color # noqa: E501
from petstore_api.rest import ApiException
class TestColor(unittest.TestCase):
"""Color unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional):
"""Test Color
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 `Color`
"""
model = petstore_api.models.color.Color() # noqa: E501
if include_optional :
return Color(
)
else :
return Color(
)
"""
def testColor(self):
"""Test Color"""
# inst_req_only = self.make_instance(include_optional=False)
# inst_req_and_optional = self.make_instance(include_optional=True)
if __name__ == '__main__':
unittest.main()