From 0d66133fb84eb58aff57fc1d109b1915ed5c8519 Mon Sep 17 00:00:00 2001 From: Rory Schadler <48921090+roryschadler@users.noreply.github.com> Date: Mon, 5 Aug 2024 10:47:50 -0400 Subject: [PATCH 01/10] fix: object serialization for multipart requests This PR is essentially but for the asyncio client. --- .../src/main/resources/python/asyncio/rest.mustache | 8 +++----- .../client/petstore/python-aiohttp/petstore_api/rest.py | 8 +++----- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/python/asyncio/rest.mustache b/modules/openapi-generator/src/main/resources/python/asyncio/rest.mustache index c3f8643687ab..5a86207bd7f5 100644 --- a/modules/openapi-generator/src/main/resources/python/asyncio/rest.mustache +++ b/modules/openapi-generator/src/main/resources/python/asyncio/rest.mustache @@ -174,6 +174,9 @@ class RESTClientObject: content_type=v[2] ) else: + # Ensures that dict objects are serialized + if isinstance(v, dict): + v = json.dumps(v) data.add_field(k, v) args["data"] = data @@ -198,8 +201,3 @@ class RESTClientObject: r = await pool_manager.request(**args) return RESTResponse(r) - - - - - diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/rest.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/rest.py index 53b81b840d2c..0cbaf99eb256 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/rest.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/rest.py @@ -184,6 +184,9 @@ async def request( content_type=v[2] ) else: + # Ensures that dict objects are serialized + if isinstance(v, dict): + v = json.dumps(v) data.add_field(k, v) args["data"] = data @@ -208,8 +211,3 @@ async def request( r = await pool_manager.request(**args) return RESTResponse(r) - - - - - From e5f25057d11072093361864cbb0f3202543ebd25 Mon Sep 17 00:00:00 2001 From: Rory Schadler <48921090+roryschadler@users.noreply.github.com> Date: Wed, 7 Aug 2024 13:09:27 -0400 Subject: [PATCH 02/10] fix: int serialization for multipart requests urllib3 handles serializing ints in post params (ref 1), while asyncio explicitly does not (ref 2). ref 1: ref 2: --- .../src/main/resources/python/asyncio/rest.mustache | 2 ++ .../client/petstore/python-aiohttp/petstore_api/rest.py | 2 ++ 2 files changed, 4 insertions(+) diff --git a/modules/openapi-generator/src/main/resources/python/asyncio/rest.mustache b/modules/openapi-generator/src/main/resources/python/asyncio/rest.mustache index 5a86207bd7f5..9da1091f4f08 100644 --- a/modules/openapi-generator/src/main/resources/python/asyncio/rest.mustache +++ b/modules/openapi-generator/src/main/resources/python/asyncio/rest.mustache @@ -177,6 +177,8 @@ class RESTClientObject: # 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 diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/rest.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/rest.py index 0cbaf99eb256..ea9f42a51c4c 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/rest.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/rest.py @@ -187,6 +187,8 @@ async def request( # 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 From c1a58f4c5d8fbcf2ddbacd0eb8d3d84a7e7fac38 Mon Sep 17 00:00:00 2001 From: Rory Schadler <48921090+roryschadler@users.noreply.github.com> Date: Thu, 22 Aug 2024 22:47:05 -0400 Subject: [PATCH 03/10] test: new fake multipart endpoint with files and body --- ...ith-fake-endpoints-models-for-testing.yaml | 35 ++ .../python-aiohttp/.openapi-generator/FILES | 3 + .../client/petstore/python-aiohttp/README.md | 2 + .../petstore/python-aiohttp/docs/FakeApi.md | 74 +++++ ...leWithAdditionalPropertiesRequestObject.md | 30 ++ .../python-aiohttp/petstore_api/__init__.py | 1 + .../petstore_api/api/fake_api.py | 305 ++++++++++++++++++ .../petstore_api/models/__init__.py | 1 + ...th_additional_properties_request_object.py | 87 +++++ ...th_additional_properties_request_object.py | 51 +++ .../.openapi-generator/FILES | 3 + .../python-pydantic-v1-aiohttp/README.md | 2 + .../docs/FakeApi.md | 73 +++++ ...leWithAdditionalPropertiesRequestObject.md | 29 ++ .../petstore_api/__init__.py | 1 + .../petstore_api/api/fake_api.py | 149 +++++++++ .../petstore_api/models/__init__.py | 1 + ...th_additional_properties_request_object.py | 71 ++++ ...th_additional_properties_request_object.py | 52 +++ .../.openapi-generator/FILES | 3 + .../petstore/python-pydantic-v1/README.md | 2 + .../python-pydantic-v1/docs/FakeApi.md | 73 +++++ ...leWithAdditionalPropertiesRequestObject.md | 29 ++ .../petstore_api/__init__.py | 1 + .../petstore_api/api/fake_api.py | 165 ++++++++++ .../petstore_api/models/__init__.py | 1 + ...th_additional_properties_request_object.py | 83 +++++ ...th_additional_properties_request_object.py | 52 +++ .../petstore/python/.openapi-generator/FILES | 3 + .../openapi3/client/petstore/python/README.md | 2 + .../client/petstore/python/docs/FakeApi.md | 74 +++++ ...leWithAdditionalPropertiesRequestObject.md | 30 ++ .../petstore/python/petstore_api/__init__.py | 1 + .../python/petstore_api/api/fake_api.py | 305 ++++++++++++++++++ .../python/petstore_api/models/__init__.py | 1 + ...th_additional_properties_request_object.py | 100 ++++++ ...th_additional_properties_request_object.py | 51 +++ 37 files changed, 1946 insertions(+) create mode 100644 samples/openapi3/client/petstore/python-aiohttp/docs/UploadFileWithAdditionalPropertiesRequestObject.md create mode 100644 samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/upload_file_with_additional_properties_request_object.py create mode 100644 samples/openapi3/client/petstore/python-aiohttp/test/test_upload_file_with_additional_properties_request_object.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/UploadFileWithAdditionalPropertiesRequestObject.md create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/upload_file_with_additional_properties_request_object.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_upload_file_with_additional_properties_request_object.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1/docs/UploadFileWithAdditionalPropertiesRequestObject.md create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/upload_file_with_additional_properties_request_object.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1/test/test_upload_file_with_additional_properties_request_object.py create mode 100644 samples/openapi3/client/petstore/python/docs/UploadFileWithAdditionalPropertiesRequestObject.md create mode 100644 samples/openapi3/client/petstore/python/petstore_api/models/upload_file_with_additional_properties_request_object.py create mode 100644 samples/openapi3/client/petstore/python/test/test_upload_file_with_additional_properties_request_object.py diff --git a/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing.yaml index e6fc5fbf6fc0..bd071a0b132d 100644 --- a/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing.yaml @@ -1552,6 +1552,41 @@ paths: schema: type: string format: byte + /fake/upload_file_with_additional_properties: + post: + tags: + - fake + summary: uploads a file and additional properties using multipart/form-data + description: '' + operationId: uploadFileWithAdditionalProperties + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + file: + description: file to upload + type: string + format: binary + object: + description: Additional object + type: object + properties: + name: + type: string + count: + description: Integer count + type: integer + required: + - file /import_test/return_datetime: get: tags: diff --git a/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/FILES b/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/FILES index 36cb0392c334..e135e1a2a180 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/FILES @@ -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 @@ -244,4 +246,5 @@ setup.cfg setup.py test-requirements.txt test/__init__.py +test/test_upload_file_with_additional_properties_request_object.py tox.ini diff --git a/samples/openapi3/client/petstore/python-aiohttp/README.md b/samples/openapi3/client/petstore/python-aiohttp/README.md index 93a8e0a22566..5e4bef3e4142 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/README.md +++ b/samples/openapi3/client/petstore/python-aiohttp/README.md @@ -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) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/FakeApi.md b/samples/openapi3/client/petstore/python-aiohttp/docs/FakeApi.md index 7d895e650b3a..901471b5477b 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/FakeApi.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/FakeApi.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) + diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/UploadFileWithAdditionalPropertiesRequestObject.md b/samples/openapi3/client/petstore/python-aiohttp/docs/UploadFileWithAdditionalPropertiesRequestObject.md new file mode 100644 index 000000000000..141027780371 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/UploadFileWithAdditionalPropertiesRequestObject.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) + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/__init__.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/__init__.py index 5c8b494eec36..27cc58ac25b6 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/__init__.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/__init__.py @@ -141,5 +141,6 @@ 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 diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/fake_api.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/fake_api.py index cb55e0371cbe..ff7f136569f5 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/fake_api.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/fake_api.py @@ -24,6 +24,7 @@ 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.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 @@ def _test_string_map_reference_serialize( ) + + + @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 + ) + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/__init__.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/__init__.py index b1dbefee666d..12531e2d9063 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/__init__.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/__init__.py @@ -116,5 +116,6 @@ 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 diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/upload_file_with_additional_properties_request_object.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/upload_file_with_additional_properties_request_object.py new file mode 100644 index 000000000000..9040618ac0d7 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/upload_file_with_additional_properties_request_object.py @@ -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 + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/test/test_upload_file_with_additional_properties_request_object.py b/samples/openapi3/client/petstore/python-aiohttp/test/test_upload_file_with_additional_properties_request_object.py new file mode 100644 index 000000000000..8b3fa3b90840 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/test/test_upload_file_with_additional_properties_request_object.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +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() diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/.openapi-generator/FILES b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/.openapi-generator/FILES index aa4a8eee280b..0f579290c2f9 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/.openapi-generator/FILES @@ -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 @@ -244,4 +246,5 @@ setup.cfg setup.py test-requirements.txt test/__init__.py +test/test_upload_file_with_additional_properties_request_object.py tox.ini diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/README.md b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/README.md index c01c6e92fef4..ee6d85b7df5f 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/README.md +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/README.md @@ -124,6 +124,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 @@ -253,6 +254,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) diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/FakeApi.md b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/FakeApi.md index e33215808a67..512323e3286a 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/FakeApi.md +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/FakeApi.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** @@ -2446,3 +2447,75 @@ 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** +> ApiResponse upload_file_with_additional_properties(file, object=object, count=count) + +uploads a file and additional properties using multipart/form-data + + + +### Example + +```python +import time +import os +import petstore_api +from petstore_api.models.api_response import ApiResponse +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 + +[**ApiResponse**](ApiResponse.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) + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/UploadFileWithAdditionalPropertiesRequestObject.md b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/UploadFileWithAdditionalPropertiesRequestObject.md new file mode 100644 index 000000000000..7b983039ab90 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/UploadFileWithAdditionalPropertiesRequestObject.md @@ -0,0 +1,29 @@ +# 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) + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/__init__.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/__init__.py index 0d1b6af243ff..f178ffe52f18 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/__init__.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/__init__.py @@ -141,5 +141,6 @@ 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 diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/api/fake_api.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/api/fake_api.py index ab7bdb1b0d60..7ee53259a5b9 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/api/fake_api.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/api/fake_api.py @@ -26,6 +26,7 @@ from typing import Any, Dict, List, Optional, Union +from petstore_api.models.api_response import ApiResponse 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 @@ -37,6 +38,7 @@ 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 @@ -4662,3 +4664,150 @@ async def test_string_map_reference_with_http_info(self, request_body : Annotate _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, _request_auth=_params.get('_request_auth')) + + @validate_arguments + async def upload_file_with_additional_properties(self, file : Annotated[Union[StrictBytes, StrictStr], Field(..., description="file to upload")], object : Optional[UploadFileWithAdditionalPropertiesRequestObject] = None, count : Annotated[Optional[StrictInt], Field(description="Integer count")] = None, **kwargs) -> ApiResponse: # noqa: E501 + """uploads a file and additional properties using multipart/form-data # noqa: E501 + + # noqa: E501 + + :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. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: ApiResponse + """ + kwargs['_return_http_data_only'] = True + if '_preload_content' in kwargs: + message = "Error! Please call the upload_file_with_additional_properties_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return await self.upload_file_with_additional_properties_with_http_info(file, object, count, **kwargs) # noqa: E501 + + @validate_arguments + async def upload_file_with_additional_properties_with_http_info(self, file : Annotated[Union[StrictBytes, StrictStr], Field(..., description="file to upload")], object : Optional[UploadFileWithAdditionalPropertiesRequestObject] = None, count : Annotated[Optional[StrictInt], Field(description="Integer count")] = None, **kwargs) -> ApiResponse: # noqa: E501 + """uploads a file and additional properties using multipart/form-data # noqa: E501 + + # noqa: E501 + + :param file: file to upload (required) + :type file: bytearray + :param object: + :type object: UploadFileWithAdditionalPropertiesRequestObject + :param count: Integer count + :type count: int + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :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. + :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 + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(ApiResponse, status_code(int), headers(HTTPHeaderDict)) + """ + + _params = locals() + + _all_params = [ + 'file', + 'object', + 'count' + ] + _all_params.extend( + [ + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth', + '_content_type', + '_headers' + ] + ) + + # validate the arguments + for _key, _val in _params['kwargs'].items(): + if _key not in _all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method upload_file_with_additional_properties" % _key + ) + _params[_key] = _val + del _params['kwargs'] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get('_headers', {})) + # process the form parameters + _form_params = [] + _files = {} + if _params['file'] is not None: + _files['file'] = _params['file'] + + if _params['object'] is not None: + _form_params.append(('object', _params['object'])) + + if _params['count'] is not None: + _form_params.append(('count', _params['count'])) + + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 + + # set the HTTP header `Content-Type` + _content_types_list = _params.get('_content_type', + self.api_client.select_header_content_type( + ['multipart/form-data'])) + if _content_types_list: + _header_params['Content-Type'] = _content_types_list + + # authentication setting + _auth_settings = [] # noqa: E501 + + _response_types_map = { + '200': "ApiResponse", + } + + return await self.api_client.call_api( + '/fake/upload_file_with_additional_properties', 'POST', + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=_params.get('_preload_content', True), + _request_timeout=_params.get('_request_timeout'), + collection_formats=_collection_formats, + _request_auth=_params.get('_request_auth')) diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/__init__.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/__init__.py index de87c281c8fb..b6a5d674a51c 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/__init__.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/__init__.py @@ -116,5 +116,6 @@ 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 diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/upload_file_with_additional_properties_request_object.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/upload_file_with_additional_properties_request_object.py new file mode 100644 index 000000000000..bafe5045c0d5 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/upload_file_with_additional_properties_request_object.py @@ -0,0 +1,71 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Optional +from pydantic import BaseModel, StrictStr + +class UploadFileWithAdditionalPropertiesRequestObject(BaseModel): + """ + Additional object # noqa: E501 + """ + name: Optional[StrictStr] = None + __properties = ["name"] + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> UploadFileWithAdditionalPropertiesRequestObject: + """Create an instance of UploadFileWithAdditionalPropertiesRequestObject from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + }, + exclude_none=True) + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> UploadFileWithAdditionalPropertiesRequestObject: + """Create an instance of UploadFileWithAdditionalPropertiesRequestObject from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return UploadFileWithAdditionalPropertiesRequestObject.parse_obj(obj) + + _obj = UploadFileWithAdditionalPropertiesRequestObject.parse_obj({ + "name": obj.get("name") + }) + return _obj + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_upload_file_with_additional_properties_request_object.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_upload_file_with_additional_properties_request_object.py new file mode 100644 index 000000000000..32ead9222dd8 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_upload_file_with_additional_properties_request_object.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +from petstore_api.models.upload_file_with_additional_properties_request_object import UploadFileWithAdditionalPropertiesRequestObject # noqa: E501 + +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_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 `UploadFileWithAdditionalPropertiesRequestObject` + """ + model = UploadFileWithAdditionalPropertiesRequestObject() # noqa: E501 + 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() diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/.openapi-generator/FILES b/samples/openapi3/client/petstore/python-pydantic-v1/.openapi-generator/FILES index aa4a8eee280b..0f579290c2f9 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python-pydantic-v1/.openapi-generator/FILES @@ -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 @@ -244,4 +246,5 @@ setup.cfg setup.py test-requirements.txt test/__init__.py +test/test_upload_file_with_additional_properties_request_object.py tox.ini diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/README.md b/samples/openapi3/client/petstore/python-pydantic-v1/README.md index 684881a19a9b..aff627886543 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/README.md +++ b/samples/openapi3/client/petstore/python-pydantic-v1/README.md @@ -124,6 +124,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 @@ -253,6 +254,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) diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/docs/FakeApi.md b/samples/openapi3/client/petstore/python-pydantic-v1/docs/FakeApi.md index 59d600df9879..3777d3d76e0e 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/docs/FakeApi.md +++ b/samples/openapi3/client/petstore/python-pydantic-v1/docs/FakeApi.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** @@ -2446,3 +2447,75 @@ 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** +> ApiResponse upload_file_with_additional_properties(file, object=object, count=count) + +uploads a file and additional properties using multipart/form-data + + + +### Example + +```python +import time +import os +import petstore_api +from petstore_api.models.api_response import ApiResponse +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 +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 = 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 + +[**ApiResponse**](ApiResponse.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) + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/docs/UploadFileWithAdditionalPropertiesRequestObject.md b/samples/openapi3/client/petstore/python-pydantic-v1/docs/UploadFileWithAdditionalPropertiesRequestObject.md new file mode 100644 index 000000000000..7b983039ab90 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/docs/UploadFileWithAdditionalPropertiesRequestObject.md @@ -0,0 +1,29 @@ +# 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) + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/__init__.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/__init__.py index 0d1b6af243ff..f178ffe52f18 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/__init__.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/__init__.py @@ -141,5 +141,6 @@ 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 diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/api/fake_api.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/api/fake_api.py index 88992b423cc3..62ef06ed6b0e 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/api/fake_api.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/api/fake_api.py @@ -25,6 +25,7 @@ from typing import Any, Dict, List, Optional, Union +from petstore_api.models.api_response import ApiResponse 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 @@ -36,6 +37,7 @@ 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 @@ -5237,3 +5239,166 @@ def test_string_map_reference_with_http_info(self, request_body : Annotated[Dict _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, _request_auth=_params.get('_request_auth')) + + @validate_arguments + def upload_file_with_additional_properties(self, file : Annotated[Union[StrictBytes, StrictStr], Field(..., description="file to upload")], object : Optional[UploadFileWithAdditionalPropertiesRequestObject] = None, count : Annotated[Optional[StrictInt], Field(description="Integer count")] = None, **kwargs) -> ApiResponse: # noqa: E501 + """uploads a file and additional properties using multipart/form-data # noqa: E501 + + # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.upload_file_with_additional_properties(file, object, count, async_req=True) + >>> result = thread.get() + + :param file: file to upload (required) + :type file: bytearray + :param object: + :type object: UploadFileWithAdditionalPropertiesRequestObject + :param count: Integer count + :type count: int + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :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. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: ApiResponse + """ + kwargs['_return_http_data_only'] = True + if '_preload_content' in kwargs: + message = "Error! Please call the upload_file_with_additional_properties_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.upload_file_with_additional_properties_with_http_info(file, object, count, **kwargs) # noqa: E501 + + @validate_arguments + def upload_file_with_additional_properties_with_http_info(self, file : Annotated[Union[StrictBytes, StrictStr], Field(..., description="file to upload")], object : Optional[UploadFileWithAdditionalPropertiesRequestObject] = None, count : Annotated[Optional[StrictInt], Field(description="Integer count")] = None, **kwargs) -> ApiResponse: # noqa: E501 + """uploads a file and additional properties using multipart/form-data # noqa: E501 + + # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.upload_file_with_additional_properties_with_http_info(file, object, count, async_req=True) + >>> result = thread.get() + + :param file: file to upload (required) + :type file: bytearray + :param object: + :type object: UploadFileWithAdditionalPropertiesRequestObject + :param count: Integer count + :type count: int + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :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. + :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 + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(ApiResponse, status_code(int), headers(HTTPHeaderDict)) + """ + + _params = locals() + + _all_params = [ + 'file', + 'object', + 'count' + ] + _all_params.extend( + [ + 'async_req', + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth', + '_content_type', + '_headers' + ] + ) + + # validate the arguments + for _key, _val in _params['kwargs'].items(): + if _key not in _all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method upload_file_with_additional_properties" % _key + ) + _params[_key] = _val + del _params['kwargs'] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get('_headers', {})) + # process the form parameters + _form_params = [] + _files = {} + if _params['file'] is not None: + _files['file'] = _params['file'] + + if _params['object'] is not None: + _form_params.append(('object', _params['object'])) + + if _params['count'] is not None: + _form_params.append(('count', _params['count'])) + + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 + + # set the HTTP header `Content-Type` + _content_types_list = _params.get('_content_type', + self.api_client.select_header_content_type( + ['multipart/form-data'])) + if _content_types_list: + _header_params['Content-Type'] = _content_types_list + + # authentication setting + _auth_settings = [] # noqa: E501 + + _response_types_map = { + '200': "ApiResponse", + } + + return self.api_client.call_api( + '/fake/upload_file_with_additional_properties', 'POST', + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get('async_req'), + _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=_params.get('_preload_content', True), + _request_timeout=_params.get('_request_timeout'), + collection_formats=_collection_formats, + _request_auth=_params.get('_request_auth')) diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/__init__.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/__init__.py index de87c281c8fb..b6a5d674a51c 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/__init__.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/__init__.py @@ -116,5 +116,6 @@ 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 diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/upload_file_with_additional_properties_request_object.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/upload_file_with_additional_properties_request_object.py new file mode 100644 index 000000000000..a8820b0262b4 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/upload_file_with_additional_properties_request_object.py @@ -0,0 +1,83 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, Dict, Optional +from pydantic import BaseModel, StrictStr + +class UploadFileWithAdditionalPropertiesRequestObject(BaseModel): + """ + Additional object # noqa: E501 + """ + name: Optional[StrictStr] = None + additional_properties: Dict[str, Any] = {} + __properties = ["name"] + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> UploadFileWithAdditionalPropertiesRequestObject: + """Create an instance of UploadFileWithAdditionalPropertiesRequestObject from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + "additional_properties" + }, + exclude_none=True) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> UploadFileWithAdditionalPropertiesRequestObject: + """Create an instance of UploadFileWithAdditionalPropertiesRequestObject from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return UploadFileWithAdditionalPropertiesRequestObject.parse_obj(obj) + + _obj = UploadFileWithAdditionalPropertiesRequestObject.parse_obj({ + "name": obj.get("name") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/test/test_upload_file_with_additional_properties_request_object.py b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_upload_file_with_additional_properties_request_object.py new file mode 100644 index 000000000000..32ead9222dd8 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_upload_file_with_additional_properties_request_object.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +from petstore_api.models.upload_file_with_additional_properties_request_object import UploadFileWithAdditionalPropertiesRequestObject # noqa: E501 + +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_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 `UploadFileWithAdditionalPropertiesRequestObject` + """ + model = UploadFileWithAdditionalPropertiesRequestObject() # noqa: E501 + 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() diff --git a/samples/openapi3/client/petstore/python/.openapi-generator/FILES b/samples/openapi3/client/petstore/python/.openapi-generator/FILES index 36cb0392c334..e135e1a2a180 100755 --- a/samples/openapi3/client/petstore/python/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python/.openapi-generator/FILES @@ -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 @@ -244,4 +246,5 @@ setup.cfg setup.py test-requirements.txt test/__init__.py +test/test_upload_file_with_additional_properties_request_object.py tox.ini diff --git a/samples/openapi3/client/petstore/python/README.md b/samples/openapi3/client/petstore/python/README.md index 3b0793204ba6..130f174208fe 100755 --- a/samples/openapi3/client/petstore/python/README.md +++ b/samples/openapi3/client/petstore/python/README.md @@ -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) diff --git a/samples/openapi3/client/petstore/python/docs/FakeApi.md b/samples/openapi3/client/petstore/python/docs/FakeApi.md index a45bd7670a8c..7b0665800fd5 100644 --- a/samples/openapi3/client/petstore/python/docs/FakeApi.md +++ b/samples/openapi3/client/petstore/python/docs/FakeApi.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 +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 = 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) + diff --git a/samples/openapi3/client/petstore/python/docs/UploadFileWithAdditionalPropertiesRequestObject.md b/samples/openapi3/client/petstore/python/docs/UploadFileWithAdditionalPropertiesRequestObject.md new file mode 100644 index 000000000000..141027780371 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/UploadFileWithAdditionalPropertiesRequestObject.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) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/__init__.py index 5c8b494eec36..27cc58ac25b6 100755 --- a/samples/openapi3/client/petstore/python/petstore_api/__init__.py +++ b/samples/openapi3/client/petstore/python/petstore_api/__init__.py @@ -141,5 +141,6 @@ 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 diff --git a/samples/openapi3/client/petstore/python/petstore_api/api/fake_api.py b/samples/openapi3/client/petstore/python/petstore_api/api/fake_api.py index 1848c6c44065..78d16e5f5045 100755 --- a/samples/openapi3/client/petstore/python/petstore_api/api/fake_api.py +++ b/samples/openapi3/client/petstore/python/petstore_api/api/fake_api.py @@ -24,6 +24,7 @@ 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.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 @@ def _test_string_map_reference_serialize( ) + + + @validate_call + 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 = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + 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 = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + 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 = 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 + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py index b1dbefee666d..12531e2d9063 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py @@ -116,5 +116,6 @@ 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 diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/upload_file_with_additional_properties_request_object.py b/samples/openapi3/client/petstore/python/petstore_api/models/upload_file_with_additional_properties_request_object.py new file mode 100644 index 000000000000..6d79131bfe79 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/models/upload_file_with_additional_properties_request_object.py @@ -0,0 +1,100 @@ +# 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 + additional_properties: Dict[str, Any] = {} + __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. + * Fields in `self.additional_properties` are added to the output dict. + """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of 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") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + diff --git a/samples/openapi3/client/petstore/python/test/test_upload_file_with_additional_properties_request_object.py b/samples/openapi3/client/petstore/python/test/test_upload_file_with_additional_properties_request_object.py new file mode 100644 index 000000000000..8b3fa3b90840 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_upload_file_with_additional_properties_request_object.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +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() From edd933aaae051b5622943558163d99ae6ecde512 Mon Sep 17 00:00:00 2001 From: Rory Schadler <48921090+roryschadler@users.noreply.github.com> Date: Thu, 22 Aug 2024 22:47:57 -0400 Subject: [PATCH 04/10] test: regression test for stringified body params --- .../python-aiohttp/tests/test_rest.py | 74 +++++++++++++++++++ .../client/petstore/python/tests/test_rest.py | 36 +++++++-- 2 files changed, 105 insertions(+), 5 deletions(-) create mode 100644 samples/openapi3/client/petstore/python-aiohttp/tests/test_rest.py diff --git a/samples/openapi3/client/petstore/python-aiohttp/tests/test_rest.py b/samples/openapi3/client/petstore/python-aiohttp/tests/test_rest.py new file mode 100644 index 000000000000..da11601c70a4 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/tests/test_rest.py @@ -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.api_client = petstore_api.ApiClient() + self.fake_api = petstore_api.FakeApi(self.api_client) + 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): + returned = await self.fake_api.test_object_for_multipart_requests( + marker=marker + ) + assert returned is None + + 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 + ): + returned = await self.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 diff --git a/samples/openapi3/client/petstore/python/tests/test_rest.py b/samples/openapi3/client/petstore/python/tests/test_rest.py index 4c69b5d72a53..b4f3669a2429 100644 --- a/samples/openapi3/client/petstore/python/tests/test_rest.py +++ b/samples/openapi3/client/petstore/python/tests/test_rest.py @@ -1,4 +1,5 @@ import json +import os import unittest from unittest.mock import patch, Mock @@ -8,9 +9,15 @@ class TestMultipleResponseTypes(unittest.TestCase): + 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, "pix.gif") + def setUp(self): self.api_client = petstore_api.ApiClient() self.fake_api = petstore_api.FakeApi(self.api_client) + self.setUpFiles() def test_multipart_requests(self): mock_resp = Mock() @@ -22,10 +29,29 @@ def test_multipart_requests(self): name="name", ) - with patch( - "urllib3.PoolManager.urlopen", return_value=mock_resp + with patch("urllib3.PoolManager.urlopen", return_value=mock_resp): + returned = self.fake_api.test_object_for_multipart_requests(marker=marker) + assert returned is None + + def test_multipart_requests_with_file_and_additional_properties(self): + mock_resp = Mock() + mock_resp.status = 200 + mock_resp.data = b'{"code": 200, "type": "success", "message": "OK"}' + mock_resp.getheader.return_value = "application/json" + mock_resp.getheaders.return_value = {"Content-Type": "application/json"} + with open(self.test_file_path, "rb") as f, patch( + "petstore_api.rest.RESTClientObject.request", return_value=mock_resp ): - returned = self.fake_api.test_object_for_multipart_requests( - marker=marker + returned = self.fake_api.upload_file_with_additional_properties( + file=(self.test_file_path, f.read()), + count=100, + object=petstore_api.UploadFileWithAdditionalPropertiesRequestObject( + name="foo" + ), ) - assert returned is None \ No newline at end of file + + assert ( + returned.code == 200 + and returned.type == "success" + and returned.message == "OK" + ) From c3371355742437ab9d0107d64c76bfb142ba96cc Mon Sep 17 00:00:00 2001 From: Rory Schadler <48921090+roryschadler@users.noreply.github.com> Date: Thu, 22 Aug 2024 22:52:07 -0400 Subject: [PATCH 05/10] fix: mypy tweak --- .../client/petstore/python-aiohttp/tests/test_rest.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/samples/openapi3/client/petstore/python-aiohttp/tests/test_rest.py b/samples/openapi3/client/petstore/python-aiohttp/tests/test_rest.py index da11601c70a4..431cdd0a54b1 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/tests/test_rest.py +++ b/samples/openapi3/client/petstore/python-aiohttp/tests/test_rest.py @@ -32,10 +32,9 @@ async def test_multipart_requests(self): ) with patch("aiohttp.ClientSession.request", mock_resp): - returned = await self.fake_api.test_object_for_multipart_requests( - marker=marker - ) - assert returned is None + await self.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() From d924de201d07d9743bb70691890140eead21879b Mon Sep 17 00:00:00 2001 From: Rory Schadler <48921090+roryschadler@users.noreply.github.com> Date: Fri, 23 Aug 2024 08:49:30 -0400 Subject: [PATCH 06/10] fix: FILES regeneration --- .../client/petstore/python-aiohttp/.openapi-generator/FILES | 1 - .../petstore/python-pydantic-v1-aiohttp/.openapi-generator/FILES | 1 - .../client/petstore/python-pydantic-v1/.openapi-generator/FILES | 1 - samples/openapi3/client/petstore/python/.openapi-generator/FILES | 1 - 4 files changed, 4 deletions(-) diff --git a/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/FILES b/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/FILES index e135e1a2a180..8558e1d2f58a 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/FILES @@ -246,5 +246,4 @@ setup.cfg setup.py test-requirements.txt test/__init__.py -test/test_upload_file_with_additional_properties_request_object.py tox.ini diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/.openapi-generator/FILES b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/.openapi-generator/FILES index 0f579290c2f9..cafa99c6a715 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/.openapi-generator/FILES @@ -246,5 +246,4 @@ setup.cfg setup.py test-requirements.txt test/__init__.py -test/test_upload_file_with_additional_properties_request_object.py tox.ini diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/.openapi-generator/FILES b/samples/openapi3/client/petstore/python-pydantic-v1/.openapi-generator/FILES index 0f579290c2f9..cafa99c6a715 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python-pydantic-v1/.openapi-generator/FILES @@ -246,5 +246,4 @@ setup.cfg setup.py test-requirements.txt test/__init__.py -test/test_upload_file_with_additional_properties_request_object.py tox.ini diff --git a/samples/openapi3/client/petstore/python/.openapi-generator/FILES b/samples/openapi3/client/petstore/python/.openapi-generator/FILES index e135e1a2a180..8558e1d2f58a 100755 --- a/samples/openapi3/client/petstore/python/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python/.openapi-generator/FILES @@ -246,5 +246,4 @@ setup.cfg setup.py test-requirements.txt test/__init__.py -test/test_upload_file_with_additional_properties_request_object.py tox.ini From bbfd186fbfbef680d2ecda2e75a76208be5027fc Mon Sep 17 00:00:00 2001 From: Rory Schadler <48921090+roryschadler@users.noreply.github.com> Date: Tue, 27 Aug 2024 11:27:14 -0400 Subject: [PATCH 07/10] feat: object, int serialization for multipart reqs Extends previous commits (and #18140) to cover the python-pydantic-v1 client as well. --- .../main/resources/python-pydantic-v1/asyncio/rest.mustache | 5 +++++ .../src/main/resources/python-pydantic-v1/rest.mustache | 2 ++ .../echo_api/python-pydantic-v1/openapi_client/rest.py | 2 ++ .../petstore/python-pydantic-v1-aiohttp/petstore_api/rest.py | 5 +++++ .../client/petstore/python-pydantic-v1/petstore_api/rest.py | 2 ++ 5 files changed, 16 insertions(+) diff --git a/modules/openapi-generator/src/main/resources/python-pydantic-v1/asyncio/rest.mustache b/modules/openapi-generator/src/main/resources/python-pydantic-v1/asyncio/rest.mustache index c97788d0c5cc..9be766ce5771 100644 --- a/modules/openapi-generator/src/main/resources/python-pydantic-v1/asyncio/rest.mustache +++ b/modules/openapi-generator/src/main/resources/python-pydantic-v1/asyncio/rest.mustache @@ -143,6 +143,11 @@ class RESTClientObject: filename=v[0], 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 diff --git a/modules/openapi-generator/src/main/resources/python-pydantic-v1/rest.mustache b/modules/openapi-generator/src/main/resources/python-pydantic-v1/rest.mustache index 1d6d255d2cd5..845324e199b8 100644 --- a/modules/openapi-generator/src/main/resources/python-pydantic-v1/rest.mustache +++ b/modules/openapi-generator/src/main/resources/python-pydantic-v1/rest.mustache @@ -190,6 +190,8 @@ class RESTClientObject: # Content-Type which generated by urllib3 will be # overwritten. del headers['Content-Type'] + # Ensures that dict objects are serialized + post_params = [(a, json.dumps(b)) if isinstance(b, dict) else (a,b) for a, b in post_params] r = self.pool_manager.request( method, url, fields=post_params, diff --git a/samples/client/echo_api/python-pydantic-v1/openapi_client/rest.py b/samples/client/echo_api/python-pydantic-v1/openapi_client/rest.py index f4a710085985..8538f9ee5200 100644 --- a/samples/client/echo_api/python-pydantic-v1/openapi_client/rest.py +++ b/samples/client/echo_api/python-pydantic-v1/openapi_client/rest.py @@ -201,6 +201,8 @@ def request(self, method, url, query_params=None, headers=None, # Content-Type which generated by urllib3 will be # overwritten. del headers['Content-Type'] + # Ensures that dict objects are serialized + post_params = [(a, json.dumps(b)) if isinstance(b, dict) else (a,b) for a, b in post_params] r = self.pool_manager.request( method, url, fields=post_params, diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/rest.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/rest.py index 7daf8c921c84..c71fbc6dea92 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/rest.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/rest.py @@ -153,6 +153,11 @@ async def request(self, method, url, query_params=None, headers=None, filename=v[0], 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 diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/rest.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/rest.py index fcbbdab49ab9..a4a233273c5e 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/rest.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/rest.py @@ -200,6 +200,8 @@ def request(self, method, url, query_params=None, headers=None, # Content-Type which generated by urllib3 will be # overwritten. del headers['Content-Type'] + # Ensures that dict objects are serialized + post_params = [(a, json.dumps(b)) if isinstance(b, dict) else (a,b) for a, b in post_params] r = self.pool_manager.request( method, url, fields=post_params, From ededfd57b3cfb092a400d20afdaf32c195d2c965 Mon Sep 17 00:00:00 2001 From: Rory Schadler <48921090+roryschadler@users.noreply.github.com> Date: Tue, 27 Aug 2024 11:28:26 -0400 Subject: [PATCH 08/10] fix: use async with in test --- .../python-aiohttp/tests/test_rest.py | 23 ++++++++++--------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/samples/openapi3/client/petstore/python-aiohttp/tests/test_rest.py b/samples/openapi3/client/petstore/python-aiohttp/tests/test_rest.py index 431cdd0a54b1..8de3969aa065 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/tests/test_rest.py +++ b/samples/openapi3/client/petstore/python-aiohttp/tests/test_rest.py @@ -2,7 +2,6 @@ import unittest from unittest.mock import AsyncMock, Mock, patch - import petstore_api @@ -17,8 +16,6 @@ def setUpFiles(self): self.test_file_path = os.path.join(self.test_file_dir, "foo.png") def setUp(self): - self.api_client = petstore_api.ApiClient() - self.fake_api = petstore_api.FakeApi(self.api_client) self.setUpFiles() async def test_multipart_requests(self): @@ -32,7 +29,9 @@ async def test_multipart_requests(self): ) with patch("aiohttp.ClientSession.request", mock_resp): - await self.fake_api.test_object_for_multipart_requests(marker=marker) + 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 @@ -48,13 +47,15 @@ async def test_multipart_requests_with_file_and_additional_properties(self): with open(self.test_file_path, "rb") as f, patch( "aiohttp.ClientSession.request", mock_request ): - returned = await self.fake_api.upload_file_with_additional_properties( - file=(self.test_file_path, f.read()), - count=100, - object=petstore_api.UploadFileWithAdditionalPropertiesRequestObject( - name="foo" - ), - ) + 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 From c2e4acf6534a722a5674179153b7d33c4c53183d Mon Sep 17 00:00:00 2001 From: Rory Schadler <48921090+roryschadler@users.noreply.github.com> Date: Tue, 27 Aug 2024 11:28:47 -0400 Subject: [PATCH 09/10] test: regression test for pydantic-v1-aiohttp --- .../tests/test_rest.py | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/tests/test_rest.py diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/tests/test_rest.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/tests/test_rest.py new file mode 100644 index 000000000000..7503fe1bc306 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/tests/test_rest.py @@ -0,0 +1,75 @@ +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 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, + count=100, + object=petstore_api.UploadFileWithAdditionalPropertiesRequestObject( + name="foo" + ), + ) + + # response shape is actually petstore_api.models.api_response.ApiResponse, + # but return type is annotated petstore_api.api_response.ApiResponse, thus + # the type: ignores + assert ( + returned.code == 200 # type: ignore + and returned.type == "success" # type: ignore + and returned.message == "OK" # type: ignore + ) + + 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 From 03f9810884f0226dd14f36257bef270e34e8e645 Mon Sep 17 00:00:00 2001 From: Rory Schadler <48921090+roryschadler@users.noreply.github.com> Date: Tue, 27 Aug 2024 11:31:31 -0400 Subject: [PATCH 10/10] test: add regression test to pydantic-v1 Also brings the second test in line with the first, patching `urllib3.PoolManager.urlopen` --- .../python-pydantic-v1/tests/test_rest.py | 57 +++++++++++++++++++ .../client/petstore/python/tests/test_rest.py | 13 ++--- 2 files changed, 63 insertions(+), 7 deletions(-) create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1/tests/test_rest.py diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/tests/test_rest.py b/samples/openapi3/client/petstore/python-pydantic-v1/tests/test_rest.py new file mode 100644 index 000000000000..d655f7da1f9c --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/tests/test_rest.py @@ -0,0 +1,57 @@ +import os +import unittest +from unittest.mock import Mock, patch + +import petstore_api + + +class TestMultipleResponseTypes(unittest.TestCase): + 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, "pix.gif") + + def setUp(self): + self.api_client = petstore_api.ApiClient() + self.fake_api = petstore_api.FakeApi(self.api_client) + self.setUpFiles() + + def test_multipart_requests(self): + mock_resp = Mock() + mock_resp.status = 200 + mock_resp.data = b"some text" + mock_resp.headers = {} + + marker = petstore_api.TestObjectForMultipartRequestsRequestMarker( + name="name", + ) + + with patch("urllib3.PoolManager.urlopen", return_value=mock_resp): + returned = self.fake_api.test_object_for_multipart_requests(marker=marker) + assert returned is None + + def test_multipart_requests_with_file_and_additional_properties(self): + mock_resp = Mock() + mock_resp.status = 200 + mock_resp.data = b'{"code": 200, "type": "success", "message": "OK"}' + mock_resp.headers = {"Content-Type": "application/json"} + with patch("urllib3.PoolManager.urlopen", return_value=mock_resp): + returned = self.fake_api.upload_file_with_additional_properties( + file=self.test_file_path, + count=100, + object=petstore_api.UploadFileWithAdditionalPropertiesRequestObject( + name="foo" + ), + ) + + # response shape is actually petstore_api.models.api_response.ApiResponse, + # but return type is annotated petstore_api.api_response.ApiResponse, thus + # the type: ignores + assert ( + returned.code == 200 # type: ignore + and returned.type == "success" # type: ignore + and returned.message == "OK" # type: ignore + ) + + # if the request is successful, both int and dict body parameters were + # successfully serialized diff --git a/samples/openapi3/client/petstore/python/tests/test_rest.py b/samples/openapi3/client/petstore/python/tests/test_rest.py index b4f3669a2429..47989845e356 100644 --- a/samples/openapi3/client/petstore/python/tests/test_rest.py +++ b/samples/openapi3/client/petstore/python/tests/test_rest.py @@ -1,9 +1,6 @@ -import json import os import unittest -from unittest.mock import patch, Mock - -import pytest +from unittest.mock import Mock, patch import petstore_api @@ -37,10 +34,9 @@ def test_multipart_requests_with_file_and_additional_properties(self): mock_resp = Mock() mock_resp.status = 200 mock_resp.data = b'{"code": 200, "type": "success", "message": "OK"}' - mock_resp.getheader.return_value = "application/json" - mock_resp.getheaders.return_value = {"Content-Type": "application/json"} + mock_resp.headers = {"Content-Type": "application/json"} with open(self.test_file_path, "rb") as f, patch( - "petstore_api.rest.RESTClientObject.request", return_value=mock_resp + "urllib3.PoolManager.urlopen", return_value=mock_resp ): returned = self.fake_api.upload_file_with_additional_properties( file=(self.test_file_path, f.read()), @@ -55,3 +51,6 @@ def test_multipart_requests_with_file_and_additional_properties(self): and returned.type == "success" and returned.message == "OK" ) + + # if the request is successful, both int and dict body parameters were + # successfully serialized