[python-nextgen] support constructor with position argument in oneOf/anyOf model (#15434)

* support position constructor

* update samples

* update test
This commit is contained in:
William Cheng 2023-05-08 10:00:57 +08:00 committed by GitHub
parent 72cb03b865
commit b4eb7071e4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
29 changed files with 662 additions and 60 deletions

View File

@ -37,6 +37,16 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
}
{{/discriminator}}
def __init__(self, *args, **kwargs):
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):
{{#isNullable}}
@ -44,7 +54,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
return v
{{/isNullable}}
instance = cls()
instance = {{{classname}}}.construct()
error_messages = []
{{#composedSchemas.anyOf}}
# validate data type: {{{dataType}}}
@ -74,7 +84,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
{{/composedSchemas.anyOf}}
if error_messages:
# no match
raise ValueError("No match found when deserializing the JSON string into {{{classname}}} with anyOf schemas: {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}. Details: " + ", ".join(error_messages))
raise ValueError("No match found when setting the actual_instance in {{{classname}}} with anyOf schemas: {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}. Details: " + ", ".join(error_messages))
else:
return v
@ -85,7 +95,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
@classmethod
def from_json(cls, json_str: str) -> {{{classname}}}:
"""Returns the object represented by the json string"""
instance = cls()
instance = {{{classname}}}.construct()
{{#isNullable}}
if json_str is None:
return instance

View File

@ -36,6 +36,16 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
}
{{/discriminator}}
def __init__(self, *args, **kwargs):
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):
{{#isNullable}}
@ -43,7 +53,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
return v
{{/isNullable}}
instance = cls()
instance = {{{classname}}}.construct()
error_messages = []
match = 0
{{#composedSchemas.oneOf}}
@ -68,16 +78,15 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
error_messages.append(f"Error! Input type `{type(v)}` is not `{{{dataType}}}`")
else:
match += 1
{{/isPrimitiveType}}
{{/isContainer}}
{{/composedSchemas.oneOf}}
if match > 1:
# more than 1 match
raise ValueError("Multiple matches found when deserializing the JSON string into {{{classname}}} with oneOf schemas: {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}. Details: " + ", ".join(error_messages))
raise ValueError("Multiple matches found when setting `actual_instance` in {{{classname}}} with oneOf schemas: {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}. Details: " + ", ".join(error_messages))
elif match == 0:
# no match
raise ValueError("No match found when deserializing the JSON string into {{{classname}}} with oneOf schemas: {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}. Details: " + ", ".join(error_messages))
raise ValueError("No match found when setting `actual_instance` in {{{classname}}} with oneOf schemas: {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}. Details: " + ", ".join(error_messages))
else:
return v
@ -88,7 +97,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
@classmethod
def from_json(cls, json_str: str) -> {{{classname}}}:
"""Returns the object represented by the json string"""
instance = cls()
instance = {{{classname}}}.construct()
{{#isNullable}}
if json_str is None:
return instance

View File

@ -2194,3 +2194,8 @@ components:
properties:
optionalDict:
$ref: "#/components/schemas/DictWithAdditionalProperties"
IntOrString:
oneOf:
- type: integer
minimum: 10
- type: string

View File

@ -44,6 +44,7 @@ docs/FormatTest.md
docs/HasOnlyReadOnly.md
docs/HealthCheckResult.md
docs/InnerDictWithProperty.md
docs/IntOrString.md
docs/List.md
docs/MapTest.md
docs/MixedPropertiesAndAdditionalPropertiesClass.md
@ -130,6 +131,7 @@ petstore_api/models/format_test.py
petstore_api/models/has_only_read_only.py
petstore_api/models/health_check_result.py
petstore_api/models/inner_dict_with_property.py
petstore_api/models/int_or_string.py
petstore_api/models/list.py
petstore_api/models/map_test.py
petstore_api/models/mixed_properties_and_additional_properties_class.py

View File

@ -169,6 +169,7 @@ Class | Method | HTTP request | Description
- [HasOnlyReadOnly](docs/HasOnlyReadOnly.md)
- [HealthCheckResult](docs/HealthCheckResult.md)
- [InnerDictWithProperty](docs/InnerDictWithProperty.md)
- [IntOrString](docs/IntOrString.md)
- [List](docs/List.md)
- [MapTest](docs/MapTest.md)
- [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md)

View File

@ -0,0 +1,27 @@
# IntOrString
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
## Example
```python
from petstore_api.models.int_or_string import IntOrString
# TODO update the JSON string below
json = "{}"
# create an instance of IntOrString from a JSON string
int_or_string_instance = IntOrString.from_json(json)
# print the JSON string representation of the object
print IntOrString.to_json()
# convert the object into a dict
int_or_string_dict = int_or_string_instance.to_dict()
# create an instance of IntOrString from a dict
int_or_string_form_dict = int_or_string.from_dict(int_or_string_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

@ -75,6 +75,7 @@ from petstore_api.models.format_test import FormatTest
from petstore_api.models.has_only_read_only import HasOnlyReadOnly
from petstore_api.models.health_check_result import HealthCheckResult
from petstore_api.models.inner_dict_with_property import InnerDictWithProperty
from petstore_api.models.int_or_string import IntOrString
from petstore_api.models.list import List
from petstore_api.models.map_test import MapTest
from petstore_api.models.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass

View File

@ -51,6 +51,7 @@ from petstore_api.models.format_test import FormatTest
from petstore_api.models.has_only_read_only import HasOnlyReadOnly
from petstore_api.models.health_check_result import HealthCheckResult
from petstore_api.models.inner_dict_with_property import InnerDictWithProperty
from petstore_api.models.int_or_string import IntOrString
from petstore_api.models.list import List
from petstore_api.models.map_test import MapTest
from petstore_api.models.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass

View File

@ -42,9 +42,19 @@ class AnyOfColor(BaseModel):
class Config:
validate_assignment = True
def __init__(self, *args, **kwargs):
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 = cls()
instance = AnyOfColor.construct()
error_messages = []
# validate data type: List[int]
try:
@ -66,7 +76,7 @@ class AnyOfColor(BaseModel):
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))
raise ValueError("No match found when setting the actual_instance in AnyOfColor with anyOf schemas: List[int], str. Details: " + ", ".join(error_messages))
else:
return v
@ -77,7 +87,7 @@ class AnyOfColor(BaseModel):
@classmethod
def from_json(cls, json_str: str) -> AnyOfColor:
"""Returns the object represented by the json string"""
instance = cls()
instance = AnyOfColor.construct()
error_messages = []
# deserialize data into List[int]
try:

View File

@ -42,9 +42,19 @@ class AnyOfPig(BaseModel):
class Config:
validate_assignment = True
def __init__(self, *args, **kwargs):
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 = cls()
instance = AnyOfPig.construct()
error_messages = []
# validate data type: BasquePig
if not isinstance(v, BasquePig):
@ -60,7 +70,7 @@ class AnyOfPig(BaseModel):
if error_messages:
# no match
raise ValueError("No match found when deserializing the JSON string into AnyOfPig with anyOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages))
raise ValueError("No match found when setting the actual_instance in AnyOfPig with anyOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages))
else:
return v
@ -71,7 +81,7 @@ class AnyOfPig(BaseModel):
@classmethod
def from_json(cls, json_str: str) -> AnyOfPig:
"""Returns the object represented by the json string"""
instance = cls()
instance = AnyOfPig.construct()
error_messages = []
# anyof_schema_1_validator: Optional[BasquePig] = None
try:

View File

@ -41,12 +41,22 @@ class Color(BaseModel):
class Config:
validate_assignment = True
def __init__(self, *args, **kwargs):
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):
if v is None:
return v
instance = cls()
instance = Color.construct()
error_messages = []
match = 0
# validate data type: List[int]
@ -69,10 +79,10 @@ class Color(BaseModel):
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))
raise ValueError("Multiple matches found when setting `actual_instance` in 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))
raise ValueError("No match found when setting `actual_instance` in Color with oneOf schemas: List[int], str. Details: " + ", ".join(error_messages))
else:
return v
@ -83,7 +93,7 @@ class Color(BaseModel):
@classmethod
def from_json(cls, json_str: str) -> Color:
"""Returns the object represented by the json string"""
instance = cls()
instance = Color.construct()
if json_str is None:
return instance

View File

@ -0,0 +1,143 @@
# 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 OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
"""
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, validator
from typing import Any, List
from pydantic import StrictStr, Field
INTORSTRING_ONE_OF_SCHEMAS = ["int", "str"]
class IntOrString(BaseModel):
"""
IntOrString
"""
# data type: int
oneof_schema_1_validator: Optional[conint(strict=True, ge=10)] = None
# data type: str
oneof_schema_2_validator: Optional[StrictStr] = None
actual_instance: Any
one_of_schemas: List[str] = Field(INTORSTRING_ONE_OF_SCHEMAS, const=True)
class Config:
validate_assignment = True
def __init__(self, *args, **kwargs):
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 = IntOrString.construct()
error_messages = []
match = 0
# validate data type: int
try:
instance.oneof_schema_1_validator = v
match += 1
except (ValidationError, ValueError) as e:
error_messages.append(str(e))
# validate data type: str
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 IntOrString with oneOf schemas: int, str. Details: " + ", ".join(error_messages))
elif match == 0:
# no match
raise ValueError("No match found when setting `actual_instance` in IntOrString with oneOf schemas: int, str. Details: " + ", ".join(error_messages))
else:
return v
@classmethod
def from_dict(cls, obj: dict) -> IntOrString:
return cls.from_json(json.dumps(obj))
@classmethod
def from_json(cls, json_str: str) -> IntOrString:
"""Returns the object represented by the json string"""
instance = IntOrString.construct()
error_messages = []
match = 0
# deserialize data into 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, ValueError) as e:
error_messages.append(str(e))
# deserialize data into str
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 IntOrString with oneOf schemas: int, str. Details: " + ", ".join(error_messages))
elif match == 0:
# no match
raise ValueError("No match found when deserializing the JSON string into IntOrString with oneOf schemas: 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())

View File

@ -41,9 +41,19 @@ class OneOfEnumString(BaseModel):
class Config:
validate_assignment = True
def __init__(self, *args, **kwargs):
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 = cls()
instance = OneOfEnumString.construct()
error_messages = []
match = 0
# validate data type: EnumString1
@ -51,19 +61,17 @@ class OneOfEnumString(BaseModel):
error_messages.append(f"Error! Input type `{type(v)}` is not `EnumString1`")
else:
match += 1
# validate data type: EnumString2
if not isinstance(v, EnumString2):
error_messages.append(f"Error! Input type `{type(v)}` is not `EnumString2`")
else:
match += 1
if match > 1:
# more than 1 match
raise ValueError("Multiple matches found when deserializing the JSON string into OneOfEnumString with oneOf schemas: EnumString1, EnumString2. Details: " + ", ".join(error_messages))
raise ValueError("Multiple matches found when setting `actual_instance` in OneOfEnumString with oneOf schemas: EnumString1, EnumString2. Details: " + ", ".join(error_messages))
elif match == 0:
# no match
raise ValueError("No match found when deserializing the JSON string into OneOfEnumString with oneOf schemas: EnumString1, EnumString2. Details: " + ", ".join(error_messages))
raise ValueError("No match found when setting `actual_instance` in OneOfEnumString with oneOf schemas: EnumString1, EnumString2. Details: " + ", ".join(error_messages))
else:
return v
@ -74,7 +82,7 @@ class OneOfEnumString(BaseModel):
@classmethod
def from_json(cls, json_str: str) -> OneOfEnumString:
"""Returns the object represented by the json string"""
instance = cls()
instance = OneOfEnumString.construct()
error_messages = []
match = 0

View File

@ -44,9 +44,19 @@ class Pig(BaseModel):
discriminator_value_class_map = {
}
def __init__(self, *args, **kwargs):
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 = cls()
instance = Pig.construct()
error_messages = []
match = 0
# validate data type: BasquePig
@ -54,19 +64,17 @@ class Pig(BaseModel):
error_messages.append(f"Error! Input type `{type(v)}` is not `BasquePig`")
else:
match += 1
# validate data type: DanishPig
if not isinstance(v, DanishPig):
error_messages.append(f"Error! Input type `{type(v)}` is not `DanishPig`")
else:
match += 1
if match > 1:
# more than 1 match
raise ValueError("Multiple matches found when deserializing the JSON string into Pig with oneOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages))
raise ValueError("Multiple matches found when setting `actual_instance` in Pig with oneOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages))
elif match == 0:
# no match
raise ValueError("No match found when deserializing the JSON string into Pig with oneOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages))
raise ValueError("No match found when setting `actual_instance` in Pig with oneOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages))
else:
return v
@ -77,7 +85,7 @@ class Pig(BaseModel):
@classmethod
def from_json(cls, json_str: str) -> Pig:
"""Returns the object represented by the json string"""
instance = cls()
instance = Pig.construct()
error_messages = []
match = 0

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 OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
"""
import unittest
import datetime
import petstore_api
from petstore_api.models.int_or_string import IntOrString # noqa: E501
from petstore_api.rest import ApiException
class TestIntOrString(unittest.TestCase):
"""IntOrString unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional):
"""Test IntOrString
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 `IntOrString`
"""
model = petstore_api.models.int_or_string.IntOrString() # noqa: E501
if include_optional :
return IntOrString(
)
else :
return IntOrString(
)
"""
def testIntOrString(self):
"""Test IntOrString"""
# 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

@ -91,8 +91,7 @@ class ModelTests(unittest.TestCase):
self.assertTrue(False) # this line shouldn't execute
except ValueError as e:
self.assertTrue(
"No match found when deserializing the JSON string into Pig with oneOf schemas: "
"BasquePig, DanishPig" in str(e))
"No match found when setting `actual_instance` in Pig with oneOf schemas: BasquePig, DanishPig" in str(e))
# failure
try:
@ -141,7 +140,7 @@ class ModelTests(unittest.TestCase):
self.assertTrue(False) # this line shouldn't execute
except ValueError as e:
self.assertTrue(
"No match found when deserializing the JSON string into AnyOfPig with anyOf schemas: BasquePig, "
"No match found when setting the actual_instance in AnyOfPig with anyOf schemas: BasquePig, "
"DanishPig" in str(e))
# failure

View File

@ -44,6 +44,7 @@ docs/FormatTest.md
docs/HasOnlyReadOnly.md
docs/HealthCheckResult.md
docs/InnerDictWithProperty.md
docs/IntOrString.md
docs/List.md
docs/MapTest.md
docs/MixedPropertiesAndAdditionalPropertiesClass.md
@ -130,6 +131,7 @@ petstore_api/models/format_test.py
petstore_api/models/has_only_read_only.py
petstore_api/models/health_check_result.py
petstore_api/models/inner_dict_with_property.py
petstore_api/models/int_or_string.py
petstore_api/models/list.py
petstore_api/models/map_test.py
petstore_api/models/mixed_properties_and_additional_properties_class.py

View File

@ -169,6 +169,7 @@ Class | Method | HTTP request | Description
- [HasOnlyReadOnly](docs/HasOnlyReadOnly.md)
- [HealthCheckResult](docs/HealthCheckResult.md)
- [InnerDictWithProperty](docs/InnerDictWithProperty.md)
- [IntOrString](docs/IntOrString.md)
- [List](docs/List.md)
- [MapTest](docs/MapTest.md)
- [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md)

View File

@ -0,0 +1,27 @@
# IntOrString
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
## Example
```python
from petstore_api.models.int_or_string import IntOrString
# TODO update the JSON string below
json = "{}"
# create an instance of IntOrString from a JSON string
int_or_string_instance = IntOrString.from_json(json)
# print the JSON string representation of the object
print IntOrString.to_json()
# convert the object into a dict
int_or_string_dict = int_or_string_instance.to_dict()
# create an instance of IntOrString from a dict
int_or_string_form_dict = int_or_string.from_dict(int_or_string_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

@ -75,6 +75,7 @@ from petstore_api.models.format_test import FormatTest
from petstore_api.models.has_only_read_only import HasOnlyReadOnly
from petstore_api.models.health_check_result import HealthCheckResult
from petstore_api.models.inner_dict_with_property import InnerDictWithProperty
from petstore_api.models.int_or_string import IntOrString
from petstore_api.models.list import List
from petstore_api.models.map_test import MapTest
from petstore_api.models.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass

View File

@ -51,6 +51,7 @@ from petstore_api.models.format_test import FormatTest
from petstore_api.models.has_only_read_only import HasOnlyReadOnly
from petstore_api.models.health_check_result import HealthCheckResult
from petstore_api.models.inner_dict_with_property import InnerDictWithProperty
from petstore_api.models.int_or_string import IntOrString
from petstore_api.models.list import List
from petstore_api.models.map_test import MapTest
from petstore_api.models.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass

View File

@ -42,9 +42,19 @@ class AnyOfColor(BaseModel):
class Config:
validate_assignment = True
def __init__(self, *args, **kwargs):
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 = cls()
instance = AnyOfColor.construct()
error_messages = []
# validate data type: List[int]
try:
@ -66,7 +76,7 @@ class AnyOfColor(BaseModel):
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))
raise ValueError("No match found when setting the actual_instance in AnyOfColor with anyOf schemas: List[int], str. Details: " + ", ".join(error_messages))
else:
return v
@ -77,7 +87,7 @@ class AnyOfColor(BaseModel):
@classmethod
def from_json(cls, json_str: str) -> AnyOfColor:
"""Returns the object represented by the json string"""
instance = cls()
instance = AnyOfColor.construct()
error_messages = []
# deserialize data into List[int]
try:

View File

@ -42,9 +42,19 @@ class AnyOfPig(BaseModel):
class Config:
validate_assignment = True
def __init__(self, *args, **kwargs):
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 = cls()
instance = AnyOfPig.construct()
error_messages = []
# validate data type: BasquePig
if not isinstance(v, BasquePig):
@ -60,7 +70,7 @@ class AnyOfPig(BaseModel):
if error_messages:
# no match
raise ValueError("No match found when deserializing the JSON string into AnyOfPig with anyOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages))
raise ValueError("No match found when setting the actual_instance in AnyOfPig with anyOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages))
else:
return v
@ -71,7 +81,7 @@ class AnyOfPig(BaseModel):
@classmethod
def from_json(cls, json_str: str) -> AnyOfPig:
"""Returns the object represented by the json string"""
instance = cls()
instance = AnyOfPig.construct()
error_messages = []
# anyof_schema_1_validator: Optional[BasquePig] = None
try:

View File

@ -41,12 +41,22 @@ class Color(BaseModel):
class Config:
validate_assignment = True
def __init__(self, *args, **kwargs):
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):
if v is None:
return v
instance = cls()
instance = Color.construct()
error_messages = []
match = 0
# validate data type: List[int]
@ -69,10 +79,10 @@ class Color(BaseModel):
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))
raise ValueError("Multiple matches found when setting `actual_instance` in 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))
raise ValueError("No match found when setting `actual_instance` in Color with oneOf schemas: List[int], str. Details: " + ", ".join(error_messages))
else:
return v
@ -83,7 +93,7 @@ class Color(BaseModel):
@classmethod
def from_json(cls, json_str: str) -> Color:
"""Returns the object represented by the json string"""
instance = cls()
instance = Color.construct()
if json_str is None:
return instance

View File

@ -0,0 +1,143 @@
# 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 OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
"""
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, validator
from typing import Any, List
from pydantic import StrictStr, Field
INTORSTRING_ONE_OF_SCHEMAS = ["int", "str"]
class IntOrString(BaseModel):
"""
IntOrString
"""
# data type: int
oneof_schema_1_validator: Optional[conint(strict=True, ge=10)] = None
# data type: str
oneof_schema_2_validator: Optional[StrictStr] = None
actual_instance: Any
one_of_schemas: List[str] = Field(INTORSTRING_ONE_OF_SCHEMAS, const=True)
class Config:
validate_assignment = True
def __init__(self, *args, **kwargs):
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 = IntOrString.construct()
error_messages = []
match = 0
# validate data type: int
try:
instance.oneof_schema_1_validator = v
match += 1
except (ValidationError, ValueError) as e:
error_messages.append(str(e))
# validate data type: str
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 IntOrString with oneOf schemas: int, str. Details: " + ", ".join(error_messages))
elif match == 0:
# no match
raise ValueError("No match found when setting `actual_instance` in IntOrString with oneOf schemas: int, str. Details: " + ", ".join(error_messages))
else:
return v
@classmethod
def from_dict(cls, obj: dict) -> IntOrString:
return cls.from_json(json.dumps(obj))
@classmethod
def from_json(cls, json_str: str) -> IntOrString:
"""Returns the object represented by the json string"""
instance = IntOrString.construct()
error_messages = []
match = 0
# deserialize data into 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, ValueError) as e:
error_messages.append(str(e))
# deserialize data into str
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 IntOrString with oneOf schemas: int, str. Details: " + ", ".join(error_messages))
elif match == 0:
# no match
raise ValueError("No match found when deserializing the JSON string into IntOrString with oneOf schemas: 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())

View File

@ -41,9 +41,19 @@ class OneOfEnumString(BaseModel):
class Config:
validate_assignment = True
def __init__(self, *args, **kwargs):
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 = cls()
instance = OneOfEnumString.construct()
error_messages = []
match = 0
# validate data type: EnumString1
@ -51,19 +61,17 @@ class OneOfEnumString(BaseModel):
error_messages.append(f"Error! Input type `{type(v)}` is not `EnumString1`")
else:
match += 1
# validate data type: EnumString2
if not isinstance(v, EnumString2):
error_messages.append(f"Error! Input type `{type(v)}` is not `EnumString2`")
else:
match += 1
if match > 1:
# more than 1 match
raise ValueError("Multiple matches found when deserializing the JSON string into OneOfEnumString with oneOf schemas: EnumString1, EnumString2. Details: " + ", ".join(error_messages))
raise ValueError("Multiple matches found when setting `actual_instance` in OneOfEnumString with oneOf schemas: EnumString1, EnumString2. Details: " + ", ".join(error_messages))
elif match == 0:
# no match
raise ValueError("No match found when deserializing the JSON string into OneOfEnumString with oneOf schemas: EnumString1, EnumString2. Details: " + ", ".join(error_messages))
raise ValueError("No match found when setting `actual_instance` in OneOfEnumString with oneOf schemas: EnumString1, EnumString2. Details: " + ", ".join(error_messages))
else:
return v
@ -74,7 +82,7 @@ class OneOfEnumString(BaseModel):
@classmethod
def from_json(cls, json_str: str) -> OneOfEnumString:
"""Returns the object represented by the json string"""
instance = cls()
instance = OneOfEnumString.construct()
error_messages = []
match = 0

View File

@ -44,9 +44,19 @@ class Pig(BaseModel):
discriminator_value_class_map = {
}
def __init__(self, *args, **kwargs):
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 = cls()
instance = Pig.construct()
error_messages = []
match = 0
# validate data type: BasquePig
@ -54,19 +64,17 @@ class Pig(BaseModel):
error_messages.append(f"Error! Input type `{type(v)}` is not `BasquePig`")
else:
match += 1
# validate data type: DanishPig
if not isinstance(v, DanishPig):
error_messages.append(f"Error! Input type `{type(v)}` is not `DanishPig`")
else:
match += 1
if match > 1:
# more than 1 match
raise ValueError("Multiple matches found when deserializing the JSON string into Pig with oneOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages))
raise ValueError("Multiple matches found when setting `actual_instance` in Pig with oneOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages))
elif match == 0:
# no match
raise ValueError("No match found when deserializing the JSON string into Pig with oneOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages))
raise ValueError("No match found when setting `actual_instance` in Pig with oneOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages))
else:
return v
@ -77,7 +85,7 @@ class Pig(BaseModel):
@classmethod
def from_json(cls, json_str: str) -> Pig:
"""Returns the object represented by the json string"""
instance = cls()
instance = Pig.construct()
error_messages = []
match = 0

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 OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
"""
import unittest
import datetime
import petstore_api
from petstore_api.models.int_or_string import IntOrString # noqa: E501
from petstore_api.rest import ApiException
class TestIntOrString(unittest.TestCase):
"""IntOrString unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional):
"""Test IntOrString
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 `IntOrString`
"""
model = petstore_api.models.int_or_string.IntOrString() # noqa: E501
if include_optional :
return IntOrString(
)
else :
return IntOrString(
)
"""
def testIntOrString(self):
"""Test IntOrString"""
# 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

@ -142,6 +142,15 @@ class ModelTests(unittest.TestCase):
except ValueError as e:
self.assertTrue("'e' is not a valid EnumString1, 'e' is not a valid EnumString" in str(e))
# test the constructor
enum_string1 = petstore_api.EnumString1('a')
constructor1 = petstore_api.OneOfEnumString(actual_instance=enum_string1)
self.assertEqual(constructor1.actual_instance, enum_string1)
constructor2 = petstore_api.OneOfEnumString(enum_string1)
self.assertEqual(constructor2.actual_instance, enum_string1)
constructor3 = petstore_api.OneOfEnumString()
self.assertEqual(constructor3.actual_instance, None)
def test_anyOf_array_of_integers(self):
# test new Color
new_color = petstore_api.AnyOfColor()
@ -180,9 +189,22 @@ class ModelTests(unittest.TestCase):
def test_oneOf(self):
# test new Pig
bp = petstore_api.BasquePig.from_dict({"className": "BasquePig", "color": "red"})
new_pig = petstore_api.Pig()
self.assertEqual("null", new_pig.to_json())
self.assertEqual(None, new_pig.actual_instance)
new_pig2 = petstore_api.Pig(actual_instance=bp)
self.assertEqual('{"className": "BasquePig", "color": "red"}', new_pig2.to_json())
new_pig3 = petstore_api.Pig(bp)
self.assertEqual('{"className": "BasquePig", "color": "red"}', new_pig3.to_json())
try:
new_pig4 = petstore_api.Pig(bp, actual_instance=bp)
except ValueError as e:
self.assertTrue("If position argument is used, keyword argument cannot be used.", str(e))
try:
new_pig5 = petstore_api.Pig(bp, bp)
except ValueError as e:
self.assertTrue("If position argument is used, only 1 is allowed to set `actual_instance`", str(e))
# test from_json
json_str = '{"className": "BasquePig", "color": "red"}'
@ -204,9 +226,7 @@ class ModelTests(unittest.TestCase):
pig3 = petstore_api.Pig(actual_instance="123")
self.assertTrue(False) # this line shouldn't execute
except ValueError as e:
self.assertTrue(
"No match found when deserializing the JSON string into Pig with oneOf schemas: "
"BasquePig, DanishPig" in str(e))
self.assertTrue("No match found when setting `actual_instance` in Pig with oneOf schemas: BasquePig, DanishPig" in str(e))
# failure
try:
@ -254,7 +274,7 @@ class ModelTests(unittest.TestCase):
# test init
basque_pig = p.actual_instance
pig2 = petstore_api.Pig(actual_instance=basque_pig)
pig2 = petstore_api.AnyOfPig(actual_instance=basque_pig)
self.assertIsInstance(pig2.actual_instance, petstore_api.BasquePig)
# test failed init
@ -263,7 +283,7 @@ class ModelTests(unittest.TestCase):
self.assertTrue(False) # this line shouldn't execute
except ValueError as e:
self.assertTrue(
"No match found when deserializing the JSON string into AnyOfPig with anyOf schemas: BasquePig, "
"No match found when setting the actual_instance in AnyOfPig with anyOf schemas: BasquePig, "
"DanishPig" in str(e))
# failure
@ -447,3 +467,14 @@ class ModelTests(unittest.TestCase):
self.assertEqual(a.value, "-efg")
self.assertEqual(a.name, "MINUS_EFG")
self.assertEqual(a, "-efg")
def test_int_or_string_oneof(self):
a = petstore_api.IntOrString("-efg")
self.assertEqual(a.actual_instance, "-efg")
a = petstore_api.IntOrString(100)
self.assertEqual(a.actual_instance, 100)
try:
a = petstore_api.IntOrString(1)
except ValueError as e:
self.assertTrue("ensure this value is greater than or equal to 10" in str(e))