mirror of
https://github.com/OpenAPITools/openapi-generator.git
synced 2025-12-18 20:57:06 +00:00
fix(python,asyncio): multipart form data serialization (#19302)
* fix: object serialization for multipart requests
This PR is essentially
<https://github.com/OpenAPITools/openapi-generator/pull/18140> but for
the asyncio client.
* fix: int serialization for multipart requests
urllib3 handles serializing ints in post params (ref 1), while asyncio
explicitly does not (ref 2).
ref 1: <9316764e90/src/urllib3/filepost.py (L75-L76)>
ref 2: <https://github.com/aio-libs/aiohttp/issues/920>
* test: new fake multipart endpoint with files and body
* test: regression test for stringified body params
* fix: mypy tweak
* fix: FILES regeneration
* feat: object, int serialization for multipart reqs
Extends previous commits (and #18140) to cover the python-pydantic-v1
client as well.
* fix: use async with in test
* test: regression test for pydantic-v1-aiohttp
* test: add regression test to pydantic-v1
Also brings the second test in line with the first, patching
`urllib3.PoolManager.urlopen`
This commit is contained in:
@@ -112,6 +112,7 @@ docs/TestObjectForMultipartRequestsRequestMarker.md
|
||||
docs/Tiger.md
|
||||
docs/UnnamedDictWithAdditionalModelListProperties.md
|
||||
docs/UnnamedDictWithAdditionalStringListProperties.md
|
||||
docs/UploadFileWithAdditionalPropertiesRequestObject.md
|
||||
docs/User.md
|
||||
docs/UserApi.md
|
||||
docs/WithNestedOneOf.md
|
||||
@@ -233,6 +234,7 @@ petstore_api/models/test_object_for_multipart_requests_request_marker.py
|
||||
petstore_api/models/tiger.py
|
||||
petstore_api/models/unnamed_dict_with_additional_model_list_properties.py
|
||||
petstore_api/models/unnamed_dict_with_additional_string_list_properties.py
|
||||
petstore_api/models/upload_file_with_additional_properties_request_object.py
|
||||
petstore_api/models/user.py
|
||||
petstore_api/models/with_nested_one_of.py
|
||||
petstore_api/py.typed
|
||||
|
||||
@@ -123,6 +123,7 @@ Class | Method | HTTP request | Description
|
||||
*FakeApi* | [**test_object_for_multipart_requests**](docs/FakeApi.md#test_object_for_multipart_requests) | **POST** /fake/object_for_multipart_requests |
|
||||
*FakeApi* | [**test_query_parameter_collection_format**](docs/FakeApi.md#test_query_parameter_collection_format) | **PUT** /fake/test-query-parameters |
|
||||
*FakeApi* | [**test_string_map_reference**](docs/FakeApi.md#test_string_map_reference) | **POST** /fake/stringMap-reference | test referenced string map
|
||||
*FakeApi* | [**upload_file_with_additional_properties**](docs/FakeApi.md#upload_file_with_additional_properties) | **POST** /fake/upload_file_with_additional_properties | uploads a file and additional properties using multipart/form-data
|
||||
*FakeClassnameTags123Api* | [**test_classname**](docs/FakeClassnameTags123Api.md#test_classname) | **PATCH** /fake_classname_test | To test class name in snake case
|
||||
*ImportTestDatetimeApi* | [**import_test_return_datetime**](docs/ImportTestDatetimeApi.md#import_test_return_datetime) | **GET** /import_test/return_datetime | test date time
|
||||
*PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store
|
||||
@@ -252,6 +253,7 @@ Class | Method | HTTP request | Description
|
||||
- [Tiger](docs/Tiger.md)
|
||||
- [UnnamedDictWithAdditionalModelListProperties](docs/UnnamedDictWithAdditionalModelListProperties.md)
|
||||
- [UnnamedDictWithAdditionalStringListProperties](docs/UnnamedDictWithAdditionalStringListProperties.md)
|
||||
- [UploadFileWithAdditionalPropertiesRequestObject](docs/UploadFileWithAdditionalPropertiesRequestObject.md)
|
||||
- [User](docs/User.md)
|
||||
- [WithNestedOneOf](docs/WithNestedOneOf.md)
|
||||
|
||||
|
||||
@@ -40,6 +40,7 @@ Method | HTTP request | Description
|
||||
[**test_object_for_multipart_requests**](FakeApi.md#test_object_for_multipart_requests) | **POST** /fake/object_for_multipart_requests |
|
||||
[**test_query_parameter_collection_format**](FakeApi.md#test_query_parameter_collection_format) | **PUT** /fake/test-query-parameters |
|
||||
[**test_string_map_reference**](FakeApi.md#test_string_map_reference) | **POST** /fake/stringMap-reference | test referenced string map
|
||||
[**upload_file_with_additional_properties**](FakeApi.md#upload_file_with_additional_properties) | **POST** /fake/upload_file_with_additional_properties | uploads a file and additional properties using multipart/form-data
|
||||
|
||||
|
||||
# **fake_any_type_request_body**
|
||||
@@ -2482,3 +2483,76 @@ No authorization required
|
||||
|
||||
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
|
||||
|
||||
# **upload_file_with_additional_properties**
|
||||
> ModelApiResponse upload_file_with_additional_properties(file, object=object, count=count)
|
||||
|
||||
uploads a file and additional properties using multipart/form-data
|
||||
|
||||
|
||||
|
||||
### Example
|
||||
|
||||
|
||||
```python
|
||||
import petstore_api
|
||||
from petstore_api.models.model_api_response import ModelApiResponse
|
||||
from petstore_api.models.upload_file_with_additional_properties_request_object import UploadFileWithAdditionalPropertiesRequestObject
|
||||
from petstore_api.rest import ApiException
|
||||
from pprint import pprint
|
||||
|
||||
# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2
|
||||
# See configuration.py for a list of all supported configuration parameters.
|
||||
configuration = petstore_api.Configuration(
|
||||
host = "http://petstore.swagger.io:80/v2"
|
||||
)
|
||||
|
||||
|
||||
# Enter a context with an instance of the API client
|
||||
async with petstore_api.ApiClient(configuration) as api_client:
|
||||
# Create an instance of the API class
|
||||
api_instance = petstore_api.FakeApi(api_client)
|
||||
file = None # bytearray | file to upload
|
||||
object = petstore_api.UploadFileWithAdditionalPropertiesRequestObject() # UploadFileWithAdditionalPropertiesRequestObject | (optional)
|
||||
count = 56 # int | Integer count (optional)
|
||||
|
||||
try:
|
||||
# uploads a file and additional properties using multipart/form-data
|
||||
api_response = await api_instance.upload_file_with_additional_properties(file, object=object, count=count)
|
||||
print("The response of FakeApi->upload_file_with_additional_properties:\n")
|
||||
pprint(api_response)
|
||||
except Exception as e:
|
||||
print("Exception when calling FakeApi->upload_file_with_additional_properties: %s\n" % e)
|
||||
```
|
||||
|
||||
|
||||
|
||||
### Parameters
|
||||
|
||||
|
||||
Name | Type | Description | Notes
|
||||
------------- | ------------- | ------------- | -------------
|
||||
**file** | **bytearray**| file to upload |
|
||||
**object** | [**UploadFileWithAdditionalPropertiesRequestObject**](UploadFileWithAdditionalPropertiesRequestObject.md)| | [optional]
|
||||
**count** | **int**| Integer count | [optional]
|
||||
|
||||
### Return type
|
||||
|
||||
[**ModelApiResponse**](ModelApiResponse.md)
|
||||
|
||||
### Authorization
|
||||
|
||||
No authorization required
|
||||
|
||||
### HTTP request headers
|
||||
|
||||
- **Content-Type**: multipart/form-data
|
||||
- **Accept**: application/json
|
||||
|
||||
### HTTP response details
|
||||
|
||||
| Status code | Description | Response headers |
|
||||
|-------------|-------------|------------------|
|
||||
**200** | successful operation | - |
|
||||
|
||||
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
|
||||
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
# UploadFileWithAdditionalPropertiesRequestObject
|
||||
|
||||
Additional object
|
||||
|
||||
## Properties
|
||||
|
||||
Name | Type | Description | Notes
|
||||
------------ | ------------- | ------------- | -------------
|
||||
**name** | **str** | | [optional]
|
||||
|
||||
## Example
|
||||
|
||||
```python
|
||||
from petstore_api.models.upload_file_with_additional_properties_request_object import UploadFileWithAdditionalPropertiesRequestObject
|
||||
|
||||
# TODO update the JSON string below
|
||||
json = "{}"
|
||||
# create an instance of UploadFileWithAdditionalPropertiesRequestObject from a JSON string
|
||||
upload_file_with_additional_properties_request_object_instance = UploadFileWithAdditionalPropertiesRequestObject.from_json(json)
|
||||
# print the JSON string representation of the object
|
||||
print(UploadFileWithAdditionalPropertiesRequestObject.to_json())
|
||||
|
||||
# convert the object into a dict
|
||||
upload_file_with_additional_properties_request_object_dict = upload_file_with_additional_properties_request_object_instance.to_dict()
|
||||
# create an instance of UploadFileWithAdditionalPropertiesRequestObject from a dict
|
||||
upload_file_with_additional_properties_request_object_from_dict = UploadFileWithAdditionalPropertiesRequestObject.from_dict(upload_file_with_additional_properties_request_object_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)
|
||||
|
||||
|
||||
@@ -141,5 +141,6 @@ from petstore_api.models.test_object_for_multipart_requests_request_marker impor
|
||||
from petstore_api.models.tiger import Tiger
|
||||
from petstore_api.models.unnamed_dict_with_additional_model_list_properties import UnnamedDictWithAdditionalModelListProperties
|
||||
from petstore_api.models.unnamed_dict_with_additional_string_list_properties import UnnamedDictWithAdditionalStringListProperties
|
||||
from petstore_api.models.upload_file_with_additional_properties_request_object import UploadFileWithAdditionalPropertiesRequestObject
|
||||
from petstore_api.models.user import User
|
||||
from petstore_api.models.with_nested_one_of import WithNestedOneOf
|
||||
|
||||
@@ -24,6 +24,7 @@ from petstore_api.models.client import Client
|
||||
from petstore_api.models.enum_class import EnumClass
|
||||
from petstore_api.models.file_schema_test_class import FileSchemaTestClass
|
||||
from petstore_api.models.health_check_result import HealthCheckResult
|
||||
from petstore_api.models.model_api_response import ModelApiResponse
|
||||
from petstore_api.models.outer_composite import OuterComposite
|
||||
from petstore_api.models.outer_enum_integer import OuterEnumInteger
|
||||
from petstore_api.models.outer_object_with_enum_property import OuterObjectWithEnumProperty
|
||||
@@ -31,6 +32,7 @@ from petstore_api.models.pet import Pet
|
||||
from petstore_api.models.tag import Tag
|
||||
from petstore_api.models.test_inline_freeform_additional_properties_request import TestInlineFreeformAdditionalPropertiesRequest
|
||||
from petstore_api.models.test_object_for_multipart_requests_request_marker import TestObjectForMultipartRequestsRequestMarker
|
||||
from petstore_api.models.upload_file_with_additional_properties_request_object import UploadFileWithAdditionalPropertiesRequestObject
|
||||
from petstore_api.models.user import User
|
||||
|
||||
from petstore_api.api_client import ApiClient, RequestSerialized
|
||||
@@ -9812,3 +9814,306 @@ class FakeApi:
|
||||
)
|
||||
|
||||
|
||||
|
||||
|
||||
@validate_call
|
||||
async def upload_file_with_additional_properties(
|
||||
self,
|
||||
file: Annotated[Union[StrictBytes, StrictStr, Tuple[StrictStr, StrictBytes]], Field(description="file to upload")],
|
||||
object: Optional[UploadFileWithAdditionalPropertiesRequestObject] = None,
|
||||
count: Annotated[Optional[StrictInt], Field(description="Integer count")] = None,
|
||||
_request_timeout: Union[
|
||||
None,
|
||||
Annotated[StrictFloat, Field(gt=0)],
|
||||
Tuple[
|
||||
Annotated[StrictFloat, Field(gt=0)],
|
||||
Annotated[StrictFloat, Field(gt=0)]
|
||||
]
|
||||
] = None,
|
||||
_request_auth: Optional[Dict[StrictStr, Any]] = None,
|
||||
_content_type: Optional[StrictStr] = None,
|
||||
_headers: Optional[Dict[StrictStr, Any]] = None,
|
||||
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
|
||||
) -> ModelApiResponse:
|
||||
"""uploads a file and additional properties using multipart/form-data
|
||||
|
||||
|
||||
|
||||
:param file: file to upload (required)
|
||||
:type file: bytearray
|
||||
:param object:
|
||||
:type object: UploadFileWithAdditionalPropertiesRequestObject
|
||||
:param count: Integer count
|
||||
:type count: int
|
||||
:param _request_timeout: timeout setting for this request. If one
|
||||
number provided, it will be total request
|
||||
timeout. It can also be a pair (tuple) of
|
||||
(connection, read) timeouts.
|
||||
:type _request_timeout: int, tuple(int, int), optional
|
||||
:param _request_auth: set to override the auth_settings for an a single
|
||||
request; this effectively ignores the
|
||||
authentication in the spec for a single request.
|
||||
:type _request_auth: dict, optional
|
||||
:param _content_type: force content-type for the request.
|
||||
:type _content_type: str, Optional
|
||||
:param _headers: set to override the headers for a single
|
||||
request; this effectively ignores the headers
|
||||
in the spec for a single request.
|
||||
:type _headers: dict, optional
|
||||
:param _host_index: set to override the host_index for a single
|
||||
request; this effectively ignores the host_index
|
||||
in the spec for a single request.
|
||||
:type _host_index: int, optional
|
||||
:return: Returns the result object.
|
||||
""" # noqa: E501
|
||||
|
||||
_param = self._upload_file_with_additional_properties_serialize(
|
||||
file=file,
|
||||
object=object,
|
||||
count=count,
|
||||
_request_auth=_request_auth,
|
||||
_content_type=_content_type,
|
||||
_headers=_headers,
|
||||
_host_index=_host_index
|
||||
)
|
||||
|
||||
_response_types_map: Dict[str, Optional[str]] = {
|
||||
'200': "ModelApiResponse",
|
||||
}
|
||||
response_data = await self.api_client.call_api(
|
||||
*_param,
|
||||
_request_timeout=_request_timeout
|
||||
)
|
||||
await response_data.read()
|
||||
return self.api_client.response_deserialize(
|
||||
response_data=response_data,
|
||||
response_types_map=_response_types_map,
|
||||
).data
|
||||
|
||||
|
||||
@validate_call
|
||||
async def upload_file_with_additional_properties_with_http_info(
|
||||
self,
|
||||
file: Annotated[Union[StrictBytes, StrictStr, Tuple[StrictStr, StrictBytes]], Field(description="file to upload")],
|
||||
object: Optional[UploadFileWithAdditionalPropertiesRequestObject] = None,
|
||||
count: Annotated[Optional[StrictInt], Field(description="Integer count")] = None,
|
||||
_request_timeout: Union[
|
||||
None,
|
||||
Annotated[StrictFloat, Field(gt=0)],
|
||||
Tuple[
|
||||
Annotated[StrictFloat, Field(gt=0)],
|
||||
Annotated[StrictFloat, Field(gt=0)]
|
||||
]
|
||||
] = None,
|
||||
_request_auth: Optional[Dict[StrictStr, Any]] = None,
|
||||
_content_type: Optional[StrictStr] = None,
|
||||
_headers: Optional[Dict[StrictStr, Any]] = None,
|
||||
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
|
||||
) -> ApiResponse[ModelApiResponse]:
|
||||
"""uploads a file and additional properties using multipart/form-data
|
||||
|
||||
|
||||
|
||||
:param file: file to upload (required)
|
||||
:type file: bytearray
|
||||
:param object:
|
||||
:type object: UploadFileWithAdditionalPropertiesRequestObject
|
||||
:param count: Integer count
|
||||
:type count: int
|
||||
:param _request_timeout: timeout setting for this request. If one
|
||||
number provided, it will be total request
|
||||
timeout. It can also be a pair (tuple) of
|
||||
(connection, read) timeouts.
|
||||
:type _request_timeout: int, tuple(int, int), optional
|
||||
:param _request_auth: set to override the auth_settings for an a single
|
||||
request; this effectively ignores the
|
||||
authentication in the spec for a single request.
|
||||
:type _request_auth: dict, optional
|
||||
:param _content_type: force content-type for the request.
|
||||
:type _content_type: str, Optional
|
||||
:param _headers: set to override the headers for a single
|
||||
request; this effectively ignores the headers
|
||||
in the spec for a single request.
|
||||
:type _headers: dict, optional
|
||||
:param _host_index: set to override the host_index for a single
|
||||
request; this effectively ignores the host_index
|
||||
in the spec for a single request.
|
||||
:type _host_index: int, optional
|
||||
:return: Returns the result object.
|
||||
""" # noqa: E501
|
||||
|
||||
_param = self._upload_file_with_additional_properties_serialize(
|
||||
file=file,
|
||||
object=object,
|
||||
count=count,
|
||||
_request_auth=_request_auth,
|
||||
_content_type=_content_type,
|
||||
_headers=_headers,
|
||||
_host_index=_host_index
|
||||
)
|
||||
|
||||
_response_types_map: Dict[str, Optional[str]] = {
|
||||
'200': "ModelApiResponse",
|
||||
}
|
||||
response_data = await self.api_client.call_api(
|
||||
*_param,
|
||||
_request_timeout=_request_timeout
|
||||
)
|
||||
await response_data.read()
|
||||
return self.api_client.response_deserialize(
|
||||
response_data=response_data,
|
||||
response_types_map=_response_types_map,
|
||||
)
|
||||
|
||||
|
||||
@validate_call
|
||||
async def upload_file_with_additional_properties_without_preload_content(
|
||||
self,
|
||||
file: Annotated[Union[StrictBytes, StrictStr, Tuple[StrictStr, StrictBytes]], Field(description="file to upload")],
|
||||
object: Optional[UploadFileWithAdditionalPropertiesRequestObject] = None,
|
||||
count: Annotated[Optional[StrictInt], Field(description="Integer count")] = None,
|
||||
_request_timeout: Union[
|
||||
None,
|
||||
Annotated[StrictFloat, Field(gt=0)],
|
||||
Tuple[
|
||||
Annotated[StrictFloat, Field(gt=0)],
|
||||
Annotated[StrictFloat, Field(gt=0)]
|
||||
]
|
||||
] = None,
|
||||
_request_auth: Optional[Dict[StrictStr, Any]] = None,
|
||||
_content_type: Optional[StrictStr] = None,
|
||||
_headers: Optional[Dict[StrictStr, Any]] = None,
|
||||
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
|
||||
) -> RESTResponseType:
|
||||
"""uploads a file and additional properties using multipart/form-data
|
||||
|
||||
|
||||
|
||||
:param file: file to upload (required)
|
||||
:type file: bytearray
|
||||
:param object:
|
||||
:type object: UploadFileWithAdditionalPropertiesRequestObject
|
||||
:param count: Integer count
|
||||
:type count: int
|
||||
:param _request_timeout: timeout setting for this request. If one
|
||||
number provided, it will be total request
|
||||
timeout. It can also be a pair (tuple) of
|
||||
(connection, read) timeouts.
|
||||
:type _request_timeout: int, tuple(int, int), optional
|
||||
:param _request_auth: set to override the auth_settings for an a single
|
||||
request; this effectively ignores the
|
||||
authentication in the spec for a single request.
|
||||
:type _request_auth: dict, optional
|
||||
:param _content_type: force content-type for the request.
|
||||
:type _content_type: str, Optional
|
||||
:param _headers: set to override the headers for a single
|
||||
request; this effectively ignores the headers
|
||||
in the spec for a single request.
|
||||
:type _headers: dict, optional
|
||||
:param _host_index: set to override the host_index for a single
|
||||
request; this effectively ignores the host_index
|
||||
in the spec for a single request.
|
||||
:type _host_index: int, optional
|
||||
:return: Returns the result object.
|
||||
""" # noqa: E501
|
||||
|
||||
_param = self._upload_file_with_additional_properties_serialize(
|
||||
file=file,
|
||||
object=object,
|
||||
count=count,
|
||||
_request_auth=_request_auth,
|
||||
_content_type=_content_type,
|
||||
_headers=_headers,
|
||||
_host_index=_host_index
|
||||
)
|
||||
|
||||
_response_types_map: Dict[str, Optional[str]] = {
|
||||
'200': "ModelApiResponse",
|
||||
}
|
||||
response_data = await self.api_client.call_api(
|
||||
*_param,
|
||||
_request_timeout=_request_timeout
|
||||
)
|
||||
return response_data.response
|
||||
|
||||
|
||||
def _upload_file_with_additional_properties_serialize(
|
||||
self,
|
||||
file,
|
||||
object,
|
||||
count,
|
||||
_request_auth,
|
||||
_content_type,
|
||||
_headers,
|
||||
_host_index,
|
||||
) -> RequestSerialized:
|
||||
|
||||
_host = None
|
||||
|
||||
_collection_formats: Dict[str, str] = {
|
||||
}
|
||||
|
||||
_path_params: Dict[str, str] = {}
|
||||
_query_params: List[Tuple[str, str]] = []
|
||||
_header_params: Dict[str, Optional[str]] = _headers or {}
|
||||
_form_params: List[Tuple[str, str]] = []
|
||||
_files: Dict[
|
||||
str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]]
|
||||
] = {}
|
||||
_body_params: Optional[bytes] = None
|
||||
|
||||
# process the path parameters
|
||||
# process the query parameters
|
||||
# process the header parameters
|
||||
# process the form parameters
|
||||
if file is not None:
|
||||
_files['file'] = file
|
||||
if object is not None:
|
||||
_form_params.append(('object', object))
|
||||
if count is not None:
|
||||
_form_params.append(('count', count))
|
||||
# process the body parameter
|
||||
|
||||
|
||||
# set the HTTP header `Accept`
|
||||
if 'Accept' not in _header_params:
|
||||
_header_params['Accept'] = self.api_client.select_header_accept(
|
||||
[
|
||||
'application/json'
|
||||
]
|
||||
)
|
||||
|
||||
# set the HTTP header `Content-Type`
|
||||
if _content_type:
|
||||
_header_params['Content-Type'] = _content_type
|
||||
else:
|
||||
_default_content_type = (
|
||||
self.api_client.select_header_content_type(
|
||||
[
|
||||
'multipart/form-data'
|
||||
]
|
||||
)
|
||||
)
|
||||
if _default_content_type is not None:
|
||||
_header_params['Content-Type'] = _default_content_type
|
||||
|
||||
# authentication setting
|
||||
_auth_settings: List[str] = [
|
||||
]
|
||||
|
||||
return self.api_client.param_serialize(
|
||||
method='POST',
|
||||
resource_path='/fake/upload_file_with_additional_properties',
|
||||
path_params=_path_params,
|
||||
query_params=_query_params,
|
||||
header_params=_header_params,
|
||||
body=_body_params,
|
||||
post_params=_form_params,
|
||||
files=_files,
|
||||
auth_settings=_auth_settings,
|
||||
collection_formats=_collection_formats,
|
||||
_host=_host,
|
||||
_request_auth=_request_auth
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -116,5 +116,6 @@ from petstore_api.models.test_object_for_multipart_requests_request_marker impor
|
||||
from petstore_api.models.tiger import Tiger
|
||||
from petstore_api.models.unnamed_dict_with_additional_model_list_properties import UnnamedDictWithAdditionalModelListProperties
|
||||
from petstore_api.models.unnamed_dict_with_additional_string_list_properties import UnnamedDictWithAdditionalStringListProperties
|
||||
from petstore_api.models.upload_file_with_additional_properties_request_object import UploadFileWithAdditionalPropertiesRequestObject
|
||||
from petstore_api.models.user import User
|
||||
from petstore_api.models.with_nested_one_of import WithNestedOneOf
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
|
||||
class UploadFileWithAdditionalPropertiesRequestObject(BaseModel):
|
||||
"""
|
||||
Additional object
|
||||
""" # noqa: E501
|
||||
name: Optional[StrictStr] = None
|
||||
__properties: ClassVar[List[str]] = ["name"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
populate_by_name=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
)
|
||||
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
|
||||
return json.dumps(self.to_dict())
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of UploadFileWithAdditionalPropertiesRequestObject from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias.
|
||||
|
||||
This has the following differences from calling pydantic's
|
||||
`self.model_dump(by_alias=True)`:
|
||||
|
||||
* `None` is only added to the output dict for nullable fields that
|
||||
were set at model initialization. Other fields with value `None`
|
||||
are ignored.
|
||||
"""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of UploadFileWithAdditionalPropertiesRequestObject from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"name": obj.get("name")
|
||||
})
|
||||
return _obj
|
||||
|
||||
|
||||
@@ -184,6 +184,11 @@ class RESTClientObject:
|
||||
content_type=v[2]
|
||||
)
|
||||
else:
|
||||
# Ensures that dict objects are serialized
|
||||
if isinstance(v, dict):
|
||||
v = json.dumps(v)
|
||||
elif isinstance(v, int):
|
||||
v = str(v)
|
||||
data.add_field(k, v)
|
||||
args["data"] = data
|
||||
|
||||
@@ -208,8 +213,3 @@ class RESTClientObject:
|
||||
r = await pool_manager.request(**args)
|
||||
|
||||
return RESTResponse(r)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
from petstore_api.models.upload_file_with_additional_properties_request_object import UploadFileWithAdditionalPropertiesRequestObject
|
||||
|
||||
class TestUploadFileWithAdditionalPropertiesRequestObject(unittest.TestCase):
|
||||
"""UploadFileWithAdditionalPropertiesRequestObject unit test stubs"""
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
||||
def make_instance(self, include_optional) -> UploadFileWithAdditionalPropertiesRequestObject:
|
||||
"""Test UploadFileWithAdditionalPropertiesRequestObject
|
||||
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 `UploadFileWithAdditionalPropertiesRequestObject`
|
||||
"""
|
||||
model = UploadFileWithAdditionalPropertiesRequestObject()
|
||||
if include_optional:
|
||||
return UploadFileWithAdditionalPropertiesRequestObject(
|
||||
name = ''
|
||||
)
|
||||
else:
|
||||
return UploadFileWithAdditionalPropertiesRequestObject(
|
||||
)
|
||||
"""
|
||||
|
||||
def testUploadFileWithAdditionalPropertiesRequestObject(self):
|
||||
"""Test UploadFileWithAdditionalPropertiesRequestObject"""
|
||||
# inst_req_only = self.make_instance(include_optional=False)
|
||||
# inst_req_and_optional = self.make_instance(include_optional=True)
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,74 @@
|
||||
import os
|
||||
import unittest
|
||||
from unittest.mock import AsyncMock, Mock, patch
|
||||
|
||||
import petstore_api
|
||||
|
||||
|
||||
def get_field_from_formdata(formdata, name):
|
||||
return next(filter(lambda x: x[0]["name"] == name, formdata._fields))[-1]
|
||||
|
||||
|
||||
class TestMultipleResponseTypes(unittest.IsolatedAsyncioTestCase):
|
||||
def setUpFiles(self):
|
||||
self.test_file_dir = os.path.join(os.path.dirname(__file__), "..", "testfiles")
|
||||
self.test_file_dir = os.path.realpath(self.test_file_dir)
|
||||
self.test_file_path = os.path.join(self.test_file_dir, "foo.png")
|
||||
|
||||
def setUp(self):
|
||||
self.setUpFiles()
|
||||
|
||||
async def test_multipart_requests(self):
|
||||
mock_resp = AsyncMock()
|
||||
mock_resp.return_value.read.return_value = b"some text"
|
||||
mock_resp.return_value.status = 200
|
||||
mock_resp.return_value.headers = {}
|
||||
|
||||
marker = petstore_api.TestObjectForMultipartRequestsRequestMarker(
|
||||
name="name",
|
||||
)
|
||||
|
||||
with patch("aiohttp.ClientSession.request", mock_resp):
|
||||
async with petstore_api.ApiClient() as api_client:
|
||||
fake_api = petstore_api.FakeApi(api_client)
|
||||
await fake_api.test_object_for_multipart_requests(marker=marker)
|
||||
|
||||
# success if no errors
|
||||
|
||||
async def test_multipart_requests_with_file_and_additional_properties(self):
|
||||
mock_resp = Mock()
|
||||
mock_resp.status = 200
|
||||
mock_resp.read = AsyncMock(
|
||||
return_value=b'{"code": 200, "type": "success", "message": "OK"}'
|
||||
)
|
||||
mock_resp.headers = {"Content-Type": "application/json"}
|
||||
|
||||
mock_request = AsyncMock(return_value=mock_resp)
|
||||
with open(self.test_file_path, "rb") as f, patch(
|
||||
"aiohttp.ClientSession.request", mock_request
|
||||
):
|
||||
async with petstore_api.ApiClient() as api_client:
|
||||
fake_api = petstore_api.FakeApi(api_client)
|
||||
returned = await fake_api.upload_file_with_additional_properties(
|
||||
file=(self.test_file_path, f.read()),
|
||||
count=100,
|
||||
object=petstore_api.UploadFileWithAdditionalPropertiesRequestObject(
|
||||
name="foo"
|
||||
),
|
||||
)
|
||||
|
||||
assert (
|
||||
returned.code == 200
|
||||
and returned.type == "success"
|
||||
and returned.message == "OK"
|
||||
)
|
||||
|
||||
mock_request.assert_called_once()
|
||||
|
||||
formdata = mock_request.call_args_list[0].kwargs["data"]
|
||||
|
||||
data_object = get_field_from_formdata(formdata, "object")
|
||||
data_count = get_field_from_formdata(formdata, "count")
|
||||
|
||||
assert type(data_count) is str
|
||||
assert type(data_object) is str
|
||||
Reference in New Issue
Block a user