From 59f672d9aa05005c4c3568535c39cd7a27daa4b2 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Tue, 30 Jan 2024 21:11:25 +0800 Subject: [PATCH 01/10] Add rule to remove x-internal in openapi normalizer (#17734) * add rule to remove x-internal in normalizer * update * update doc * better code format * update samples --- docs/customization.md | 6 + .../openapitools/codegen/DefaultCodegen.java | 45 +++---- .../codegen/DefaultGenerator.java | 40 +++--- .../codegen/OpenAPINormalizer.java | 40 +++++- .../codegen/OpenAPINormalizerTest.java | 24 +++- ...nableKeepOnlyFirstTagInOperation_test.yaml | 8 ++ .../petstore/java/okhttp-gson/README.md | 1 - .../java/okhttp-gson/docs/ValuesApi.md | 60 --------- .../openapitools/client/api/ValuesApi.java | 117 ------------------ 9 files changed, 118 insertions(+), 223 deletions(-) diff --git a/docs/customization.md b/docs/customization.md index ade155b1ba11..6b00ae907d52 100644 --- a/docs/customization.md +++ b/docs/customization.md @@ -571,3 +571,9 @@ Example: java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generate -g java -i modules/openapi-generator/src/test/resources/3_0/allOf_extension_parent.yaml -o /tmp/java-okhttp/ --openapi-normalizer REFACTOR_ALLOF_WITH_PROPERTIES_ONLY=true ``` +- `REMOVE_X_INTERNAL`: When set to true, remove `x-internal` extension from operations and models. + +Example: +``` +java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generate -g java -i modules/openapi-generator/src/test/resources/3_0/enableKeepOnlyFirstTagInOperation_test.yaml -o /tmp/java-okhttp/ --openapi-normalizer REMOVE_X_INTERNAL=true +``` diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java index 6b687f96e18c..2f2fdb16183f 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java @@ -4507,11 +4507,6 @@ public CodegenOperation fromOperation(String path, if (operation == null) throw new RuntimeException("operation cannot be null in fromOperation"); - if (operation.getExtensions() != null && Boolean.TRUE.equals(operation.getExtensions().get("x-internal"))) { - LOGGER.info("Operation ({} {} - {}) not generated since x-internal is set to true", - httpMethod, path, operation.getOperationId()); - } - Map schemas = ModelUtils.getSchemas(this.openAPI); CodegenOperation op = CodegenModelFactory.newInstance(CodegenModelType.OPERATION); Set imports = new HashSet<>(); @@ -5083,25 +5078,31 @@ public CodegenCallback fromCallback(String name, Callback callback, List String method = p.getKey(); Operation op = p.getValue(); - boolean genId = op.getOperationId() == null; - if (genId) { - op.setOperationId(getOrGenerateOperationId(op, c.name + "_" + expression.replaceAll("\\{\\$.*}", ""), method)); - } + if (op.getExtensions() != null && Boolean.TRUE.equals(op.getExtensions().get("x-internal"))) { + // skip operation if x-internal sets to true + LOGGER.info("Operation ({} {} - {}) not generated since x-internal is set to true", + method, expression, op.getOperationId()); + } else { + boolean genId = op.getOperationId() == null; + if (genId) { + op.setOperationId(getOrGenerateOperationId(op, c.name + "_" + expression.replaceAll("\\{\\$.*}", ""), method)); + } - if (op.getExtensions() == null) { - op.setExtensions(new HashMap<>()); - } - // This extension will be removed later by `fromOperation()` as it is only needed here to - // distinguish between normal operations and callback requests - op.getExtensions().put("x-callback-request", true); - - CodegenOperation co = fromOperation(expression, method, op, servers); - if (genId) { - co.operationIdOriginal = null; - // legacy (see `fromOperation()`) - co.nickname = co.operationId; + if (op.getExtensions() == null) { + op.setExtensions(new HashMap<>()); + } + // This extension will be removed later by `fromOperation()` as it is only needed here to + // distinguish between normal operations and callback requests + op.getExtensions().put("x-callback-request", true); + + CodegenOperation co = fromOperation(expression, method, op, servers); + if (genId) { + co.operationIdOriginal = null; + // legacy (see `fromOperation()`) + co.nickname = co.operationId; + } + u.requests.add(co); } - u.requests.add(co); }); c.urls.add(u); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java index 32e9ac61050b..071f755d374b 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java @@ -1492,31 +1492,36 @@ private void processOperation(String resourcePath, String httpMethod, Operation final List globalSecurities = openAPI.getSecurity(); for (Tag tag : tags) { try { - CodegenOperation codegenOperation = config.fromOperation(resourcePath, httpMethod, operation, path.getServers()); - codegenOperation.tags = new ArrayList<>(tags); - config.addOperationToGroup(config.sanitizeTag(tag.getName()), resourcePath, operation, codegenOperation, operations); - - List securities = operation.getSecurity(); - if (securities != null && securities.isEmpty()) { - continue; - } + if (operation.getExtensions() != null && Boolean.TRUE.equals(operation.getExtensions().get("x-internal"))) { + // skip operation if x-internal sets to true + LOGGER.info("Operation ({} {} - {}) not generated since x-internal is set to true", + httpMethod, resourcePath, operation.getOperationId()); + } else { + CodegenOperation codegenOperation = config.fromOperation(resourcePath, httpMethod, operation, path.getServers()); + codegenOperation.tags = new ArrayList<>(tags); + config.addOperationToGroup(config.sanitizeTag(tag.getName()), resourcePath, operation, codegenOperation, operations); - Map authMethods = getAuthMethods(securities, securitySchemes); + List securities = operation.getSecurity(); + if (securities != null && securities.isEmpty()) { + continue; + } - if (authMethods != null && !authMethods.isEmpty()) { - List fullAuthMethods = config.fromSecurity(authMethods); - codegenOperation.authMethods = filterAuthMethods(fullAuthMethods, securities); - codegenOperation.hasAuthMethods = true; - } else { - authMethods = getAuthMethods(globalSecurities, securitySchemes); + Map authMethods = getAuthMethods(securities, securitySchemes); if (authMethods != null && !authMethods.isEmpty()) { List fullAuthMethods = config.fromSecurity(authMethods); - codegenOperation.authMethods = filterAuthMethods(fullAuthMethods, globalSecurities); + codegenOperation.authMethods = filterAuthMethods(fullAuthMethods, securities); codegenOperation.hasAuthMethods = true; + } else { + authMethods = getAuthMethods(globalSecurities, securitySchemes); + + if (authMethods != null && !authMethods.isEmpty()) { + List fullAuthMethods = config.fromSecurity(authMethods); + codegenOperation.authMethods = filterAuthMethods(fullAuthMethods, globalSecurities); + codegenOperation.hasAuthMethods = true; + } } } - } catch (Exception ex) { String msg = "Could not process operation:\n" // + " Tag: " + tag + "\n"// @@ -1527,7 +1532,6 @@ private void processOperation(String resourcePath, String httpMethod, Operation throw new RuntimeException(msg, ex); } } - } private static String generateParameterId(Parameter parameter) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java index f17a36c3d031..61ea6c2f73eb 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java @@ -96,6 +96,11 @@ public class OpenAPINormalizer { // when set to true, normalize OpenAPI 3.1 spec to make it work with the generator final String NORMALIZE_31SPEC = "NORMALIZE_31SPEC"; + // when set to true, remove x-internal: true from models, operations + final String REMOVE_X_INTERNAL = "REMOVE_X_INTERNAL"; + final String X_INTERNAL = "x-internal"; + boolean removeXInternal; + // ============= end of rules ============= /** @@ -125,6 +130,7 @@ public OpenAPINormalizer(OpenAPI openAPI, Map inputRules) { ruleNames.add(ADD_UNSIGNED_TO_INTEGER_WITH_INVALID_MAX_VALUE); ruleNames.add(REFACTOR_ALLOF_WITH_PROPERTIES_ONLY); ruleNames.add(NORMALIZE_31SPEC); + ruleNames.add(REMOVE_X_INTERNAL); // rules that are default to true rules.put(SIMPLIFY_ONEOF_ANYOF, true); @@ -224,7 +230,6 @@ private void normalizePaths() { normalizeParameters(path.getParameters()); for (Operation operation : operations) { - normalizeOperation(operation); normalizeRequestBody(operation); normalizeParameters(operation.getParameters()); @@ -239,6 +244,8 @@ private void normalizePaths() { * @param operation Operation */ private void normalizeOperation(Operation operation) { + processRemoveXInternalFromOperation(operation); + processKeepOnlyFirstTagInOperation(operation); processSetTagsForAllOperations(operation); @@ -372,8 +379,15 @@ private void normalizeComponentsSchemas() { if (schema == null) { LOGGER.warn("{} not fount found in openapi/components/schemas.", schemaName); } else { - Schema result = normalizeSchema(schema, new HashSet<>()); - schemas.put(schemaName, result); + // remove x-internal if needed + if (schema.getExtensions() != null && getRule(REMOVE_X_INTERNAL)) { + if (Boolean.parseBoolean(String.valueOf(schema.getExtensions().get(X_INTERNAL)))) { + schema.getExtensions().remove(X_INTERNAL); + } + } + + // normalize the schemas + schemas.put(schemaName, normalizeSchema(schema, new HashSet<>())); } } } @@ -605,6 +619,26 @@ private void processUseAllOfRefAsParent(Schema schema) { } } + /** + * Keep only first tag in the operation if the operation has more than + * one tag. + * + * @param operation Operation + */ + private void processRemoveXInternalFromOperation(Operation operation) { + if (!getRule(REMOVE_X_INTERNAL)) { + return; + } + + if (operation.getExtensions() == null) { + return; + } + + if (Boolean.parseBoolean(String.valueOf(operation.getExtensions().get("x-internal")))) { + operation.getExtensions().remove(X_INTERNAL); + } + } + /** * Keep only first tag in the operation if the operation has more than * one tag. diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/OpenAPINormalizerTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/OpenAPINormalizerTest.java index eb3de1a6a263..2c43e697c626 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/OpenAPINormalizerTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/OpenAPINormalizerTest.java @@ -400,7 +400,7 @@ public void testNormalize31Schema() { Schema pet = openAPI.getComponents().getSchemas().get("Pet"); // verify schema for property id - Schema petSchema = (Schema)pet.getProperties().get("id"); + Schema petSchema = (Schema) pet.getProperties().get("id"); // both type and types are defined assertNotNull(petSchema.getType()); assertNotNull(petSchema.getTypes()); @@ -429,4 +429,24 @@ public void testNormalize31Parameters() { assertNotNull(pathItem.getDelete().getParameters().get(0).getSchema().getType()); assertNotNull(pathItem.getDelete().getParameters().get(0).getSchema().getTypes()); } -} + + @Test + public void testRemoveXInternal() { + OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/3_0/enableKeepOnlyFirstTagInOperation_test.yaml"); + Schema s = openAPI.getComponents().getSchemas().get("Dummy"); + + assertEquals(openAPI.getPaths().get("/person/display/{personId}").getGet().getExtensions(), null); + assertEquals(openAPI.getPaths().get("/person/display/{personId}").getDelete().getExtensions().get("x-internal"), true); + assertEquals(s.getExtensions().get("x-internal"), true); + + Map options = new HashMap<>(); + options.put("REMOVE_X_INTERNAL", "true"); + OpenAPINormalizer openAPINormalizer = new OpenAPINormalizer(openAPI, options); + openAPINormalizer.normalize(); + + Schema s2 = openAPI.getComponents().getSchemas().get("Dummy"); + assertEquals(openAPI.getPaths().get("/person/display/{personId}").getGet().getExtensions(), null); + assertEquals(openAPI.getPaths().get("/person/display/{personId}").getDelete().getExtensions().get("x-internal"), null); + assertEquals(s2.getExtensions().get("x-internal"), null); + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/enableKeepOnlyFirstTagInOperation_test.yaml b/modules/openapi-generator/src/test/resources/3_0/enableKeepOnlyFirstTagInOperation_test.yaml index 02c9017e6282..8b99e18d3ba1 100644 --- a/modules/openapi-generator/src/test/resources/3_0/enableKeepOnlyFirstTagInOperation_test.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/enableKeepOnlyFirstTagInOperation_test.yaml @@ -30,6 +30,7 @@ paths: delete: tags: - person + x-internal: true parameters: - name: personId in: path @@ -57,3 +58,10 @@ components: type: string firstName: type: string + Dummy: + x-internal: true + description: to test x-internal + type: object + properties: + test: + type: string \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson/README.md b/samples/client/petstore/java/okhttp-gson/README.md index d4a7bc52e89a..f3ed707b0116 100644 --- a/samples/client/petstore/java/okhttp-gson/README.md +++ b/samples/client/petstore/java/okhttp-gson/README.md @@ -160,7 +160,6 @@ Class | Method | HTTP request | Description *UserApi* | [**logoutUser**](docs/UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session *UserApi* | [**updateUser**](docs/UserApi.md#updateUser) | **PUT** /user/{username} | Updated user *ValuesApi* | [**getSomeValues**](docs/ValuesApi.md#getSomeValues) | **GET** /values | Get some primitive variable values -*ValuesApi* | [**internalOnlyGet**](docs/ValuesApi.md#internalOnlyGet) | **GET** /internal/only | internal only ## Documentation for Models diff --git a/samples/client/petstore/java/okhttp-gson/docs/ValuesApi.md b/samples/client/petstore/java/okhttp-gson/docs/ValuesApi.md index a607e93df06e..4210bff03ec9 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/ValuesApi.md +++ b/samples/client/petstore/java/okhttp-gson/docs/ValuesApi.md @@ -5,7 +5,6 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | Method | HTTP request | Description | |------------- | ------------- | -------------| | [**getSomeValues**](ValuesApi.md#getSomeValues) | **GET** /values | Get some primitive variable values | -| [**internalOnlyGet**](ValuesApi.md#internalOnlyGet) | **GET** /internal/only | internal only | @@ -67,62 +66,3 @@ No authorization required | **200** | successful operation | - | | **400** | Invalid Value | - | - -# **internalOnlyGet** -> Variable internalOnlyGet() - -internal only - - - -### Example -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.ValuesApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - ValuesApi apiInstance = new ValuesApi(defaultClient); - try { - Variable result = apiInstance.internalOnlyGet(); - System.out.println(result); - } catch (ApiException e) { - System.err.println("Exception when calling ValuesApi#internalOnlyGet"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters -This endpoint does not need any parameter. - -### Return type - -[**Variable**](Variable.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | -| **400** | Invalid Value | - | - diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/ValuesApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/ValuesApi.java index 327ccfafe4c1..79fe043970d5 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/ValuesApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/ValuesApi.java @@ -189,121 +189,4 @@ public okhttp3.Call getSomeValuesAsync(final ApiCallback _callback) th localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } - /** - * Build call for internalOnlyGet - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - - -
Status Code Description Response Headers
200 successful operation -
400 Invalid Value -
- */ - public okhttp3.Call internalOnlyGetCall(final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/internal/only"; - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call internalOnlyGetValidateBeforeCall(final ApiCallback _callback) throws ApiException { - return internalOnlyGetCall(_callback); - - } - - /** - * internal only - * - * @return Variable - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - -
Status Code Description Response Headers
200 successful operation -
400 Invalid Value -
- */ - public Variable internalOnlyGet() throws ApiException { - ApiResponse localVarResp = internalOnlyGetWithHttpInfo(); - return localVarResp.getData(); - } - - /** - * internal only - * - * @return ApiResponse<Variable> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - -
Status Code Description Response Headers
200 successful operation -
400 Invalid Value -
- */ - public ApiResponse internalOnlyGetWithHttpInfo() throws ApiException { - okhttp3.Call localVarCall = internalOnlyGetValidateBeforeCall(null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * internal only (asynchronously) - * - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - - -
Status Code Description Response Headers
200 successful operation -
400 Invalid Value -
- */ - public okhttp3.Call internalOnlyGetAsync(final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = internalOnlyGetValidateBeforeCall(_callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } } From ef5958928733f4d398c17274fcf5048ec53d261d Mon Sep 17 00:00:00 2001 From: William Cheng Date: Wed, 31 Jan 2024 10:38:59 +0800 Subject: [PATCH 02/10] update samples --- samples/client/petstore/perl/README.md | 1 - samples/client/petstore/perl/docs/FakeApi.md | 46 -------------- .../perl/lib/WWW/OpenAPIClient/FakeApi.pm | 61 ------------------- .../builds/test-petstore/api.ts | 6 +- .../api.ts | 6 +- .../mockserver/api/FakeApiMockServer.java | 28 +++++++++ 6 files changed, 34 insertions(+), 114 deletions(-) diff --git a/samples/client/petstore/perl/README.md b/samples/client/petstore/perl/README.md index 7f6153b054df..3443b82fdee4 100644 --- a/samples/client/petstore/perl/README.md +++ b/samples/client/petstore/perl/README.md @@ -419,7 +419,6 @@ Class | Method | HTTP request | Description *FakeApi* | [**test_json_form_data**](docs/FakeApi.md#test_json_form_data) | **GET** /fake/jsonFormData | test json serialization of form data *FakeApi* | [**test_nullable**](docs/FakeApi.md#test_nullable) | **POST** /fake/nullable | test nullable parent property *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 *FakeClassnameTags123Api* | [**test_classname**](docs/FakeClassnameTags123Api.md#test_classname) | **PATCH** /fake_classname_test | To test class name in snake case *PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store *PetApi* | [**delete_pet**](docs/PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet diff --git a/samples/client/petstore/perl/docs/FakeApi.md b/samples/client/petstore/perl/docs/FakeApi.md index 498e93cced7b..440d7f0e5506 100644 --- a/samples/client/petstore/perl/docs/FakeApi.md +++ b/samples/client/petstore/perl/docs/FakeApi.md @@ -30,7 +30,6 @@ Method | HTTP request | Description [**test_json_form_data**](FakeApi.md#test_json_form_data) | **GET** /fake/jsonFormData | test json serialization of form data [**test_nullable**](FakeApi.md#test_nullable) | **POST** /fake/nullable | test nullable parent property [**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 # **fake_big_decimal_map** @@ -1055,48 +1054,3 @@ 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) -# **test_string_map_reference** -> test_string_map_reference(request_body => $request_body) - -test referenced string map - - - -### Example -```perl -use Data::Dumper; -use WWW::OpenAPIClient::FakeApi; -my $api_instance = WWW::OpenAPIClient::FakeApi->new( -); - -my $request_body = WWW::OpenAPIClient::Object::HASH[string,string]->new(); # HASH[string,string] | request body - -eval { - $api_instance->test_string_map_reference(request_body => $request_body); -}; -if ($@) { - warn "Exception when calling FakeApi->test_string_map_reference: $@\n"; -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **request_body** | [**HASH[string,string]**](string.md)| request body | - -### Return type - -void (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: Not defined - -[[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/client/petstore/perl/lib/WWW/OpenAPIClient/FakeApi.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/FakeApi.pm index 1838f4d84597..d2a79db97cf4 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/FakeApi.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/FakeApi.pm @@ -1756,65 +1756,4 @@ sub test_query_parameter_collection_format { return; } -# -# test_string_map_reference -# -# test referenced string map -# -# @param HASH[string,string] $request_body request body (required) -{ - my $params = { - 'request_body' => { - data_type => 'HASH[string,string]', - description => 'request body', - required => '1', - }, - }; - __PACKAGE__->method_documentation->{ 'test_string_map_reference' } = { - summary => 'test referenced string map', - params => $params, - returns => undef, - }; -} -# @return void -# -sub test_string_map_reference { - my ($self, %args) = @_; - - # verify the required parameter 'request_body' is set - unless (exists $args{'request_body'}) { - croak("Missing the required parameter 'request_body' when calling test_string_map_reference"); - } - - # parse inputs - my $_resource_path = '/fake/stringMap-reference'; - - my $_method = 'POST'; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept(); - if ($_header_accept) { - $header_params->{'Accept'} = $_header_accept; - } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json'); - - my $_body_data; - # body params - if ( exists $args{'request_body'}) { - $_body_data = $args{'request_body'}; - } - - # authentication setting, if any - my $auth_settings = [qw()]; - - # make the API Call - $self->{api_client}->call_api($_resource_path, $_method, - $query_params, $form_params, - $header_params, $_body_data, $auth_settings); - return; -} - 1; diff --git a/samples/client/petstore/typescript-axios/builds/test-petstore/api.ts b/samples/client/petstore/typescript-axios/builds/test-petstore/api.ts index 2d0cef8918e8..b78f8ad853a8 100644 --- a/samples/client/petstore/typescript-axios/builds/test-petstore/api.ts +++ b/samples/client/petstore/typescript-axios/builds/test-petstore/api.ts @@ -2997,9 +2997,9 @@ export const FakeApiFp = function(configuration?: Configuration) { */ async testStringMapReference(requestBody: { [key: string]: string; }, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.testStringMapReference(requestBody, options); - const index = configuration?.serverIndex ?? 0; - const operationBasePath = operationServerMap['FakeApi.testStringMapReference']?.[index]?.url; - return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); + const localVarOperationServerIndex = configuration?.serverIndex ?? 0; + const localVarOperationServerBasePath = operationServerMap['FakeApi.testStringMapReference']?.[localVarOperationServerIndex]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath); }, } }; diff --git a/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/api.ts b/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/api.ts index e8a38fc993d3..ad31a71f0e3f 100644 --- a/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/api.ts @@ -2653,9 +2653,9 @@ export const FakeApiFp = function(configuration?: Configuration) { */ async testStringMapReference(requestBody: { [key: string]: string; }, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.testStringMapReference(requestBody, options); - const index = configuration?.serverIndex ?? 0; - const operationBasePath = operationServerMap['FakeApi.testStringMapReference']?.[index]?.url; - return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); + const localVarOperationServerIndex = configuration?.serverIndex ?? 0; + const localVarOperationServerBasePath = operationServerMap['FakeApi.testStringMapReference']?.[localVarOperationServerIndex]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath); }, /** * To test unique items in header and query parameters diff --git a/samples/server/petstore/java-wiremock/src/main/java/org/openapitools/mockserver/api/FakeApiMockServer.java b/samples/server/petstore/java-wiremock/src/main/java/org/openapitools/mockserver/api/FakeApiMockServer.java index ceb430dea216..986873635112 100644 --- a/samples/server/petstore/java-wiremock/src/main/java/org/openapitools/mockserver/api/FakeApiMockServer.java +++ b/samples/server/petstore/java-wiremock/src/main/java/org/openapitools/mockserver/api/FakeApiMockServer.java @@ -889,4 +889,32 @@ public static MappingBuilder stubTestQueryParameterCollectionFormatFault(@javax. + public static MappingBuilder stubTestStringMapReference200(@javax.annotation.Nonnull String body) { + MappingBuilder stub = post(urlPathEqualTo("/fake/stringMap-reference")) + .withRequestBody(equalToJson(body)) + .willReturn(aResponse() + .withStatus(200) + ); + + + return stub; + } + + public static MappingBuilder stubTestStringMapReferenceFault(@javax.annotation.Nonnull String body, Fault fault) { + MappingBuilder stub = post(urlPathEqualTo("/fake/stringMap-reference")) + .withRequestBody(equalToJson(body)) + .willReturn(aResponse() + .withFault(fault) + ); + + + return stub; + } + + + public static String testStringMapReferenceRequestSample1() { + return ""; + } + + } From 1146575848ea0ac1fdbe184a14e7e29c733ff453 Mon Sep 17 00:00:00 2001 From: Aron <66121375+aronkankel@users.noreply.github.com> Date: Wed, 31 Jan 2024 03:42:15 +0100 Subject: [PATCH 03/10] corrected handling of "isPrimitiveType" for FormParameters (#17700) * FormParameters correct handling for "isPrimitiveType" https://github.com/OpenAPITools/openapi-generator/issues/17699 * MultipartApi.cs generated with new mustache https://github.com/OpenAPITools/openapi-generator/issues/17699 * FakeApi.cs generated based on new mustache https://github.com/OpenAPITools/openapi-generator/issues/17699 * FakeApi.cs generated based on new mustache https://github.com/OpenAPITools/openapi-generator/issues/17699 * FakeApi.cs generated based on new mustache https://github.com/OpenAPITools/openapi-generator/issues/17699 * FakeApi.cs generated based on new mustache https://github.com/OpenAPITools/openapi-generator/issues/17699 * FakeApi.cs generated based on new mustache https://github.com/OpenAPITools/openapi-generator/issues/17699 * FakeApi.cs generated based on new mustache https://github.com/OpenAPITools/openapi-generator/issues/17699 --- .../src/main/resources/csharp/api.mustache | 6 +++--- .../src/Org.OpenAPITools/Api/MultipartApi.cs | 10 +++++----- .../src/Org.OpenAPITools/Api/FakeApi.cs | 4 ++-- .../src/Org.OpenAPITools/Api/FakeApi.cs | 4 ++-- .../src/Org.OpenAPITools/Api/FakeApi.cs | 4 ++-- .../src/Org.OpenAPITools/Api/FakeApi.cs | 4 ++-- .../OpenAPIClient/src/Org.OpenAPITools/Api/FakeApi.cs | 4 ++-- .../src/Org.OpenAPITools/Api/FakeApi.cs | 4 ++-- 8 files changed, 20 insertions(+), 20 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/csharp/api.mustache b/modules/openapi-generator/src/main/resources/csharp/api.mustache index 63fdd07f19b4..d7e0571ef601 100644 --- a/modules/openapi-generator/src/main/resources/csharp/api.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/api.mustache @@ -397,7 +397,7 @@ namespace {{packageName}}.{{apiPackage}} {{/isArray}} {{/isFile}} {{^isFile}} - localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // form parameter + localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.{{#isPrimitiveType}}ParameterToString{{/isPrimitiveType}}{{^isPrimitiveType}}Serialize{{/isPrimitiveType}}({{paramName}})); // form parameter {{/isFile}} } {{/required}} @@ -647,7 +647,7 @@ namespace {{packageName}}.{{apiPackage}} {{/isArray}} {{/isFile}} {{^isFile}} - localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // form parameter + localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.{{#isPrimitiveType}}ParameterToString{{/isPrimitiveType}}{{^isPrimitiveType}}Serialize{{/isPrimitiveType}}({{paramName}})); // form parameter {{/isFile}} {{/required}} {{^required}} @@ -669,7 +669,7 @@ namespace {{packageName}}.{{apiPackage}} {{/isArray}} {{/isFile}} {{^isFile}} - localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // form parameter + localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.{{#isPrimitiveType}}ParameterToString{{/isPrimitiveType}}{{^isPrimitiveType}}Serialize{{/isPrimitiveType}}({{paramName}})); // form parameter {{/isFile}} } {{/required}} diff --git a/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Api/MultipartApi.cs b/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Api/MultipartApi.cs index b165faa5bd07..b8058401397a 100644 --- a/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Api/MultipartApi.cs +++ b/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Api/MultipartApi.cs @@ -517,12 +517,12 @@ public Org.OpenAPITools.Client.ExceptionFactory ExceptionFactory localVarRequestOptions.FormParameters.Add("status", Org.OpenAPITools.Client.ClientUtils.Serialize(status)); // form parameter if (marker != null) { - localVarRequestOptions.FormParameters.Add("marker", Org.OpenAPITools.Client.ClientUtils.ParameterToString(marker)); // form parameter + localVarRequestOptions.FormParameters.Add("marker", Org.OpenAPITools.Client.ClientUtils.Serialize(marker)); // form parameter } localVarRequestOptions.FileParameters.Add("file", file); if (statusArray != null) { - localVarRequestOptions.FormParameters.Add("statusArray", Org.OpenAPITools.Client.ClientUtils.ParameterToString(statusArray)); // form parameter + localVarRequestOptions.FormParameters.Add("statusArray", Org.OpenAPITools.Client.ClientUtils.Serialize(statusArray)); // form parameter } localVarRequestOptions.Operation = "MultipartApi.MultipartMixed"; @@ -607,15 +607,15 @@ public Org.OpenAPITools.Client.ExceptionFactory ExceptionFactory localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); } - localVarRequestOptions.FormParameters.Add("status", Org.OpenAPITools.Client.ClientUtils.ParameterToString(status)); // form parameter + localVarRequestOptions.FormParameters.Add("status", Org.OpenAPITools.Client.ClientUtils.Serialize(status)); // form parameter if (marker != null) { - localVarRequestOptions.FormParameters.Add("marker", Org.OpenAPITools.Client.ClientUtils.ParameterToString(marker)); // form parameter + localVarRequestOptions.FormParameters.Add("marker", Org.OpenAPITools.Client.ClientUtils.Serialize(marker)); // form parameter } localVarRequestOptions.FileParameters.Add("file", file); if (statusArray != null) { - localVarRequestOptions.FormParameters.Add("statusArray", Org.OpenAPITools.Client.ClientUtils.ParameterToString(statusArray)); // form parameter + localVarRequestOptions.FormParameters.Add("statusArray", Org.OpenAPITools.Client.ClientUtils.Serialize(statusArray)); // form parameter } localVarRequestOptions.Operation = "MultipartApi.MultipartMixed"; diff --git a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/FakeApi.cs index 9d861a2ccf86..bc6276012d1e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/FakeApi.cs @@ -2903,7 +2903,7 @@ public Org.OpenAPITools.Client.ApiResponse TestClientModelWithHttpI } if (enumFormStringArray != null) { - localVarRequestOptions.FormParameters.Add("enum_form_string_array", Org.OpenAPITools.Client.ClientUtils.ParameterToString(enumFormStringArray)); // form parameter + localVarRequestOptions.FormParameters.Add("enum_form_string_array", Org.OpenAPITools.Client.ClientUtils.Serialize(enumFormStringArray)); // form parameter } if (enumFormString != null) { @@ -3014,7 +3014,7 @@ public Org.OpenAPITools.Client.ApiResponse TestClientModelWithHttpI } if (enumFormStringArray != null) { - localVarRequestOptions.FormParameters.Add("enum_form_string_array", Org.OpenAPITools.Client.ClientUtils.ParameterToString(enumFormStringArray)); // form parameter + localVarRequestOptions.FormParameters.Add("enum_form_string_array", Org.OpenAPITools.Client.ClientUtils.Serialize(enumFormStringArray)); // form parameter } if (enumFormString != null) { diff --git a/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Api/FakeApi.cs index 9d861a2ccf86..bc6276012d1e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Api/FakeApi.cs @@ -2903,7 +2903,7 @@ public Org.OpenAPITools.Client.ApiResponse TestClientModelWithHttpI } if (enumFormStringArray != null) { - localVarRequestOptions.FormParameters.Add("enum_form_string_array", Org.OpenAPITools.Client.ClientUtils.ParameterToString(enumFormStringArray)); // form parameter + localVarRequestOptions.FormParameters.Add("enum_form_string_array", Org.OpenAPITools.Client.ClientUtils.Serialize(enumFormStringArray)); // form parameter } if (enumFormString != null) { @@ -3014,7 +3014,7 @@ public Org.OpenAPITools.Client.ApiResponse TestClientModelWithHttpI } if (enumFormStringArray != null) { - localVarRequestOptions.FormParameters.Add("enum_form_string_array", Org.OpenAPITools.Client.ClientUtils.ParameterToString(enumFormStringArray)); // form parameter + localVarRequestOptions.FormParameters.Add("enum_form_string_array", Org.OpenAPITools.Client.ClientUtils.Serialize(enumFormStringArray)); // form parameter } if (enumFormString != null) { diff --git a/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Api/FakeApi.cs index 9d861a2ccf86..bc6276012d1e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Api/FakeApi.cs @@ -2903,7 +2903,7 @@ public Org.OpenAPITools.Client.ApiResponse TestClientModelWithHttpI } if (enumFormStringArray != null) { - localVarRequestOptions.FormParameters.Add("enum_form_string_array", Org.OpenAPITools.Client.ClientUtils.ParameterToString(enumFormStringArray)); // form parameter + localVarRequestOptions.FormParameters.Add("enum_form_string_array", Org.OpenAPITools.Client.ClientUtils.Serialize(enumFormStringArray)); // form parameter } if (enumFormString != null) { @@ -3014,7 +3014,7 @@ public Org.OpenAPITools.Client.ApiResponse TestClientModelWithHttpI } if (enumFormStringArray != null) { - localVarRequestOptions.FormParameters.Add("enum_form_string_array", Org.OpenAPITools.Client.ClientUtils.ParameterToString(enumFormStringArray)); // form parameter + localVarRequestOptions.FormParameters.Add("enum_form_string_array", Org.OpenAPITools.Client.ClientUtils.Serialize(enumFormStringArray)); // form parameter } if (enumFormString != null) { diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/FakeApi.cs index 78a5a735f098..fda76f972ea2 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/FakeApi.cs @@ -2903,7 +2903,7 @@ public Org.OpenAPITools.Client.ApiResponse TestClientModelWithHttpI } if (enumFormStringArray != null) { - localVarRequestOptions.FormParameters.Add("enum_form_string_array", Org.OpenAPITools.Client.ClientUtils.ParameterToString(enumFormStringArray)); // form parameter + localVarRequestOptions.FormParameters.Add("enum_form_string_array", Org.OpenAPITools.Client.ClientUtils.Serialize(enumFormStringArray)); // form parameter } if (enumFormString != null) { @@ -3014,7 +3014,7 @@ public Org.OpenAPITools.Client.ApiResponse TestClientModelWithHttpI } if (enumFormStringArray != null) { - localVarRequestOptions.FormParameters.Add("enum_form_string_array", Org.OpenAPITools.Client.ClientUtils.ParameterToString(enumFormStringArray)); // form parameter + localVarRequestOptions.FormParameters.Add("enum_form_string_array", Org.OpenAPITools.Client.ClientUtils.Serialize(enumFormStringArray)); // form parameter } if (enumFormString != null) { diff --git a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Api/FakeApi.cs index 9d861a2ccf86..bc6276012d1e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Api/FakeApi.cs @@ -2903,7 +2903,7 @@ public Org.OpenAPITools.Client.ApiResponse TestClientModelWithHttpI } if (enumFormStringArray != null) { - localVarRequestOptions.FormParameters.Add("enum_form_string_array", Org.OpenAPITools.Client.ClientUtils.ParameterToString(enumFormStringArray)); // form parameter + localVarRequestOptions.FormParameters.Add("enum_form_string_array", Org.OpenAPITools.Client.ClientUtils.Serialize(enumFormStringArray)); // form parameter } if (enumFormString != null) { @@ -3014,7 +3014,7 @@ public Org.OpenAPITools.Client.ApiResponse TestClientModelWithHttpI } if (enumFormStringArray != null) { - localVarRequestOptions.FormParameters.Add("enum_form_string_array", Org.OpenAPITools.Client.ClientUtils.ParameterToString(enumFormStringArray)); // form parameter + localVarRequestOptions.FormParameters.Add("enum_form_string_array", Org.OpenAPITools.Client.ClientUtils.Serialize(enumFormStringArray)); // form parameter } if (enumFormString != null) { diff --git a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Api/FakeApi.cs index 78a5a735f098..fda76f972ea2 100644 --- a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Api/FakeApi.cs @@ -2903,7 +2903,7 @@ public Org.OpenAPITools.Client.ApiResponse TestClientModelWithHttpI } if (enumFormStringArray != null) { - localVarRequestOptions.FormParameters.Add("enum_form_string_array", Org.OpenAPITools.Client.ClientUtils.ParameterToString(enumFormStringArray)); // form parameter + localVarRequestOptions.FormParameters.Add("enum_form_string_array", Org.OpenAPITools.Client.ClientUtils.Serialize(enumFormStringArray)); // form parameter } if (enumFormString != null) { @@ -3014,7 +3014,7 @@ public Org.OpenAPITools.Client.ApiResponse TestClientModelWithHttpI } if (enumFormStringArray != null) { - localVarRequestOptions.FormParameters.Add("enum_form_string_array", Org.OpenAPITools.Client.ClientUtils.ParameterToString(enumFormStringArray)); // form parameter + localVarRequestOptions.FormParameters.Add("enum_form_string_array", Org.OpenAPITools.Client.ClientUtils.Serialize(enumFormStringArray)); // form parameter } if (enumFormString != null) { From af4800132d78ebfa6b44a75d5d0cf69ac31b59bc Mon Sep 17 00:00:00 2001 From: Charles Treatman Date: Tue, 30 Jan 2024 20:46:14 -0600 Subject: [PATCH 04/10] revert swagger-parser upgrade (#17657) --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index a1f58d95f43f..5673e24132cf 100644 --- a/pom.xml +++ b/pom.xml @@ -1237,7 +1237,7 @@ 1.7.36 3.1.12.2 io.swagger.parser.v3 - 2.1.19 + 2.1.18 7.5 1.34 3.4.3 From 7267e809c32767c17dde3c3eab9aef05a7710f65 Mon Sep 17 00:00:00 2001 From: Sander Hoentjen Date: Wed, 31 Jan 2024 04:03:14 +0100 Subject: [PATCH 05/10] [python-fastapi] Ensure path param is ... instead of None (#17532) Fixes #16029 Code from https://github.com/OpenAPITools/openapi-generator/issues/16029#issuecomment-1776271921 --- .../python-fastapi/endpoint_argument_definition.mustache | 2 +- .../python-fastapi/src/openapi_server/apis/pet_api.py | 8 ++++---- .../python-fastapi/src/openapi_server/apis/store_api.py | 4 ++-- .../python-fastapi/src/openapi_server/apis/user_api.py | 6 +++--- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/endpoint_argument_definition.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/endpoint_argument_definition.mustache index 2b4b6d7c4887..c8887fb64f4e 100644 --- a/modules/openapi-generator/src/main/resources/python-fastapi/endpoint_argument_definition.mustache +++ b/modules/openapi-generator/src/main/resources/python-fastapi/endpoint_argument_definition.mustache @@ -1 +1 @@ -{{#isPathParam}}{{baseName}}{{/isPathParam}}{{^isPathParam}}{{paramName}}{{/isPathParam}}: {{>param_type}} = {{#isPathParam}}Path{{/isPathParam}}{{#isHeaderParam}}Header{{/isHeaderParam}}{{#isFormParam}}Form{{/isFormParam}}{{#isQueryParam}}Query{{/isQueryParam}}{{#isCookieParam}}Cookie{{/isCookieParam}}{{#isBodyParam}}Body{{/isBodyParam}}({{&defaultValue}}{{^defaultValue}}None{{/defaultValue}}, description="{{description}}"{{#isQueryParam}}, alias="{{baseName}}"{{/isQueryParam}}{{#isLong}}{{#minimum}}, ge={{.}}{{/minimum}}{{#maximum}}, le={{.}}{{/maximum}}{{/isLong}}{{#isInteger}}{{#minimum}}, ge={{.}}{{/minimum}}{{#maximum}}, le={{.}}{{/maximum}}{{/isInteger}}{{#pattern}}, regex=r"{{.}}"{{/pattern}}{{#minLength}}, min_length={{.}}{{/minLength}}{{#maxLength}}, max_length={{.}}{{/maxLength}}) \ No newline at end of file +{{#isPathParam}}{{baseName}}{{/isPathParam}}{{^isPathParam}}{{paramName}}{{/isPathParam}}: {{>param_type}} = {{#isPathParam}}Path{{/isPathParam}}{{#isHeaderParam}}Header{{/isHeaderParam}}{{#isFormParam}}Form{{/isFormParam}}{{#isQueryParam}}Query{{/isQueryParam}}{{#isCookieParam}}Cookie{{/isCookieParam}}{{#isBodyParam}}Body{{/isBodyParam}}({{&defaultValue}}{{^defaultValue}}{{#isPathParam}}...{{/isPathParam}}{{^isPathParam}}None{{/isPathParam}}{{/defaultValue}}, description="{{description}}"{{#isQueryParam}}, alias="{{baseName}}"{{/isQueryParam}}{{#isLong}}{{#minimum}}, ge={{.}}{{/minimum}}{{#maximum}}, le={{.}}{{/maximum}}{{/isLong}}{{#isInteger}}{{#minimum}}, ge={{.}}{{/minimum}}{{#maximum}}, le={{.}}{{/maximum}}{{/isInteger}}{{#pattern}}, regex=r"{{.}}"{{/pattern}}{{#minLength}}, min_length={{.}}{{/minLength}}{{#maxLength}}, max_length={{.}}{{/maxLength}}) \ No newline at end of file diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/apis/pet_api.py b/samples/server/petstore/python-fastapi/src/openapi_server/apis/pet_api.py index cf8ada786d1e..1229ceeed197 100644 --- a/samples/server/petstore/python-fastapi/src/openapi_server/apis/pet_api.py +++ b/samples/server/petstore/python-fastapi/src/openapi_server/apis/pet_api.py @@ -63,7 +63,7 @@ async def add_pet( response_model_by_alias=True, ) async def delete_pet( - petId: int = Path(None, description="Pet id to delete"), + petId: int = Path(..., description="Pet id to delete"), api_key: str = Header(None, description=""), token_petstore_auth: TokenModel = Security( get_token_petstore_auth, scopes=["write:pets", "read:pets"] @@ -125,7 +125,7 @@ async def find_pets_by_tags( response_model_by_alias=True, ) async def get_pet_by_id( - petId: int = Path(None, description="ID of pet to return"), + petId: int = Path(..., description="ID of pet to return"), token_api_key: TokenModel = Security( get_token_api_key ), @@ -166,7 +166,7 @@ async def update_pet( response_model_by_alias=True, ) async def update_pet_with_form( - petId: int = Path(None, description="ID of pet that needs to be updated"), + petId: int = Path(..., description="ID of pet that needs to be updated"), name: str = Form(None, description="Updated name of the pet"), status: str = Form(None, description="Updated status of the pet"), token_petstore_auth: TokenModel = Security( @@ -187,7 +187,7 @@ async def update_pet_with_form( response_model_by_alias=True, ) async def upload_file( - petId: int = Path(None, description="ID of pet to update"), + petId: int = Path(..., description="ID of pet to update"), additional_metadata: str = Form(None, description="Additional data to pass to server"), file: str = Form(None, description="file to upload"), token_petstore_auth: TokenModel = Security( diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/apis/store_api.py b/samples/server/petstore/python-fastapi/src/openapi_server/apis/store_api.py index 585a671bbaf4..b583c10a625b 100644 --- a/samples/server/petstore/python-fastapi/src/openapi_server/apis/store_api.py +++ b/samples/server/petstore/python-fastapi/src/openapi_server/apis/store_api.py @@ -43,7 +43,7 @@ response_model_by_alias=True, ) async def delete_order( - orderId: str = Path(None, description="ID of the order that needs to be deleted"), + orderId: str = Path(..., description="ID of the order that needs to be deleted"), ) -> None: """For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors""" return BaseStoreApi.subclasses[0]().delete_order(orderId) @@ -79,7 +79,7 @@ async def get_inventory( response_model_by_alias=True, ) async def get_order_by_id( - orderId: int = Path(None, description="ID of pet that needs to be fetched", ge=1, le=5), + orderId: int = Path(..., description="ID of pet that needs to be fetched", ge=1, le=5), ) -> Order: """For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions""" return BaseStoreApi.subclasses[0]().get_order_by_id(orderId) diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/apis/user_api.py b/samples/server/petstore/python-fastapi/src/openapi_server/apis/user_api.py index e57b899c69b6..1ee291c2a02b 100644 --- a/samples/server/petstore/python-fastapi/src/openapi_server/apis/user_api.py +++ b/samples/server/petstore/python-fastapi/src/openapi_server/apis/user_api.py @@ -100,7 +100,7 @@ async def create_users_with_list_input( response_model_by_alias=True, ) async def delete_user( - username: str = Path(None, description="The name that needs to be deleted"), + username: str = Path(..., description="The name that needs to be deleted"), token_api_key: TokenModel = Security( get_token_api_key ), @@ -121,7 +121,7 @@ async def delete_user( response_model_by_alias=True, ) async def get_user_by_name( - username: str = Path(None, description="The name that needs to be fetched. Use user1 for testing."), + username: str = Path(..., description="The name that needs to be fetched. Use user1 for testing."), ) -> User: """""" return BaseUserApi.subclasses[0]().get_user_by_name(username) @@ -174,7 +174,7 @@ async def logout_user( response_model_by_alias=True, ) async def update_user( - username: str = Path(None, description="name that need to be deleted"), + username: str = Path(..., description="name that need to be deleted"), user: User = Body(None, description="Updated user object"), token_api_key: TokenModel = Security( get_token_api_key From 6ec4ed0b691404db2e6e76e90da0342ac44f3426 Mon Sep 17 00:00:00 2001 From: hopi Date: Wed, 31 Jan 2024 04:05:56 +0100 Subject: [PATCH 06/10] scala-sttp: fix for missing EnumNameSerializer for inner enum definitions (#17697) --- .../src/main/resources/scala-sttp/jsonSupport.mustache | 3 ++- .../scala/org/openapitools/client/core/JsonSupport.scala | 6 +++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/scala-sttp/jsonSupport.mustache b/modules/openapi-generator/src/main/resources/scala-sttp/jsonSupport.mustache index c6d1d06eef52..6a0b9665a096 100644 --- a/modules/openapi-generator/src/main/resources/scala-sttp/jsonSupport.mustache +++ b/modules/openapi-generator/src/main/resources/scala-sttp/jsonSupport.mustache @@ -11,7 +11,8 @@ import scala.reflect.ClassTag object JsonSupport extends SttpJson4sApi { def enumSerializers: Seq[Serializer[_]] = Seq[Serializer[_]](){{#models}}{{#model}}{{#isEnum}} :+ - new EnumNameSerializer({{classname}}){{/isEnum}}{{/model}}{{/models}} + new EnumNameSerializer({{classname}}){{/isEnum}}{{#hasEnums}}{{#vars}}{{#isEnum}} :+ + new EnumNameSerializer({{classname}}Enums.{{datatypeWithEnum}}){{/isEnum}}{{/vars}}{{/hasEnums}}{{/model}}{{/models}} private class EnumNameSerializer[E <: Enumeration: ClassTag](enumeration: E) extends Serializer[E#Value] { import JsonDSL._ diff --git a/samples/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/core/JsonSupport.scala b/samples/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/core/JsonSupport.scala index 767c0b4b9a6b..e8bb0c329d0a 100644 --- a/samples/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/core/JsonSupport.scala +++ b/samples/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/core/JsonSupport.scala @@ -17,7 +17,11 @@ import sttp.client3.json4s.SttpJson4sApi import scala.reflect.ClassTag object JsonSupport extends SttpJson4sApi { - def enumSerializers: Seq[Serializer[_]] = Seq[Serializer[_]]() + def enumSerializers: Seq[Serializer[_]] = Seq[Serializer[_]]() :+ + new EnumNameSerializer(EnumTestEnums.Search) :+ + new EnumNameSerializer(EnumTestEnums.SortBy) :+ + new EnumNameSerializer(OrderEnums.Status) :+ + new EnumNameSerializer(PetEnums.Status) private class EnumNameSerializer[E <: Enumeration: ClassTag](enumeration: E) extends Serializer[E#Value] { import JsonDSL._ From c9204c4330ac9bd6bddc5e8f1591845066d2907c Mon Sep 17 00:00:00 2001 From: William Cheng Date: Wed, 31 Jan 2024 11:29:15 +0800 Subject: [PATCH 07/10] Update model_generic.mustache, tuple notation breaks when there is only one element in the tuple (#17749) * Update model_generic.mustache, tuple notation breaks when there is only one element in the tuple In this excerpt of the mustache template, the matching behaviour is bugged when there is only one element in the tuple notation. A single string with the tuple notation, e.g., `("string")`, will result in a string, and when values are compared with the string, it will do a `contains` match instead of an exact match, which is unintended behaviour. * Update with samples, step 3 * Add test spec and regenerate samples * Update samples * Update spec and samples * update samples --------- Co-authored-by: Edmund Loo Co-authored-by: Edmund Loo --- .../resources/python/model_generic.mustache | 4 +- ...ith-fake-endpoints-models-for-testing.yaml | 61 +++++++ .../openapi_client/models/default_value.py | 2 +- .../openapi_client/models/pet.py | 2 +- .../openapi_client/models/query.py | 2 +- .../openapi_client/models/default_value.py | 2 +- .../python/openapi_client/models/pet.py | 2 +- .../python/openapi_client/models/query.py | 2 +- .../python-aiohttp/.openapi-generator/FILES | 10 ++ .../client/petstore/python-aiohttp/README.md | 5 + .../petstore/python-aiohttp/docs/Bathing.md | 31 ++++ .../petstore/python-aiohttp/docs/Feeding.md | 31 ++++ .../python-aiohttp/docs/PoopCleaning.md | 31 ++++ .../petstore/python-aiohttp/docs/Task.md | 31 ++++ .../python-aiohttp/docs/TaskActivity.md | 31 ++++ .../python-aiohttp/petstore_api/__init__.py | 5 + .../petstore_api/models/__init__.py | 5 + .../petstore_api/models/bathing.py | 105 ++++++++++++ .../petstore_api/models/enum_arrays.py | 4 +- .../petstore_api/models/enum_test.py | 10 +- .../petstore_api/models/feeding.py | 105 ++++++++++++ .../petstore_api/models/map_test.py | 2 +- .../petstore_api/models/order.py | 2 +- .../python-aiohttp/petstore_api/models/pet.py | 2 +- .../petstore_api/models/poop_cleaning.py | 105 ++++++++++++ .../petstore_api/models/special_name.py | 2 +- .../petstore_api/models/task.py | 93 +++++++++++ .../petstore_api/models/task_activity.py | 151 +++++++++++++++++ .../python-aiohttp/test/test_bathing.py | 57 +++++++ .../python-aiohttp/test/test_feeding.py | 57 +++++++ .../python-aiohttp/test/test_poop_cleaning.py | 57 +++++++ .../petstore/python-aiohttp/test/test_task.py | 55 +++++++ .../python-aiohttp/test/test_task_activity.py | 57 +++++++ .../.openapi-generator/FILES | 10 ++ .../python-pydantic-v1-aiohttp/README.md | 5 + .../docs/Bathing.md | 30 ++++ .../docs/Feeding.md | 30 ++++ .../docs/PoopCleaning.md | 30 ++++ .../python-pydantic-v1-aiohttp/docs/Task.md | 30 ++++ .../docs/TaskActivity.md | 30 ++++ .../petstore_api/__init__.py | 5 + .../petstore_api/models/__init__.py | 5 + .../petstore_api/models/bathing.py | 89 ++++++++++ .../petstore_api/models/feeding.py | 89 ++++++++++ .../petstore_api/models/poop_cleaning.py | 89 ++++++++++ .../petstore_api/models/task.py | 77 +++++++++ .../petstore_api/models/task_activity.py | 155 ++++++++++++++++++ .../test/test_bathing.py | 57 +++++++ .../test/test_feeding.py | 57 +++++++ .../test/test_poop_cleaning.py | 57 +++++++ .../test/test_task.py | 55 +++++++ .../test/test_task_activity.py | 57 +++++++ .../.openapi-generator/FILES | 10 ++ .../petstore/python-pydantic-v1/README.md | 5 + .../python-pydantic-v1/docs/Bathing.md | 30 ++++ .../python-pydantic-v1/docs/Feeding.md | 30 ++++ .../python-pydantic-v1/docs/PoopCleaning.md | 30 ++++ .../petstore/python-pydantic-v1/docs/Task.md | 30 ++++ .../python-pydantic-v1/docs/TaskActivity.md | 30 ++++ .../petstore_api/__init__.py | 5 + .../petstore_api/models/__init__.py | 5 + .../petstore_api/models/bathing.py | 101 ++++++++++++ .../petstore_api/models/feeding.py | 101 ++++++++++++ .../petstore_api/models/poop_cleaning.py | 101 ++++++++++++ .../petstore_api/models/task.py | 89 ++++++++++ .../petstore_api/models/task_activity.py | 155 ++++++++++++++++++ .../python-pydantic-v1/test/test_bathing.py | 57 +++++++ .../python-pydantic-v1/test/test_feeding.py | 57 +++++++ .../test/test_poop_cleaning.py | 57 +++++++ .../python-pydantic-v1/test/test_task.py | 55 +++++++ .../test/test_task_activity.py | 57 +++++++ .../petstore/python/.openapi-generator/FILES | 10 ++ .../openapi3/client/petstore/python/README.md | 5 + .../client/petstore/python/docs/Bathing.md | 31 ++++ .../client/petstore/python/docs/Feeding.md | 31 ++++ .../petstore/python/docs/PoopCleaning.md | 31 ++++ .../client/petstore/python/docs/Task.md | 31 ++++ .../petstore/python/docs/TaskActivity.md | 31 ++++ .../petstore/python/petstore_api/__init__.py | 5 + .../python/petstore_api/models/__init__.py | 5 + .../python/petstore_api/models/bathing.py | 118 +++++++++++++ .../python/petstore_api/models/enum_arrays.py | 4 +- .../python/petstore_api/models/enum_test.py | 10 +- .../python/petstore_api/models/feeding.py | 118 +++++++++++++ .../python/petstore_api/models/map_test.py | 2 +- .../python/petstore_api/models/order.py | 2 +- .../python/petstore_api/models/pet.py | 2 +- .../petstore_api/models/poop_cleaning.py | 118 +++++++++++++ .../petstore_api/models/special_name.py | 2 +- .../python/petstore_api/models/task.py | 106 ++++++++++++ .../petstore_api/models/task_activity.py | 151 +++++++++++++++++ .../petstore/python/test/test_bathing.py | 57 +++++++ .../petstore/python/test/test_feeding.py | 57 +++++++ .../python/test/test_poop_cleaning.py | 57 +++++++ .../client/petstore/python/test/test_task.py | 55 +++++++ .../python/test/test_task_activity.py | 57 +++++++ 96 files changed, 4149 insertions(+), 30 deletions(-) create mode 100644 samples/openapi3/client/petstore/python-aiohttp/docs/Bathing.md create mode 100644 samples/openapi3/client/petstore/python-aiohttp/docs/Feeding.md create mode 100644 samples/openapi3/client/petstore/python-aiohttp/docs/PoopCleaning.md create mode 100644 samples/openapi3/client/petstore/python-aiohttp/docs/Task.md create mode 100644 samples/openapi3/client/petstore/python-aiohttp/docs/TaskActivity.md create mode 100644 samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/bathing.py create mode 100644 samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/feeding.py create mode 100644 samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/poop_cleaning.py create mode 100644 samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/task.py create mode 100644 samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/task_activity.py create mode 100644 samples/openapi3/client/petstore/python-aiohttp/test/test_bathing.py create mode 100644 samples/openapi3/client/petstore/python-aiohttp/test/test_feeding.py create mode 100644 samples/openapi3/client/petstore/python-aiohttp/test/test_poop_cleaning.py create mode 100644 samples/openapi3/client/petstore/python-aiohttp/test/test_task.py create mode 100644 samples/openapi3/client/petstore/python-aiohttp/test/test_task_activity.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/Bathing.md create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/Feeding.md create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/PoopCleaning.md create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/Task.md create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/TaskActivity.md create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/bathing.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/feeding.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/poop_cleaning.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/task.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/task_activity.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_bathing.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_feeding.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_poop_cleaning.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_task.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_task_activity.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1/docs/Bathing.md create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1/docs/Feeding.md create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1/docs/PoopCleaning.md create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1/docs/Task.md create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1/docs/TaskActivity.md create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/bathing.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/feeding.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/poop_cleaning.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/task.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/task_activity.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1/test/test_bathing.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1/test/test_feeding.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1/test/test_poop_cleaning.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1/test/test_task.py create mode 100644 samples/openapi3/client/petstore/python-pydantic-v1/test/test_task_activity.py create mode 100644 samples/openapi3/client/petstore/python/docs/Bathing.md create mode 100644 samples/openapi3/client/petstore/python/docs/Feeding.md create mode 100644 samples/openapi3/client/petstore/python/docs/PoopCleaning.md create mode 100644 samples/openapi3/client/petstore/python/docs/Task.md create mode 100644 samples/openapi3/client/petstore/python/docs/TaskActivity.md create mode 100644 samples/openapi3/client/petstore/python/petstore_api/models/bathing.py create mode 100644 samples/openapi3/client/petstore/python/petstore_api/models/feeding.py create mode 100644 samples/openapi3/client/petstore/python/petstore_api/models/poop_cleaning.py create mode 100644 samples/openapi3/client/petstore/python/petstore_api/models/task.py create mode 100644 samples/openapi3/client/petstore/python/petstore_api/models/task_activity.py create mode 100644 samples/openapi3/client/petstore/python/test/test_bathing.py create mode 100644 samples/openapi3/client/petstore/python/test/test_feeding.py create mode 100644 samples/openapi3/client/petstore/python/test/test_poop_cleaning.py create mode 100644 samples/openapi3/client/petstore/python/test/test_task.py create mode 100644 samples/openapi3/client/petstore/python/test/test_task_activity.py diff --git a/modules/openapi-generator/src/main/resources/python/model_generic.mustache b/modules/openapi-generator/src/main/resources/python/model_generic.mustache index c9df87810970..fe470f8295ff 100644 --- a/modules/openapi-generator/src/main/resources/python/model_generic.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_generic.mustache @@ -64,11 +64,11 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} {{/required}} {{#isArray}} for i in value: - if i not in ({{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}): + if i not in set([{{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}]): raise ValueError("each list item must be one of ({{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}})") {{/isArray}} {{^isArray}} - if value not in ({{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}): + if value not in set([{{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}]): raise ValueError("must be one of enum values ({{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}})") {{/isArray}} return value 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 0081123ded62..1e992fab4669 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 @@ -1579,6 +1579,67 @@ components: type: string xml: name: Tag + PoopCleaning: + type: object + properties: + task_name: + type: string + enum: [cleaning] + function_name: + type: string + enum: [care] + content: + type: string + required: + - task_name + - function_name + - content + Feeding: + type: object + properties: + task_name: + type: string + enum: [cleaning] + function_name: + type: string + enum: [care_nourish] + content: + type: string + required: + - task_name + - function_name + - content + Bathing: + type: object + properties: + task_name: + type: string + enum: [cleaning_deep] + function_name: + type: string + enum: [care_nourish] + content: + type: string + required: + - task_name + - function_name + - content + Task: + title: Task + type: object + description: Used to test oneOf enums with only one string value. + properties: + id: + type: string + format: uuid + activity: + oneOf: + - $ref: '#/components/schemas/PoopCleaning' + - $ref: '#/components/schemas/Feeding' + - $ref: '#/components/schemas/Bathing' + required: + - id + - activity Pet: type: object required: diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/default_value.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/default_value.py index aaaeb2682c12..b5311d7a43c6 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/default_value.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/default_value.py @@ -45,7 +45,7 @@ def array_string_enum_default_validate_enum(cls, value): return value for i in value: - if i not in ('success', 'failure', 'unclassified'): + if i not in set(['success', 'failure', 'unclassified']): raise ValueError("each list item must be one of ('success', 'failure', 'unclassified')") return value diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/pet.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/pet.py index 54caa7b78b9e..24eb8075e612 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/pet.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/pet.py @@ -43,7 +43,7 @@ def status_validate_enum(cls, value): if value is None: return value - if value not in ('available', 'pending', 'sold'): + if value not in set(['available', 'pending', 'sold']): raise ValueError("must be one of enum values ('available', 'pending', 'sold')") return value diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/query.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/query.py index 2f7343030130..0d2c05017fdc 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/query.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/query.py @@ -38,7 +38,7 @@ def outcomes_validate_enum(cls, value): return value for i in value: - if i not in ('SUCCESS', 'FAILURE', 'SKIPPED'): + if i not in set(['SUCCESS', 'FAILURE', 'SKIPPED']): raise ValueError("each list item must be one of ('SUCCESS', 'FAILURE', 'SKIPPED')") return value diff --git a/samples/client/echo_api/python/openapi_client/models/default_value.py b/samples/client/echo_api/python/openapi_client/models/default_value.py index 80cdb03a45d1..a8c27c721cdd 100644 --- a/samples/client/echo_api/python/openapi_client/models/default_value.py +++ b/samples/client/echo_api/python/openapi_client/models/default_value.py @@ -45,7 +45,7 @@ def array_string_enum_default_validate_enum(cls, value): return value for i in value: - if i not in ('success', 'failure', 'unclassified'): + if i not in set(['success', 'failure', 'unclassified']): raise ValueError("each list item must be one of ('success', 'failure', 'unclassified')") return value diff --git a/samples/client/echo_api/python/openapi_client/models/pet.py b/samples/client/echo_api/python/openapi_client/models/pet.py index 62c473647ba5..a3f9d65d7103 100644 --- a/samples/client/echo_api/python/openapi_client/models/pet.py +++ b/samples/client/echo_api/python/openapi_client/models/pet.py @@ -43,7 +43,7 @@ def status_validate_enum(cls, value): if value is None: return value - if value not in ('available', 'pending', 'sold'): + if value not in set(['available', 'pending', 'sold']): raise ValueError("must be one of enum values ('available', 'pending', 'sold')") return value diff --git a/samples/client/echo_api/python/openapi_client/models/query.py b/samples/client/echo_api/python/openapi_client/models/query.py index 2f7343030130..0d2c05017fdc 100644 --- a/samples/client/echo_api/python/openapi_client/models/query.py +++ b/samples/client/echo_api/python/openapi_client/models/query.py @@ -38,7 +38,7 @@ def outcomes_validate_enum(cls, value): return value for i in value: - if i not in ('SUCCESS', 'FAILURE', 'SKIPPED'): + if i not in set(['SUCCESS', 'FAILURE', 'SKIPPED']): raise ValueError("each list item must be one of ('SUCCESS', 'FAILURE', 'SKIPPED')") return value diff --git a/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/FILES b/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/FILES index b85011e97909..b262850d70c5 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/FILES @@ -17,6 +17,7 @@ docs/ArrayOfArrayOfNumberOnly.md docs/ArrayOfNumberOnly.md docs/ArrayTest.md docs/BasquePig.md +docs/Bathing.md docs/Capitalization.md docs/Cat.md docs/Category.md @@ -38,6 +39,7 @@ docs/EnumString2.md docs/EnumTest.md docs/FakeApi.md docs/FakeClassnameTags123Api.md +docs/Feeding.md docs/File.md docs/FileSchemaTestClass.md docs/FirstRef.md @@ -74,6 +76,7 @@ docs/ParentWithOptionalDict.md docs/Pet.md docs/PetApi.md docs/Pig.md +docs/PoopCleaning.md docs/PropertyNameCollision.md docs/ReadOnlyFirst.md docs/SecondRef.md @@ -84,6 +87,8 @@ docs/SpecialModelName.md docs/SpecialName.md docs/StoreApi.md docs/Tag.md +docs/Task.md +docs/TaskActivity.md docs/TestErrorResponsesWithModel400Response.md docs/TestErrorResponsesWithModel404Response.md docs/TestInlineFreeformAdditionalPropertiesRequest.md @@ -121,6 +126,7 @@ petstore_api/models/array_of_array_of_number_only.py petstore_api/models/array_of_number_only.py petstore_api/models/array_test.py petstore_api/models/basque_pig.py +petstore_api/models/bathing.py petstore_api/models/capitalization.py petstore_api/models/cat.py petstore_api/models/category.py @@ -139,6 +145,7 @@ petstore_api/models/enum_class.py petstore_api/models/enum_string1.py petstore_api/models/enum_string2.py petstore_api/models/enum_test.py +petstore_api/models/feeding.py petstore_api/models/file.py petstore_api/models/file_schema_test_class.py petstore_api/models/first_ref.py @@ -174,6 +181,7 @@ petstore_api/models/parent.py petstore_api/models/parent_with_optional_dict.py petstore_api/models/pet.py petstore_api/models/pig.py +petstore_api/models/poop_cleaning.py petstore_api/models/property_name_collision.py petstore_api/models/read_only_first.py petstore_api/models/second_ref.py @@ -183,6 +191,8 @@ petstore_api/models/special_character_enum.py petstore_api/models/special_model_name.py petstore_api/models/special_name.py petstore_api/models/tag.py +petstore_api/models/task.py +petstore_api/models/task_activity.py petstore_api/models/test_error_responses_with_model400_response.py petstore_api/models/test_error_responses_with_model404_response.py petstore_api/models/test_inline_freeform_additional_properties_request.py diff --git a/samples/openapi3/client/petstore/python-aiohttp/README.md b/samples/openapi3/client/petstore/python-aiohttp/README.md index 93d1a926bece..cf37ef18e40e 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/README.md +++ b/samples/openapi3/client/petstore/python-aiohttp/README.md @@ -152,6 +152,7 @@ Class | Method | HTTP request | Description - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) - [ArrayTest](docs/ArrayTest.md) - [BasquePig](docs/BasquePig.md) + - [Bathing](docs/Bathing.md) - [Capitalization](docs/Capitalization.md) - [Cat](docs/Cat.md) - [Category](docs/Category.md) @@ -170,6 +171,7 @@ Class | Method | HTTP request | Description - [EnumString1](docs/EnumString1.md) - [EnumString2](docs/EnumString2.md) - [EnumTest](docs/EnumTest.md) + - [Feeding](docs/Feeding.md) - [File](docs/File.md) - [FileSchemaTestClass](docs/FileSchemaTestClass.md) - [FirstRef](docs/FirstRef.md) @@ -205,6 +207,7 @@ Class | Method | HTTP request | Description - [ParentWithOptionalDict](docs/ParentWithOptionalDict.md) - [Pet](docs/Pet.md) - [Pig](docs/Pig.md) + - [PoopCleaning](docs/PoopCleaning.md) - [PropertyNameCollision](docs/PropertyNameCollision.md) - [ReadOnlyFirst](docs/ReadOnlyFirst.md) - [SecondRef](docs/SecondRef.md) @@ -214,6 +217,8 @@ Class | Method | HTTP request | Description - [SpecialModelName](docs/SpecialModelName.md) - [SpecialName](docs/SpecialName.md) - [Tag](docs/Tag.md) + - [Task](docs/Task.md) + - [TaskActivity](docs/TaskActivity.md) - [TestErrorResponsesWithModel400Response](docs/TestErrorResponsesWithModel400Response.md) - [TestErrorResponsesWithModel404Response](docs/TestErrorResponsesWithModel404Response.md) - [TestInlineFreeformAdditionalPropertiesRequest](docs/TestInlineFreeformAdditionalPropertiesRequest.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Bathing.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Bathing.md new file mode 100644 index 000000000000..4c4963bf5934 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Bathing.md @@ -0,0 +1,31 @@ +# Bathing + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**task_name** | **str** | | +**function_name** | **str** | | +**content** | **str** | | + +## Example + +```python +from petstore_api.models.bathing import Bathing + +# TODO update the JSON string below +json = "{}" +# create an instance of Bathing from a JSON string +bathing_instance = Bathing.from_json(json) +# print the JSON string representation of the object +print Bathing.to_json() + +# convert the object into a dict +bathing_dict = bathing_instance.to_dict() +# create an instance of Bathing from a dict +bathing_form_dict = bathing.from_dict(bathing_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Feeding.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Feeding.md new file mode 100644 index 000000000000..f0d51f621c29 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Feeding.md @@ -0,0 +1,31 @@ +# Feeding + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**task_name** | **str** | | +**function_name** | **str** | | +**content** | **str** | | + +## Example + +```python +from petstore_api.models.feeding import Feeding + +# TODO update the JSON string below +json = "{}" +# create an instance of Feeding from a JSON string +feeding_instance = Feeding.from_json(json) +# print the JSON string representation of the object +print Feeding.to_json() + +# convert the object into a dict +feeding_dict = feeding_instance.to_dict() +# create an instance of Feeding from a dict +feeding_form_dict = feeding.from_dict(feeding_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/PoopCleaning.md b/samples/openapi3/client/petstore/python-aiohttp/docs/PoopCleaning.md new file mode 100644 index 000000000000..9fd6b0c32451 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/PoopCleaning.md @@ -0,0 +1,31 @@ +# PoopCleaning + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**task_name** | **str** | | +**function_name** | **str** | | +**content** | **str** | | + +## Example + +```python +from petstore_api.models.poop_cleaning import PoopCleaning + +# TODO update the JSON string below +json = "{}" +# create an instance of PoopCleaning from a JSON string +poop_cleaning_instance = PoopCleaning.from_json(json) +# print the JSON string representation of the object +print PoopCleaning.to_json() + +# convert the object into a dict +poop_cleaning_dict = poop_cleaning_instance.to_dict() +# create an instance of PoopCleaning from a dict +poop_cleaning_form_dict = poop_cleaning.from_dict(poop_cleaning_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Task.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Task.md new file mode 100644 index 000000000000..6cee08c6fe61 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Task.md @@ -0,0 +1,31 @@ +# Task + +Used to test oneOf enums with only one string value. + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **str** | | +**activity** | [**TaskActivity**](TaskActivity.md) | | + +## Example + +```python +from petstore_api.models.task import Task + +# TODO update the JSON string below +json = "{}" +# create an instance of Task from a JSON string +task_instance = Task.from_json(json) +# print the JSON string representation of the object +print Task.to_json() + +# convert the object into a dict +task_dict = task_instance.to_dict() +# create an instance of Task from a dict +task_form_dict = task.from_dict(task_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/TaskActivity.md b/samples/openapi3/client/petstore/python-aiohttp/docs/TaskActivity.md new file mode 100644 index 000000000000..37f10f9031ec --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/TaskActivity.md @@ -0,0 +1,31 @@ +# TaskActivity + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**task_name** | **str** | | +**function_name** | **str** | | +**content** | **str** | | + +## Example + +```python +from petstore_api.models.task_activity import TaskActivity + +# TODO update the JSON string below +json = "{}" +# create an instance of TaskActivity from a JSON string +task_activity_instance = TaskActivity.from_json(json) +# print the JSON string representation of the object +print TaskActivity.to_json() + +# convert the object into a dict +task_activity_dict = task_activity_instance.to_dict() +# create an instance of TaskActivity from a dict +task_activity_form_dict = task_activity.from_dict(task_activity_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 f791bc531127..704dcbaffbd6 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/__init__.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/__init__.py @@ -51,6 +51,7 @@ from petstore_api.models.array_of_number_only import ArrayOfNumberOnly from petstore_api.models.array_test import ArrayTest from petstore_api.models.basque_pig import BasquePig +from petstore_api.models.bathing import Bathing from petstore_api.models.capitalization import Capitalization from petstore_api.models.cat import Cat from petstore_api.models.category import Category @@ -69,6 +70,7 @@ from petstore_api.models.enum_string1 import EnumString1 from petstore_api.models.enum_string2 import EnumString2 from petstore_api.models.enum_test import EnumTest +from petstore_api.models.feeding import Feeding from petstore_api.models.file import File from petstore_api.models.file_schema_test_class import FileSchemaTestClass from petstore_api.models.first_ref import FirstRef @@ -104,6 +106,7 @@ from petstore_api.models.parent_with_optional_dict import ParentWithOptionalDict from petstore_api.models.pet import Pet from petstore_api.models.pig import Pig +from petstore_api.models.poop_cleaning import PoopCleaning from petstore_api.models.property_name_collision import PropertyNameCollision from petstore_api.models.read_only_first import ReadOnlyFirst from petstore_api.models.second_ref import SecondRef @@ -113,6 +116,8 @@ from petstore_api.models.special_model_name import SpecialModelName from petstore_api.models.special_name import SpecialName from petstore_api.models.tag import Tag +from petstore_api.models.task import Task +from petstore_api.models.task_activity import TaskActivity from petstore_api.models.test_error_responses_with_model400_response import TestErrorResponsesWithModel400Response from petstore_api.models.test_error_responses_with_model404_response import TestErrorResponsesWithModel404Response from petstore_api.models.test_inline_freeform_additional_properties_request import TestInlineFreeformAdditionalPropertiesRequest 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 945dd198de1a..554f557cb05a 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 @@ -27,6 +27,7 @@ from petstore_api.models.array_of_number_only import ArrayOfNumberOnly from petstore_api.models.array_test import ArrayTest from petstore_api.models.basque_pig import BasquePig +from petstore_api.models.bathing import Bathing from petstore_api.models.capitalization import Capitalization from petstore_api.models.cat import Cat from petstore_api.models.category import Category @@ -45,6 +46,7 @@ from petstore_api.models.enum_string1 import EnumString1 from petstore_api.models.enum_string2 import EnumString2 from petstore_api.models.enum_test import EnumTest +from petstore_api.models.feeding import Feeding from petstore_api.models.file import File from petstore_api.models.file_schema_test_class import FileSchemaTestClass from petstore_api.models.first_ref import FirstRef @@ -80,6 +82,7 @@ from petstore_api.models.parent_with_optional_dict import ParentWithOptionalDict from petstore_api.models.pet import Pet from petstore_api.models.pig import Pig +from petstore_api.models.poop_cleaning import PoopCleaning from petstore_api.models.property_name_collision import PropertyNameCollision from petstore_api.models.read_only_first import ReadOnlyFirst from petstore_api.models.second_ref import SecondRef @@ -89,6 +92,8 @@ from petstore_api.models.special_model_name import SpecialModelName from petstore_api.models.special_name import SpecialName from petstore_api.models.tag import Tag +from petstore_api.models.task import Task +from petstore_api.models.task_activity import TaskActivity from petstore_api.models.test_error_responses_with_model400_response import TestErrorResponsesWithModel400Response from petstore_api.models.test_error_responses_with_model404_response import TestErrorResponsesWithModel404Response from petstore_api.models.test_inline_freeform_additional_properties_request import TestInlineFreeformAdditionalPropertiesRequest diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/bathing.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/bathing.py new file mode 100644 index 000000000000..efc485131032 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/bathing.py @@ -0,0 +1,105 @@ +# 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, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class Bathing(BaseModel): + """ + Bathing + """ # noqa: E501 + task_name: StrictStr + function_name: StrictStr + content: StrictStr + __properties: ClassVar[List[str]] = ["task_name", "function_name", "content"] + + @field_validator('task_name') + def task_name_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['cleaning_deep']): + raise ValueError("must be one of enum values ('cleaning_deep')") + return value + + @field_validator('function_name') + def function_name_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['care_nourish']): + raise ValueError("must be one of enum values ('care_nourish')") + return value + + model_config = { + "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 Bathing 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 Bathing from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "task_name": obj.get("task_name"), + "function_name": obj.get("function_name"), + "content": obj.get("content") + }) + return _obj + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_arrays.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_arrays.py index 1e957885f837..6bac8225630a 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_arrays.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_arrays.py @@ -36,7 +36,7 @@ def just_symbol_validate_enum(cls, value): if value is None: return value - if value not in ('>=', '$'): + if value not in set(['>=', '$']): raise ValueError("must be one of enum values ('>=', '$')") return value @@ -47,7 +47,7 @@ def array_enum_validate_enum(cls, value): return value for i in value: - if i not in ('fish', 'crab'): + if i not in set(['fish', 'crab']): raise ValueError("each list item must be one of ('fish', 'crab')") return value diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_test.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_test.py index 45308ff4da4e..4f2d86483fb5 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_test.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_test.py @@ -47,14 +47,14 @@ def enum_string_validate_enum(cls, value): if value is None: return value - if value not in ('UPPER', 'lower', ''): + if value not in set(['UPPER', 'lower', '']): raise ValueError("must be one of enum values ('UPPER', 'lower', '')") return value @field_validator('enum_string_required') def enum_string_required_validate_enum(cls, value): """Validates the enum""" - if value not in ('UPPER', 'lower', ''): + if value not in set(['UPPER', 'lower', '']): raise ValueError("must be one of enum values ('UPPER', 'lower', '')") return value @@ -64,7 +64,7 @@ def enum_integer_default_validate_enum(cls, value): if value is None: return value - if value not in (1, 5, 14): + if value not in set([1, 5, 14]): raise ValueError("must be one of enum values (1, 5, 14)") return value @@ -74,7 +74,7 @@ def enum_integer_validate_enum(cls, value): if value is None: return value - if value not in (1, -1): + if value not in set([1, -1]): raise ValueError("must be one of enum values (1, -1)") return value @@ -84,7 +84,7 @@ def enum_number_validate_enum(cls, value): if value is None: return value - if value not in (1.1, -1.2): + if value not in set([1.1, -1.2]): raise ValueError("must be one of enum values (1.1, -1.2)") return value diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/feeding.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/feeding.py new file mode 100644 index 000000000000..4c5333d3b161 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/feeding.py @@ -0,0 +1,105 @@ +# 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, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class Feeding(BaseModel): + """ + Feeding + """ # noqa: E501 + task_name: StrictStr + function_name: StrictStr + content: StrictStr + __properties: ClassVar[List[str]] = ["task_name", "function_name", "content"] + + @field_validator('task_name') + def task_name_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['cleaning']): + raise ValueError("must be one of enum values ('cleaning')") + return value + + @field_validator('function_name') + def function_name_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['care_nourish']): + raise ValueError("must be one of enum values ('care_nourish')") + return value + + model_config = { + "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 Feeding 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 Feeding from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "task_name": obj.get("task_name"), + "function_name": obj.get("function_name"), + "content": obj.get("content") + }) + return _obj + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/map_test.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/map_test.py index 8d0e5a8ad628..bb674830c01d 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/map_test.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/map_test.py @@ -38,7 +38,7 @@ def map_of_enum_string_validate_enum(cls, value): if value is None: return value - if value not in ('UPPER', 'lower'): + if value not in set(['UPPER', 'lower']): raise ValueError("must be one of enum values ('UPPER', 'lower')") return value diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/order.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/order.py index 94f1a306b27d..5c08aae91b1b 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/order.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/order.py @@ -41,7 +41,7 @@ def status_validate_enum(cls, value): if value is None: return value - if value not in ('placed', 'approved', 'delivered'): + if value not in set(['placed', 'approved', 'delivered']): raise ValueError("must be one of enum values ('placed', 'approved', 'delivered')") return value diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/pet.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/pet.py index 3812cfa2a15e..05f24508062d 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/pet.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/pet.py @@ -43,7 +43,7 @@ def status_validate_enum(cls, value): if value is None: return value - if value not in ('available', 'pending', 'sold'): + if value not in set(['available', 'pending', 'sold']): raise ValueError("must be one of enum values ('available', 'pending', 'sold')") return value diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/poop_cleaning.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/poop_cleaning.py new file mode 100644 index 000000000000..789ef627f0ed --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/poop_cleaning.py @@ -0,0 +1,105 @@ +# 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, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class PoopCleaning(BaseModel): + """ + PoopCleaning + """ # noqa: E501 + task_name: StrictStr + function_name: StrictStr + content: StrictStr + __properties: ClassVar[List[str]] = ["task_name", "function_name", "content"] + + @field_validator('task_name') + def task_name_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['cleaning']): + raise ValueError("must be one of enum values ('cleaning')") + return value + + @field_validator('function_name') + def function_name_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['care']): + raise ValueError("must be one of enum values ('care')") + return value + + model_config = { + "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 PoopCleaning 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 PoopCleaning from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "task_name": obj.get("task_name"), + "function_name": obj.get("function_name"), + "content": obj.get("content") + }) + return _obj + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/special_name.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/special_name.py index caff65e97c1d..9029b789f5ec 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/special_name.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/special_name.py @@ -38,7 +38,7 @@ def var_schema_validate_enum(cls, value): if value is None: return value - if value not in ('available', 'pending', 'sold'): + if value not in set(['available', 'pending', 'sold']): raise ValueError("must be one of enum values ('available', 'pending', 'sold')") return value diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/task.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/task.py new file mode 100644 index 000000000000..7fb9e638729f --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/task.py @@ -0,0 +1,93 @@ +# 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, StrictStr +from typing import Any, ClassVar, Dict, List +from petstore_api.models.task_activity import TaskActivity +from typing import Optional, Set +from typing_extensions import Self + +class Task(BaseModel): + """ + Used to test oneOf enums with only one string value. + """ # noqa: E501 + id: StrictStr + activity: TaskActivity + __properties: ClassVar[List[str]] = ["id", "activity"] + + model_config = { + "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 Task 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, + ) + # override the default output from pydantic by calling `to_dict()` of activity + if self.activity: + _dict['activity'] = self.activity.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Task from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "activity": TaskActivity.from_dict(obj["activity"]) if obj.get("activity") is not None else None + }) + return _obj + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/task_activity.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/task_activity.py new file mode 100644 index 000000000000..b76c2604597c --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/task_activity.py @@ -0,0 +1,151 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +import pprint +from pydantic import BaseModel, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional +from petstore_api.models.bathing import Bathing +from petstore_api.models.feeding import Feeding +from petstore_api.models.poop_cleaning import PoopCleaning +from pydantic import StrictStr, Field +from typing import Union, List, Optional, Dict +from typing_extensions import Literal, Self + +TASKACTIVITY_ONE_OF_SCHEMAS = ["Bathing", "Feeding", "PoopCleaning"] + +class TaskActivity(BaseModel): + """ + TaskActivity + """ + # data type: PoopCleaning + oneof_schema_1_validator: Optional[PoopCleaning] = None + # data type: Feeding + oneof_schema_2_validator: Optional[Feeding] = None + # data type: Bathing + oneof_schema_3_validator: Optional[Bathing] = None + actual_instance: Optional[Union[Bathing, Feeding, PoopCleaning]] = None + one_of_schemas: List[str] = Field(default=Literal["Bathing", "Feeding", "PoopCleaning"]) + + model_config = { + "validate_assignment": True, + "protected_namespaces": (), + } + + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @field_validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = TaskActivity.model_construct() + error_messages = [] + match = 0 + # validate data type: PoopCleaning + if not isinstance(v, PoopCleaning): + error_messages.append(f"Error! Input type `{type(v)}` is not `PoopCleaning`") + else: + match += 1 + # validate data type: Feeding + if not isinstance(v, Feeding): + error_messages.append(f"Error! Input type `{type(v)}` is not `Feeding`") + else: + match += 1 + # validate data type: Bathing + if not isinstance(v, Bathing): + error_messages.append(f"Error! Input type `{type(v)}` is not `Bathing`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in TaskActivity with oneOf schemas: Bathing, Feeding, PoopCleaning. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in TaskActivity with oneOf schemas: Bathing, Feeding, PoopCleaning. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + instance = cls.model_construct() + error_messages = [] + match = 0 + + # deserialize data into PoopCleaning + try: + instance.actual_instance = PoopCleaning.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into Feeding + try: + instance.actual_instance = Feeding.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into Bathing + try: + instance.actual_instance = Bathing.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into TaskActivity with oneOf schemas: Bathing, Feeding, PoopCleaning. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into TaskActivity with oneOf schemas: Bathing, Feeding, PoopCleaning. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> Optional[Union[Dict[str, Any], Bathing, Feeding, PoopCleaning]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.model_dump()) + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/test/test_bathing.py b/samples/openapi3/client/petstore/python-aiohttp/test/test_bathing.py new file mode 100644 index 000000000000..583bdcbb09ec --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/test/test_bathing.py @@ -0,0 +1,57 @@ +# 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.bathing import Bathing + +class TestBathing(unittest.TestCase): + """Bathing unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Bathing: + """Test Bathing + 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 `Bathing` + """ + model = Bathing() + if include_optional: + return Bathing( + task_name = 'cleaning_deep', + function_name = 'care_nourish', + content = '' + ) + else: + return Bathing( + task_name = 'cleaning_deep', + function_name = 'care_nourish', + content = '', + ) + """ + + def testBathing(self): + """Test Bathing""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-aiohttp/test/test_feeding.py b/samples/openapi3/client/petstore/python-aiohttp/test/test_feeding.py new file mode 100644 index 000000000000..a0cdfc8f3460 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/test/test_feeding.py @@ -0,0 +1,57 @@ +# 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.feeding import Feeding + +class TestFeeding(unittest.TestCase): + """Feeding unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Feeding: + """Test Feeding + 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 `Feeding` + """ + model = Feeding() + if include_optional: + return Feeding( + task_name = 'cleaning', + function_name = 'care_nourish', + content = '' + ) + else: + return Feeding( + task_name = 'cleaning', + function_name = 'care_nourish', + content = '', + ) + """ + + def testFeeding(self): + """Test Feeding""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-aiohttp/test/test_poop_cleaning.py b/samples/openapi3/client/petstore/python-aiohttp/test/test_poop_cleaning.py new file mode 100644 index 000000000000..4c94fddca97a --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/test/test_poop_cleaning.py @@ -0,0 +1,57 @@ +# 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.poop_cleaning import PoopCleaning + +class TestPoopCleaning(unittest.TestCase): + """PoopCleaning unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> PoopCleaning: + """Test PoopCleaning + 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 `PoopCleaning` + """ + model = PoopCleaning() + if include_optional: + return PoopCleaning( + task_name = 'cleaning', + function_name = 'care', + content = '' + ) + else: + return PoopCleaning( + task_name = 'cleaning', + function_name = 'care', + content = '', + ) + """ + + def testPoopCleaning(self): + """Test PoopCleaning""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-aiohttp/test/test_task.py b/samples/openapi3/client/petstore/python-aiohttp/test/test_task.py new file mode 100644 index 000000000000..bbbc14a39928 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/test/test_task.py @@ -0,0 +1,55 @@ +# 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.task import Task + +class TestTask(unittest.TestCase): + """Task unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Task: + """Test Task + 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 `Task` + """ + model = Task() + if include_optional: + return Task( + id = '', + activity = None + ) + else: + return Task( + id = '', + activity = None, + ) + """ + + def testTask(self): + """Test Task""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-aiohttp/test/test_task_activity.py b/samples/openapi3/client/petstore/python-aiohttp/test/test_task_activity.py new file mode 100644 index 000000000000..2d56d9c5ad3e --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/test/test_task_activity.py @@ -0,0 +1,57 @@ +# 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.task_activity import TaskActivity + +class TestTaskActivity(unittest.TestCase): + """TaskActivity unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TaskActivity: + """Test TaskActivity + 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 `TaskActivity` + """ + model = TaskActivity() + if include_optional: + return TaskActivity( + task_name = 'cleaning_deep', + function_name = 'care_nourish', + content = '' + ) + else: + return TaskActivity( + task_name = 'cleaning_deep', + function_name = 'care_nourish', + content = '', + ) + """ + + def testTaskActivity(self): + """Test TaskActivity""" + # 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 1ef5f596fa14..b03e397c14c3 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 @@ -18,6 +18,7 @@ docs/ArrayOfArrayOfNumberOnly.md docs/ArrayOfNumberOnly.md docs/ArrayTest.md docs/BasquePig.md +docs/Bathing.md docs/Capitalization.md docs/Cat.md docs/Category.md @@ -39,6 +40,7 @@ docs/EnumString2.md docs/EnumTest.md docs/FakeApi.md docs/FakeClassnameTags123Api.md +docs/Feeding.md docs/File.md docs/FileSchemaTestClass.md docs/FirstRef.md @@ -74,6 +76,7 @@ docs/ParentWithOptionalDict.md docs/Pet.md docs/PetApi.md docs/Pig.md +docs/PoopCleaning.md docs/PropertyNameCollision.md docs/ReadOnlyFirst.md docs/SecondRef.md @@ -84,6 +87,8 @@ docs/SpecialModelName.md docs/SpecialName.md docs/StoreApi.md docs/Tag.md +docs/Task.md +docs/TaskActivity.md docs/TestErrorResponsesWithModel400Response.md docs/TestErrorResponsesWithModel404Response.md docs/TestInlineFreeformAdditionalPropertiesRequest.md @@ -122,6 +127,7 @@ petstore_api/models/array_of_array_of_number_only.py petstore_api/models/array_of_number_only.py petstore_api/models/array_test.py petstore_api/models/basque_pig.py +petstore_api/models/bathing.py petstore_api/models/capitalization.py petstore_api/models/cat.py petstore_api/models/category.py @@ -140,6 +146,7 @@ petstore_api/models/enum_class.py petstore_api/models/enum_string1.py petstore_api/models/enum_string2.py petstore_api/models/enum_test.py +petstore_api/models/feeding.py petstore_api/models/file.py petstore_api/models/file_schema_test_class.py petstore_api/models/first_ref.py @@ -174,6 +181,7 @@ petstore_api/models/parent.py petstore_api/models/parent_with_optional_dict.py petstore_api/models/pet.py petstore_api/models/pig.py +petstore_api/models/poop_cleaning.py petstore_api/models/property_name_collision.py petstore_api/models/read_only_first.py petstore_api/models/second_ref.py @@ -183,6 +191,8 @@ petstore_api/models/special_character_enum.py petstore_api/models/special_model_name.py petstore_api/models/special_name.py petstore_api/models/tag.py +petstore_api/models/task.py +petstore_api/models/task_activity.py petstore_api/models/test_error_responses_with_model400_response.py petstore_api/models/test_error_responses_with_model404_response.py petstore_api/models/test_inline_freeform_additional_properties_request.py diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/README.md b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/README.md index b284e2059c87..4912e657ad82 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/README.md +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/README.md @@ -154,6 +154,7 @@ Class | Method | HTTP request | Description - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) - [ArrayTest](docs/ArrayTest.md) - [BasquePig](docs/BasquePig.md) + - [Bathing](docs/Bathing.md) - [Capitalization](docs/Capitalization.md) - [Cat](docs/Cat.md) - [Category](docs/Category.md) @@ -172,6 +173,7 @@ Class | Method | HTTP request | Description - [EnumString1](docs/EnumString1.md) - [EnumString2](docs/EnumString2.md) - [EnumTest](docs/EnumTest.md) + - [Feeding](docs/Feeding.md) - [File](docs/File.md) - [FileSchemaTestClass](docs/FileSchemaTestClass.md) - [FirstRef](docs/FirstRef.md) @@ -206,6 +208,7 @@ Class | Method | HTTP request | Description - [ParentWithOptionalDict](docs/ParentWithOptionalDict.md) - [Pet](docs/Pet.md) - [Pig](docs/Pig.md) + - [PoopCleaning](docs/PoopCleaning.md) - [PropertyNameCollision](docs/PropertyNameCollision.md) - [ReadOnlyFirst](docs/ReadOnlyFirst.md) - [SecondRef](docs/SecondRef.md) @@ -215,6 +218,8 @@ Class | Method | HTTP request | Description - [SpecialModelName](docs/SpecialModelName.md) - [SpecialName](docs/SpecialName.md) - [Tag](docs/Tag.md) + - [Task](docs/Task.md) + - [TaskActivity](docs/TaskActivity.md) - [TestErrorResponsesWithModel400Response](docs/TestErrorResponsesWithModel400Response.md) - [TestErrorResponsesWithModel404Response](docs/TestErrorResponsesWithModel404Response.md) - [TestInlineFreeformAdditionalPropertiesRequest](docs/TestInlineFreeformAdditionalPropertiesRequest.md) diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/Bathing.md b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/Bathing.md new file mode 100644 index 000000000000..f7844f95d54d --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/Bathing.md @@ -0,0 +1,30 @@ +# Bathing + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**task_name** | **str** | | +**function_name** | **str** | | +**content** | **str** | | + +## Example + +```python +from petstore_api.models.bathing import Bathing + +# TODO update the JSON string below +json = "{}" +# create an instance of Bathing from a JSON string +bathing_instance = Bathing.from_json(json) +# print the JSON string representation of the object +print Bathing.to_json() + +# convert the object into a dict +bathing_dict = bathing_instance.to_dict() +# create an instance of Bathing from a dict +bathing_form_dict = bathing.from_dict(bathing_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/Feeding.md b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/Feeding.md new file mode 100644 index 000000000000..30750a67a075 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/Feeding.md @@ -0,0 +1,30 @@ +# Feeding + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**task_name** | **str** | | +**function_name** | **str** | | +**content** | **str** | | + +## Example + +```python +from petstore_api.models.feeding import Feeding + +# TODO update the JSON string below +json = "{}" +# create an instance of Feeding from a JSON string +feeding_instance = Feeding.from_json(json) +# print the JSON string representation of the object +print Feeding.to_json() + +# convert the object into a dict +feeding_dict = feeding_instance.to_dict() +# create an instance of Feeding from a dict +feeding_form_dict = feeding.from_dict(feeding_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/PoopCleaning.md b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/PoopCleaning.md new file mode 100644 index 000000000000..bbc93c0203c0 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/PoopCleaning.md @@ -0,0 +1,30 @@ +# PoopCleaning + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**task_name** | **str** | | +**function_name** | **str** | | +**content** | **str** | | + +## Example + +```python +from petstore_api.models.poop_cleaning import PoopCleaning + +# TODO update the JSON string below +json = "{}" +# create an instance of PoopCleaning from a JSON string +poop_cleaning_instance = PoopCleaning.from_json(json) +# print the JSON string representation of the object +print PoopCleaning.to_json() + +# convert the object into a dict +poop_cleaning_dict = poop_cleaning_instance.to_dict() +# create an instance of PoopCleaning from a dict +poop_cleaning_form_dict = poop_cleaning.from_dict(poop_cleaning_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/Task.md b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/Task.md new file mode 100644 index 000000000000..aefe66e7638b --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/Task.md @@ -0,0 +1,30 @@ +# Task + +Used to test oneOf enums with only one string value. + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **str** | | +**activity** | [**TaskActivity**](TaskActivity.md) | | + +## Example + +```python +from petstore_api.models.task import Task + +# TODO update the JSON string below +json = "{}" +# create an instance of Task from a JSON string +task_instance = Task.from_json(json) +# print the JSON string representation of the object +print Task.to_json() + +# convert the object into a dict +task_dict = task_instance.to_dict() +# create an instance of Task from a dict +task_form_dict = task.from_dict(task_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/TaskActivity.md b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/TaskActivity.md new file mode 100644 index 000000000000..eb2549061563 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/TaskActivity.md @@ -0,0 +1,30 @@ +# TaskActivity + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**task_name** | **str** | | +**function_name** | **str** | | +**content** | **str** | | + +## Example + +```python +from petstore_api.models.task_activity import TaskActivity + +# TODO update the JSON string below +json = "{}" +# create an instance of TaskActivity from a JSON string +task_activity_instance = TaskActivity.from_json(json) +# print the JSON string representation of the object +print TaskActivity.to_json() + +# convert the object into a dict +task_activity_dict = task_activity_instance.to_dict() +# create an instance of TaskActivity from a dict +task_activity_form_dict = task_activity.from_dict(task_activity_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 72d39b9c55e6..a0cbcf6fe0c8 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 @@ -52,6 +52,7 @@ from petstore_api.models.array_of_number_only import ArrayOfNumberOnly from petstore_api.models.array_test import ArrayTest from petstore_api.models.basque_pig import BasquePig +from petstore_api.models.bathing import Bathing from petstore_api.models.capitalization import Capitalization from petstore_api.models.cat import Cat from petstore_api.models.category import Category @@ -70,6 +71,7 @@ from petstore_api.models.enum_string1 import EnumString1 from petstore_api.models.enum_string2 import EnumString2 from petstore_api.models.enum_test import EnumTest +from petstore_api.models.feeding import Feeding from petstore_api.models.file import File from petstore_api.models.file_schema_test_class import FileSchemaTestClass from petstore_api.models.first_ref import FirstRef @@ -104,6 +106,7 @@ from petstore_api.models.parent_with_optional_dict import ParentWithOptionalDict from petstore_api.models.pet import Pet from petstore_api.models.pig import Pig +from petstore_api.models.poop_cleaning import PoopCleaning from petstore_api.models.property_name_collision import PropertyNameCollision from petstore_api.models.read_only_first import ReadOnlyFirst from petstore_api.models.second_ref import SecondRef @@ -113,6 +116,8 @@ from petstore_api.models.special_model_name import SpecialModelName from petstore_api.models.special_name import SpecialName from petstore_api.models.tag import Tag +from petstore_api.models.task import Task +from petstore_api.models.task_activity import TaskActivity from petstore_api.models.test_error_responses_with_model400_response import TestErrorResponsesWithModel400Response from petstore_api.models.test_error_responses_with_model404_response import TestErrorResponsesWithModel404Response from petstore_api.models.test_inline_freeform_additional_properties_request import TestInlineFreeformAdditionalPropertiesRequest 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 c106409daa97..baa94da3a2cb 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 @@ -28,6 +28,7 @@ from petstore_api.models.array_of_number_only import ArrayOfNumberOnly from petstore_api.models.array_test import ArrayTest from petstore_api.models.basque_pig import BasquePig +from petstore_api.models.bathing import Bathing from petstore_api.models.capitalization import Capitalization from petstore_api.models.cat import Cat from petstore_api.models.category import Category @@ -46,6 +47,7 @@ from petstore_api.models.enum_string1 import EnumString1 from petstore_api.models.enum_string2 import EnumString2 from petstore_api.models.enum_test import EnumTest +from petstore_api.models.feeding import Feeding from petstore_api.models.file import File from petstore_api.models.file_schema_test_class import FileSchemaTestClass from petstore_api.models.first_ref import FirstRef @@ -80,6 +82,7 @@ from petstore_api.models.parent_with_optional_dict import ParentWithOptionalDict from petstore_api.models.pet import Pet from petstore_api.models.pig import Pig +from petstore_api.models.poop_cleaning import PoopCleaning from petstore_api.models.property_name_collision import PropertyNameCollision from petstore_api.models.read_only_first import ReadOnlyFirst from petstore_api.models.second_ref import SecondRef @@ -89,6 +92,8 @@ from petstore_api.models.special_model_name import SpecialModelName from petstore_api.models.special_name import SpecialName from petstore_api.models.tag import Tag +from petstore_api.models.task import Task +from petstore_api.models.task_activity import TaskActivity from petstore_api.models.test_error_responses_with_model400_response import TestErrorResponsesWithModel400Response from petstore_api.models.test_error_responses_with_model404_response import TestErrorResponsesWithModel404Response from petstore_api.models.test_inline_freeform_additional_properties_request import TestInlineFreeformAdditionalPropertiesRequest diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/bathing.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/bathing.py new file mode 100644 index 000000000000..986de06f0c20 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/bathing.py @@ -0,0 +1,89 @@ +# 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, Field, StrictStr, validator + +class Bathing(BaseModel): + """ + Bathing + """ + task_name: StrictStr = Field(...) + function_name: StrictStr = Field(...) + content: StrictStr = Field(...) + __properties = ["task_name", "function_name", "content"] + + @validator('task_name') + def task_name_validate_enum(cls, value): + """Validates the enum""" + if value not in ('cleaning_deep'): + raise ValueError("must be one of enum values ('cleaning_deep')") + return value + + @validator('function_name') + def function_name_validate_enum(cls, value): + """Validates the enum""" + if value not in ('care_nourish'): + raise ValueError("must be one of enum values ('care_nourish')") + return value + + 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) -> Bathing: + """Create an instance of Bathing 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) -> Bathing: + """Create an instance of Bathing from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return Bathing.parse_obj(obj) + + _obj = Bathing.parse_obj({ + "task_name": obj.get("task_name"), + "function_name": obj.get("function_name"), + "content": obj.get("content") + }) + return _obj + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/feeding.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/feeding.py new file mode 100644 index 000000000000..ad8143b457aa --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/feeding.py @@ -0,0 +1,89 @@ +# 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, Field, StrictStr, validator + +class Feeding(BaseModel): + """ + Feeding + """ + task_name: StrictStr = Field(...) + function_name: StrictStr = Field(...) + content: StrictStr = Field(...) + __properties = ["task_name", "function_name", "content"] + + @validator('task_name') + def task_name_validate_enum(cls, value): + """Validates the enum""" + if value not in ('cleaning'): + raise ValueError("must be one of enum values ('cleaning')") + return value + + @validator('function_name') + def function_name_validate_enum(cls, value): + """Validates the enum""" + if value not in ('care_nourish'): + raise ValueError("must be one of enum values ('care_nourish')") + return value + + 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) -> Feeding: + """Create an instance of Feeding 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) -> Feeding: + """Create an instance of Feeding from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return Feeding.parse_obj(obj) + + _obj = Feeding.parse_obj({ + "task_name": obj.get("task_name"), + "function_name": obj.get("function_name"), + "content": obj.get("content") + }) + return _obj + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/poop_cleaning.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/poop_cleaning.py new file mode 100644 index 000000000000..54dff6de1f12 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/poop_cleaning.py @@ -0,0 +1,89 @@ +# 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, Field, StrictStr, validator + +class PoopCleaning(BaseModel): + """ + PoopCleaning + """ + task_name: StrictStr = Field(...) + function_name: StrictStr = Field(...) + content: StrictStr = Field(...) + __properties = ["task_name", "function_name", "content"] + + @validator('task_name') + def task_name_validate_enum(cls, value): + """Validates the enum""" + if value not in ('cleaning'): + raise ValueError("must be one of enum values ('cleaning')") + return value + + @validator('function_name') + def function_name_validate_enum(cls, value): + """Validates the enum""" + if value not in ('care'): + raise ValueError("must be one of enum values ('care')") + return value + + 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) -> PoopCleaning: + """Create an instance of PoopCleaning 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) -> PoopCleaning: + """Create an instance of PoopCleaning from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return PoopCleaning.parse_obj(obj) + + _obj = PoopCleaning.parse_obj({ + "task_name": obj.get("task_name"), + "function_name": obj.get("function_name"), + "content": obj.get("content") + }) + return _obj + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/task.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/task.py new file mode 100644 index 000000000000..2fb988a0a5d5 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/task.py @@ -0,0 +1,77 @@ +# 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, Field, StrictStr +from petstore_api.models.task_activity import TaskActivity + +class Task(BaseModel): + """ + Used to test oneOf enums with only one string value. # noqa: E501 + """ + id: StrictStr = Field(...) + activity: TaskActivity = Field(...) + __properties = ["id", "activity"] + + 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) -> Task: + """Create an instance of Task 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) + # override the default output from pydantic by calling `to_dict()` of activity + if self.activity: + _dict['activity'] = self.activity.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> Task: + """Create an instance of Task from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return Task.parse_obj(obj) + + _obj = Task.parse_obj({ + "id": obj.get("id"), + "activity": TaskActivity.from_dict(obj.get("activity")) if obj.get("activity") is not None else None + }) + return _obj + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/task_activity.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/task_activity.py new file mode 100644 index 000000000000..70553f1ef202 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/task_activity.py @@ -0,0 +1,155 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +from inspect import getfullargspec +import json +import pprint +import re # noqa: F401 + +from typing import Any, List, Optional +from pydantic import BaseModel, Field, StrictStr, ValidationError, validator +from petstore_api.models.bathing import Bathing +from petstore_api.models.feeding import Feeding +from petstore_api.models.poop_cleaning import PoopCleaning +from typing import Union, Any, List, TYPE_CHECKING +from pydantic import StrictStr, Field + +TASKACTIVITY_ONE_OF_SCHEMAS = ["Bathing", "Feeding", "PoopCleaning"] + +class TaskActivity(BaseModel): + """ + TaskActivity + """ + # data type: PoopCleaning + oneof_schema_1_validator: Optional[PoopCleaning] = None + # data type: Feeding + oneof_schema_2_validator: Optional[Feeding] = None + # data type: Bathing + oneof_schema_3_validator: Optional[Bathing] = None + if TYPE_CHECKING: + actual_instance: Union[Bathing, Feeding, PoopCleaning] + else: + actual_instance: Any + one_of_schemas: List[str] = Field(TASKACTIVITY_ONE_OF_SCHEMAS, const=True) + + class Config: + validate_assignment = True + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = TaskActivity.construct() + error_messages = [] + match = 0 + # validate data type: PoopCleaning + if not isinstance(v, PoopCleaning): + error_messages.append(f"Error! Input type `{type(v)}` is not `PoopCleaning`") + else: + match += 1 + # validate data type: Feeding + if not isinstance(v, Feeding): + error_messages.append(f"Error! Input type `{type(v)}` is not `Feeding`") + else: + match += 1 + # validate data type: Bathing + if not isinstance(v, Bathing): + error_messages.append(f"Error! Input type `{type(v)}` is not `Bathing`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in TaskActivity with oneOf schemas: Bathing, Feeding, PoopCleaning. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in TaskActivity with oneOf schemas: Bathing, Feeding, PoopCleaning. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: dict) -> TaskActivity: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> TaskActivity: + """Returns the object represented by the json string""" + instance = TaskActivity.construct() + error_messages = [] + match = 0 + + # deserialize data into PoopCleaning + try: + instance.actual_instance = PoopCleaning.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into Feeding + try: + instance.actual_instance = Feeding.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into Bathing + try: + instance.actual_instance = Bathing.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into TaskActivity with oneOf schemas: Bathing, Feeding, PoopCleaning. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into TaskActivity with oneOf schemas: Bathing, Feeding, PoopCleaning. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + to_json = getattr(self.actual_instance, "to_json", None) + if callable(to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> dict: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + to_dict = getattr(self.actual_instance, "to_dict", None) + if callable(to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.dict()) + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_bathing.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_bathing.py new file mode 100644 index 000000000000..cc3a79b6f412 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_bathing.py @@ -0,0 +1,57 @@ +# 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.bathing import Bathing # noqa: E501 + +class TestBathing(unittest.TestCase): + """Bathing unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Bathing: + """Test Bathing + 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 `Bathing` + """ + model = Bathing() # noqa: E501 + if include_optional: + return Bathing( + task_name = 'cleaning_deep', + function_name = 'care_nourish', + content = '' + ) + else: + return Bathing( + task_name = 'cleaning_deep', + function_name = 'care_nourish', + content = '', + ) + """ + + def testBathing(self): + """Test Bathing""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_feeding.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_feeding.py new file mode 100644 index 000000000000..f445dc67c1b8 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_feeding.py @@ -0,0 +1,57 @@ +# 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.feeding import Feeding # noqa: E501 + +class TestFeeding(unittest.TestCase): + """Feeding unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Feeding: + """Test Feeding + 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 `Feeding` + """ + model = Feeding() # noqa: E501 + if include_optional: + return Feeding( + task_name = 'cleaning', + function_name = 'care_nourish', + content = '' + ) + else: + return Feeding( + task_name = 'cleaning', + function_name = 'care_nourish', + content = '', + ) + """ + + def testFeeding(self): + """Test Feeding""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_poop_cleaning.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_poop_cleaning.py new file mode 100644 index 000000000000..e2594e920fa0 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_poop_cleaning.py @@ -0,0 +1,57 @@ +# 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.poop_cleaning import PoopCleaning # noqa: E501 + +class TestPoopCleaning(unittest.TestCase): + """PoopCleaning unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> PoopCleaning: + """Test PoopCleaning + 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 `PoopCleaning` + """ + model = PoopCleaning() # noqa: E501 + if include_optional: + return PoopCleaning( + task_name = 'cleaning', + function_name = 'care', + content = '' + ) + else: + return PoopCleaning( + task_name = 'cleaning', + function_name = 'care', + content = '', + ) + """ + + def testPoopCleaning(self): + """Test PoopCleaning""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_task.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_task.py new file mode 100644 index 000000000000..8e510333d7dd --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_task.py @@ -0,0 +1,55 @@ +# 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.task import Task # noqa: E501 + +class TestTask(unittest.TestCase): + """Task unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Task: + """Test Task + 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 `Task` + """ + model = Task() # noqa: E501 + if include_optional: + return Task( + id = '', + activity = None + ) + else: + return Task( + id = '', + activity = None, + ) + """ + + def testTask(self): + """Test Task""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_task_activity.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_task_activity.py new file mode 100644 index 000000000000..b09dc360824b --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_task_activity.py @@ -0,0 +1,57 @@ +# 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.task_activity import TaskActivity # noqa: E501 + +class TestTaskActivity(unittest.TestCase): + """TaskActivity unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TaskActivity: + """Test TaskActivity + 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 `TaskActivity` + """ + model = TaskActivity() # noqa: E501 + if include_optional: + return TaskActivity( + task_name = 'cleaning_deep', + function_name = 'care_nourish', + content = '' + ) + else: + return TaskActivity( + task_name = 'cleaning_deep', + function_name = 'care_nourish', + content = '', + ) + """ + + def testTaskActivity(self): + """Test TaskActivity""" + # 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 1ef5f596fa14..b03e397c14c3 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python-pydantic-v1/.openapi-generator/FILES @@ -18,6 +18,7 @@ docs/ArrayOfArrayOfNumberOnly.md docs/ArrayOfNumberOnly.md docs/ArrayTest.md docs/BasquePig.md +docs/Bathing.md docs/Capitalization.md docs/Cat.md docs/Category.md @@ -39,6 +40,7 @@ docs/EnumString2.md docs/EnumTest.md docs/FakeApi.md docs/FakeClassnameTags123Api.md +docs/Feeding.md docs/File.md docs/FileSchemaTestClass.md docs/FirstRef.md @@ -74,6 +76,7 @@ docs/ParentWithOptionalDict.md docs/Pet.md docs/PetApi.md docs/Pig.md +docs/PoopCleaning.md docs/PropertyNameCollision.md docs/ReadOnlyFirst.md docs/SecondRef.md @@ -84,6 +87,8 @@ docs/SpecialModelName.md docs/SpecialName.md docs/StoreApi.md docs/Tag.md +docs/Task.md +docs/TaskActivity.md docs/TestErrorResponsesWithModel400Response.md docs/TestErrorResponsesWithModel404Response.md docs/TestInlineFreeformAdditionalPropertiesRequest.md @@ -122,6 +127,7 @@ petstore_api/models/array_of_array_of_number_only.py petstore_api/models/array_of_number_only.py petstore_api/models/array_test.py petstore_api/models/basque_pig.py +petstore_api/models/bathing.py petstore_api/models/capitalization.py petstore_api/models/cat.py petstore_api/models/category.py @@ -140,6 +146,7 @@ petstore_api/models/enum_class.py petstore_api/models/enum_string1.py petstore_api/models/enum_string2.py petstore_api/models/enum_test.py +petstore_api/models/feeding.py petstore_api/models/file.py petstore_api/models/file_schema_test_class.py petstore_api/models/first_ref.py @@ -174,6 +181,7 @@ petstore_api/models/parent.py petstore_api/models/parent_with_optional_dict.py petstore_api/models/pet.py petstore_api/models/pig.py +petstore_api/models/poop_cleaning.py petstore_api/models/property_name_collision.py petstore_api/models/read_only_first.py petstore_api/models/second_ref.py @@ -183,6 +191,8 @@ petstore_api/models/special_character_enum.py petstore_api/models/special_model_name.py petstore_api/models/special_name.py petstore_api/models/tag.py +petstore_api/models/task.py +petstore_api/models/task_activity.py petstore_api/models/test_error_responses_with_model400_response.py petstore_api/models/test_error_responses_with_model404_response.py petstore_api/models/test_inline_freeform_additional_properties_request.py diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/README.md b/samples/openapi3/client/petstore/python-pydantic-v1/README.md index 3cc746aa66fe..ed4434cd181a 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/README.md +++ b/samples/openapi3/client/petstore/python-pydantic-v1/README.md @@ -154,6 +154,7 @@ Class | Method | HTTP request | Description - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) - [ArrayTest](docs/ArrayTest.md) - [BasquePig](docs/BasquePig.md) + - [Bathing](docs/Bathing.md) - [Capitalization](docs/Capitalization.md) - [Cat](docs/Cat.md) - [Category](docs/Category.md) @@ -172,6 +173,7 @@ Class | Method | HTTP request | Description - [EnumString1](docs/EnumString1.md) - [EnumString2](docs/EnumString2.md) - [EnumTest](docs/EnumTest.md) + - [Feeding](docs/Feeding.md) - [File](docs/File.md) - [FileSchemaTestClass](docs/FileSchemaTestClass.md) - [FirstRef](docs/FirstRef.md) @@ -206,6 +208,7 @@ Class | Method | HTTP request | Description - [ParentWithOptionalDict](docs/ParentWithOptionalDict.md) - [Pet](docs/Pet.md) - [Pig](docs/Pig.md) + - [PoopCleaning](docs/PoopCleaning.md) - [PropertyNameCollision](docs/PropertyNameCollision.md) - [ReadOnlyFirst](docs/ReadOnlyFirst.md) - [SecondRef](docs/SecondRef.md) @@ -215,6 +218,8 @@ Class | Method | HTTP request | Description - [SpecialModelName](docs/SpecialModelName.md) - [SpecialName](docs/SpecialName.md) - [Tag](docs/Tag.md) + - [Task](docs/Task.md) + - [TaskActivity](docs/TaskActivity.md) - [TestErrorResponsesWithModel400Response](docs/TestErrorResponsesWithModel400Response.md) - [TestErrorResponsesWithModel404Response](docs/TestErrorResponsesWithModel404Response.md) - [TestInlineFreeformAdditionalPropertiesRequest](docs/TestInlineFreeformAdditionalPropertiesRequest.md) diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/docs/Bathing.md b/samples/openapi3/client/petstore/python-pydantic-v1/docs/Bathing.md new file mode 100644 index 000000000000..f7844f95d54d --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/docs/Bathing.md @@ -0,0 +1,30 @@ +# Bathing + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**task_name** | **str** | | +**function_name** | **str** | | +**content** | **str** | | + +## Example + +```python +from petstore_api.models.bathing import Bathing + +# TODO update the JSON string below +json = "{}" +# create an instance of Bathing from a JSON string +bathing_instance = Bathing.from_json(json) +# print the JSON string representation of the object +print Bathing.to_json() + +# convert the object into a dict +bathing_dict = bathing_instance.to_dict() +# create an instance of Bathing from a dict +bathing_form_dict = bathing.from_dict(bathing_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/docs/Feeding.md b/samples/openapi3/client/petstore/python-pydantic-v1/docs/Feeding.md new file mode 100644 index 000000000000..30750a67a075 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/docs/Feeding.md @@ -0,0 +1,30 @@ +# Feeding + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**task_name** | **str** | | +**function_name** | **str** | | +**content** | **str** | | + +## Example + +```python +from petstore_api.models.feeding import Feeding + +# TODO update the JSON string below +json = "{}" +# create an instance of Feeding from a JSON string +feeding_instance = Feeding.from_json(json) +# print the JSON string representation of the object +print Feeding.to_json() + +# convert the object into a dict +feeding_dict = feeding_instance.to_dict() +# create an instance of Feeding from a dict +feeding_form_dict = feeding.from_dict(feeding_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/docs/PoopCleaning.md b/samples/openapi3/client/petstore/python-pydantic-v1/docs/PoopCleaning.md new file mode 100644 index 000000000000..bbc93c0203c0 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/docs/PoopCleaning.md @@ -0,0 +1,30 @@ +# PoopCleaning + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**task_name** | **str** | | +**function_name** | **str** | | +**content** | **str** | | + +## Example + +```python +from petstore_api.models.poop_cleaning import PoopCleaning + +# TODO update the JSON string below +json = "{}" +# create an instance of PoopCleaning from a JSON string +poop_cleaning_instance = PoopCleaning.from_json(json) +# print the JSON string representation of the object +print PoopCleaning.to_json() + +# convert the object into a dict +poop_cleaning_dict = poop_cleaning_instance.to_dict() +# create an instance of PoopCleaning from a dict +poop_cleaning_form_dict = poop_cleaning.from_dict(poop_cleaning_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/docs/Task.md b/samples/openapi3/client/petstore/python-pydantic-v1/docs/Task.md new file mode 100644 index 000000000000..aefe66e7638b --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/docs/Task.md @@ -0,0 +1,30 @@ +# Task + +Used to test oneOf enums with only one string value. + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **str** | | +**activity** | [**TaskActivity**](TaskActivity.md) | | + +## Example + +```python +from petstore_api.models.task import Task + +# TODO update the JSON string below +json = "{}" +# create an instance of Task from a JSON string +task_instance = Task.from_json(json) +# print the JSON string representation of the object +print Task.to_json() + +# convert the object into a dict +task_dict = task_instance.to_dict() +# create an instance of Task from a dict +task_form_dict = task.from_dict(task_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/docs/TaskActivity.md b/samples/openapi3/client/petstore/python-pydantic-v1/docs/TaskActivity.md new file mode 100644 index 000000000000..eb2549061563 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/docs/TaskActivity.md @@ -0,0 +1,30 @@ +# TaskActivity + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**task_name** | **str** | | +**function_name** | **str** | | +**content** | **str** | | + +## Example + +```python +from petstore_api.models.task_activity import TaskActivity + +# TODO update the JSON string below +json = "{}" +# create an instance of TaskActivity from a JSON string +task_activity_instance = TaskActivity.from_json(json) +# print the JSON string representation of the object +print TaskActivity.to_json() + +# convert the object into a dict +task_activity_dict = task_activity_instance.to_dict() +# create an instance of TaskActivity from a dict +task_activity_form_dict = task_activity.from_dict(task_activity_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 72d39b9c55e6..a0cbcf6fe0c8 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 @@ -52,6 +52,7 @@ from petstore_api.models.array_of_number_only import ArrayOfNumberOnly from petstore_api.models.array_test import ArrayTest from petstore_api.models.basque_pig import BasquePig +from petstore_api.models.bathing import Bathing from petstore_api.models.capitalization import Capitalization from petstore_api.models.cat import Cat from petstore_api.models.category import Category @@ -70,6 +71,7 @@ from petstore_api.models.enum_string1 import EnumString1 from petstore_api.models.enum_string2 import EnumString2 from petstore_api.models.enum_test import EnumTest +from petstore_api.models.feeding import Feeding from petstore_api.models.file import File from petstore_api.models.file_schema_test_class import FileSchemaTestClass from petstore_api.models.first_ref import FirstRef @@ -104,6 +106,7 @@ from petstore_api.models.parent_with_optional_dict import ParentWithOptionalDict from petstore_api.models.pet import Pet from petstore_api.models.pig import Pig +from petstore_api.models.poop_cleaning import PoopCleaning from petstore_api.models.property_name_collision import PropertyNameCollision from petstore_api.models.read_only_first import ReadOnlyFirst from petstore_api.models.second_ref import SecondRef @@ -113,6 +116,8 @@ from petstore_api.models.special_model_name import SpecialModelName from petstore_api.models.special_name import SpecialName from petstore_api.models.tag import Tag +from petstore_api.models.task import Task +from petstore_api.models.task_activity import TaskActivity from petstore_api.models.test_error_responses_with_model400_response import TestErrorResponsesWithModel400Response from petstore_api.models.test_error_responses_with_model404_response import TestErrorResponsesWithModel404Response from petstore_api.models.test_inline_freeform_additional_properties_request import TestInlineFreeformAdditionalPropertiesRequest 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 c106409daa97..baa94da3a2cb 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 @@ -28,6 +28,7 @@ from petstore_api.models.array_of_number_only import ArrayOfNumberOnly from petstore_api.models.array_test import ArrayTest from petstore_api.models.basque_pig import BasquePig +from petstore_api.models.bathing import Bathing from petstore_api.models.capitalization import Capitalization from petstore_api.models.cat import Cat from petstore_api.models.category import Category @@ -46,6 +47,7 @@ from petstore_api.models.enum_string1 import EnumString1 from petstore_api.models.enum_string2 import EnumString2 from petstore_api.models.enum_test import EnumTest +from petstore_api.models.feeding import Feeding from petstore_api.models.file import File from petstore_api.models.file_schema_test_class import FileSchemaTestClass from petstore_api.models.first_ref import FirstRef @@ -80,6 +82,7 @@ from petstore_api.models.parent_with_optional_dict import ParentWithOptionalDict from petstore_api.models.pet import Pet from petstore_api.models.pig import Pig +from petstore_api.models.poop_cleaning import PoopCleaning from petstore_api.models.property_name_collision import PropertyNameCollision from petstore_api.models.read_only_first import ReadOnlyFirst from petstore_api.models.second_ref import SecondRef @@ -89,6 +92,8 @@ from petstore_api.models.special_model_name import SpecialModelName from petstore_api.models.special_name import SpecialName from petstore_api.models.tag import Tag +from petstore_api.models.task import Task +from petstore_api.models.task_activity import TaskActivity from petstore_api.models.test_error_responses_with_model400_response import TestErrorResponsesWithModel400Response from petstore_api.models.test_error_responses_with_model404_response import TestErrorResponsesWithModel404Response from petstore_api.models.test_inline_freeform_additional_properties_request import TestInlineFreeformAdditionalPropertiesRequest diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/bathing.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/bathing.py new file mode 100644 index 000000000000..09bb3b7a0385 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/bathing.py @@ -0,0 +1,101 @@ +# 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 +from pydantic import BaseModel, Field, StrictStr, validator + +class Bathing(BaseModel): + """ + Bathing + """ + task_name: StrictStr = Field(...) + function_name: StrictStr = Field(...) + content: StrictStr = Field(...) + additional_properties: Dict[str, Any] = {} + __properties = ["task_name", "function_name", "content"] + + @validator('task_name') + def task_name_validate_enum(cls, value): + """Validates the enum""" + if value not in ('cleaning_deep'): + raise ValueError("must be one of enum values ('cleaning_deep')") + return value + + @validator('function_name') + def function_name_validate_enum(cls, value): + """Validates the enum""" + if value not in ('care_nourish'): + raise ValueError("must be one of enum values ('care_nourish')") + return value + + 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) -> Bathing: + """Create an instance of Bathing 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) -> Bathing: + """Create an instance of Bathing from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return Bathing.parse_obj(obj) + + _obj = Bathing.parse_obj({ + "task_name": obj.get("task_name"), + "function_name": obj.get("function_name"), + "content": obj.get("content") + }) + # 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/petstore_api/models/feeding.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/feeding.py new file mode 100644 index 000000000000..9afe7dce1b4f --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/feeding.py @@ -0,0 +1,101 @@ +# 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 +from pydantic import BaseModel, Field, StrictStr, validator + +class Feeding(BaseModel): + """ + Feeding + """ + task_name: StrictStr = Field(...) + function_name: StrictStr = Field(...) + content: StrictStr = Field(...) + additional_properties: Dict[str, Any] = {} + __properties = ["task_name", "function_name", "content"] + + @validator('task_name') + def task_name_validate_enum(cls, value): + """Validates the enum""" + if value not in ('cleaning'): + raise ValueError("must be one of enum values ('cleaning')") + return value + + @validator('function_name') + def function_name_validate_enum(cls, value): + """Validates the enum""" + if value not in ('care_nourish'): + raise ValueError("must be one of enum values ('care_nourish')") + return value + + 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) -> Feeding: + """Create an instance of Feeding 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) -> Feeding: + """Create an instance of Feeding from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return Feeding.parse_obj(obj) + + _obj = Feeding.parse_obj({ + "task_name": obj.get("task_name"), + "function_name": obj.get("function_name"), + "content": obj.get("content") + }) + # 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/petstore_api/models/poop_cleaning.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/poop_cleaning.py new file mode 100644 index 000000000000..5649822e4f20 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/poop_cleaning.py @@ -0,0 +1,101 @@ +# 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 +from pydantic import BaseModel, Field, StrictStr, validator + +class PoopCleaning(BaseModel): + """ + PoopCleaning + """ + task_name: StrictStr = Field(...) + function_name: StrictStr = Field(...) + content: StrictStr = Field(...) + additional_properties: Dict[str, Any] = {} + __properties = ["task_name", "function_name", "content"] + + @validator('task_name') + def task_name_validate_enum(cls, value): + """Validates the enum""" + if value not in ('cleaning'): + raise ValueError("must be one of enum values ('cleaning')") + return value + + @validator('function_name') + def function_name_validate_enum(cls, value): + """Validates the enum""" + if value not in ('care'): + raise ValueError("must be one of enum values ('care')") + return value + + 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) -> PoopCleaning: + """Create an instance of PoopCleaning 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) -> PoopCleaning: + """Create an instance of PoopCleaning from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return PoopCleaning.parse_obj(obj) + + _obj = PoopCleaning.parse_obj({ + "task_name": obj.get("task_name"), + "function_name": obj.get("function_name"), + "content": obj.get("content") + }) + # 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/petstore_api/models/task.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/task.py new file mode 100644 index 000000000000..3bcc9d0c3f22 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/task.py @@ -0,0 +1,89 @@ +# 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 +from pydantic import BaseModel, Field, StrictStr +from petstore_api.models.task_activity import TaskActivity + +class Task(BaseModel): + """ + Used to test oneOf enums with only one string value. # noqa: E501 + """ + id: StrictStr = Field(...) + activity: TaskActivity = Field(...) + additional_properties: Dict[str, Any] = {} + __properties = ["id", "activity"] + + 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) -> Task: + """Create an instance of Task 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) + # override the default output from pydantic by calling `to_dict()` of activity + if self.activity: + _dict['activity'] = self.activity.to_dict() + # 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) -> Task: + """Create an instance of Task from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return Task.parse_obj(obj) + + _obj = Task.parse_obj({ + "id": obj.get("id"), + "activity": TaskActivity.from_dict(obj.get("activity")) if obj.get("activity") is not None else None + }) + # 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/petstore_api/models/task_activity.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/task_activity.py new file mode 100644 index 000000000000..70553f1ef202 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/task_activity.py @@ -0,0 +1,155 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +from inspect import getfullargspec +import json +import pprint +import re # noqa: F401 + +from typing import Any, List, Optional +from pydantic import BaseModel, Field, StrictStr, ValidationError, validator +from petstore_api.models.bathing import Bathing +from petstore_api.models.feeding import Feeding +from petstore_api.models.poop_cleaning import PoopCleaning +from typing import Union, Any, List, TYPE_CHECKING +from pydantic import StrictStr, Field + +TASKACTIVITY_ONE_OF_SCHEMAS = ["Bathing", "Feeding", "PoopCleaning"] + +class TaskActivity(BaseModel): + """ + TaskActivity + """ + # data type: PoopCleaning + oneof_schema_1_validator: Optional[PoopCleaning] = None + # data type: Feeding + oneof_schema_2_validator: Optional[Feeding] = None + # data type: Bathing + oneof_schema_3_validator: Optional[Bathing] = None + if TYPE_CHECKING: + actual_instance: Union[Bathing, Feeding, PoopCleaning] + else: + actual_instance: Any + one_of_schemas: List[str] = Field(TASKACTIVITY_ONE_OF_SCHEMAS, const=True) + + class Config: + validate_assignment = True + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = TaskActivity.construct() + error_messages = [] + match = 0 + # validate data type: PoopCleaning + if not isinstance(v, PoopCleaning): + error_messages.append(f"Error! Input type `{type(v)}` is not `PoopCleaning`") + else: + match += 1 + # validate data type: Feeding + if not isinstance(v, Feeding): + error_messages.append(f"Error! Input type `{type(v)}` is not `Feeding`") + else: + match += 1 + # validate data type: Bathing + if not isinstance(v, Bathing): + error_messages.append(f"Error! Input type `{type(v)}` is not `Bathing`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in TaskActivity with oneOf schemas: Bathing, Feeding, PoopCleaning. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in TaskActivity with oneOf schemas: Bathing, Feeding, PoopCleaning. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: dict) -> TaskActivity: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> TaskActivity: + """Returns the object represented by the json string""" + instance = TaskActivity.construct() + error_messages = [] + match = 0 + + # deserialize data into PoopCleaning + try: + instance.actual_instance = PoopCleaning.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into Feeding + try: + instance.actual_instance = Feeding.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into Bathing + try: + instance.actual_instance = Bathing.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into TaskActivity with oneOf schemas: Bathing, Feeding, PoopCleaning. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into TaskActivity with oneOf schemas: Bathing, Feeding, PoopCleaning. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + to_json = getattr(self.actual_instance, "to_json", None) + if callable(to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> dict: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + to_dict = getattr(self.actual_instance, "to_dict", None) + if callable(to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.dict()) + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/test/test_bathing.py b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_bathing.py new file mode 100644 index 000000000000..cc3a79b6f412 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_bathing.py @@ -0,0 +1,57 @@ +# 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.bathing import Bathing # noqa: E501 + +class TestBathing(unittest.TestCase): + """Bathing unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Bathing: + """Test Bathing + 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 `Bathing` + """ + model = Bathing() # noqa: E501 + if include_optional: + return Bathing( + task_name = 'cleaning_deep', + function_name = 'care_nourish', + content = '' + ) + else: + return Bathing( + task_name = 'cleaning_deep', + function_name = 'care_nourish', + content = '', + ) + """ + + def testBathing(self): + """Test Bathing""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/test/test_feeding.py b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_feeding.py new file mode 100644 index 000000000000..f445dc67c1b8 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_feeding.py @@ -0,0 +1,57 @@ +# 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.feeding import Feeding # noqa: E501 + +class TestFeeding(unittest.TestCase): + """Feeding unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Feeding: + """Test Feeding + 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 `Feeding` + """ + model = Feeding() # noqa: E501 + if include_optional: + return Feeding( + task_name = 'cleaning', + function_name = 'care_nourish', + content = '' + ) + else: + return Feeding( + task_name = 'cleaning', + function_name = 'care_nourish', + content = '', + ) + """ + + def testFeeding(self): + """Test Feeding""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/test/test_poop_cleaning.py b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_poop_cleaning.py new file mode 100644 index 000000000000..e2594e920fa0 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_poop_cleaning.py @@ -0,0 +1,57 @@ +# 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.poop_cleaning import PoopCleaning # noqa: E501 + +class TestPoopCleaning(unittest.TestCase): + """PoopCleaning unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> PoopCleaning: + """Test PoopCleaning + 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 `PoopCleaning` + """ + model = PoopCleaning() # noqa: E501 + if include_optional: + return PoopCleaning( + task_name = 'cleaning', + function_name = 'care', + content = '' + ) + else: + return PoopCleaning( + task_name = 'cleaning', + function_name = 'care', + content = '', + ) + """ + + def testPoopCleaning(self): + """Test PoopCleaning""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/test/test_task.py b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_task.py new file mode 100644 index 000000000000..8e510333d7dd --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_task.py @@ -0,0 +1,55 @@ +# 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.task import Task # noqa: E501 + +class TestTask(unittest.TestCase): + """Task unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Task: + """Test Task + 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 `Task` + """ + model = Task() # noqa: E501 + if include_optional: + return Task( + id = '', + activity = None + ) + else: + return Task( + id = '', + activity = None, + ) + """ + + def testTask(self): + """Test Task""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/test/test_task_activity.py b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_task_activity.py new file mode 100644 index 000000000000..b09dc360824b --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_task_activity.py @@ -0,0 +1,57 @@ +# 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.task_activity import TaskActivity # noqa: E501 + +class TestTaskActivity(unittest.TestCase): + """TaskActivity unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TaskActivity: + """Test TaskActivity + 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 `TaskActivity` + """ + model = TaskActivity() # noqa: E501 + if include_optional: + return TaskActivity( + task_name = 'cleaning_deep', + function_name = 'care_nourish', + content = '' + ) + else: + return TaskActivity( + task_name = 'cleaning_deep', + function_name = 'care_nourish', + content = '', + ) + """ + + def testTaskActivity(self): + """Test TaskActivity""" + # 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 b85011e97909..b262850d70c5 100755 --- a/samples/openapi3/client/petstore/python/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python/.openapi-generator/FILES @@ -17,6 +17,7 @@ docs/ArrayOfArrayOfNumberOnly.md docs/ArrayOfNumberOnly.md docs/ArrayTest.md docs/BasquePig.md +docs/Bathing.md docs/Capitalization.md docs/Cat.md docs/Category.md @@ -38,6 +39,7 @@ docs/EnumString2.md docs/EnumTest.md docs/FakeApi.md docs/FakeClassnameTags123Api.md +docs/Feeding.md docs/File.md docs/FileSchemaTestClass.md docs/FirstRef.md @@ -74,6 +76,7 @@ docs/ParentWithOptionalDict.md docs/Pet.md docs/PetApi.md docs/Pig.md +docs/PoopCleaning.md docs/PropertyNameCollision.md docs/ReadOnlyFirst.md docs/SecondRef.md @@ -84,6 +87,8 @@ docs/SpecialModelName.md docs/SpecialName.md docs/StoreApi.md docs/Tag.md +docs/Task.md +docs/TaskActivity.md docs/TestErrorResponsesWithModel400Response.md docs/TestErrorResponsesWithModel404Response.md docs/TestInlineFreeformAdditionalPropertiesRequest.md @@ -121,6 +126,7 @@ petstore_api/models/array_of_array_of_number_only.py petstore_api/models/array_of_number_only.py petstore_api/models/array_test.py petstore_api/models/basque_pig.py +petstore_api/models/bathing.py petstore_api/models/capitalization.py petstore_api/models/cat.py petstore_api/models/category.py @@ -139,6 +145,7 @@ petstore_api/models/enum_class.py petstore_api/models/enum_string1.py petstore_api/models/enum_string2.py petstore_api/models/enum_test.py +petstore_api/models/feeding.py petstore_api/models/file.py petstore_api/models/file_schema_test_class.py petstore_api/models/first_ref.py @@ -174,6 +181,7 @@ petstore_api/models/parent.py petstore_api/models/parent_with_optional_dict.py petstore_api/models/pet.py petstore_api/models/pig.py +petstore_api/models/poop_cleaning.py petstore_api/models/property_name_collision.py petstore_api/models/read_only_first.py petstore_api/models/second_ref.py @@ -183,6 +191,8 @@ petstore_api/models/special_character_enum.py petstore_api/models/special_model_name.py petstore_api/models/special_name.py petstore_api/models/tag.py +petstore_api/models/task.py +petstore_api/models/task_activity.py petstore_api/models/test_error_responses_with_model400_response.py petstore_api/models/test_error_responses_with_model404_response.py petstore_api/models/test_inline_freeform_additional_properties_request.py diff --git a/samples/openapi3/client/petstore/python/README.md b/samples/openapi3/client/petstore/python/README.md index 07f3cb8623c6..605c380c8099 100755 --- a/samples/openapi3/client/petstore/python/README.md +++ b/samples/openapi3/client/petstore/python/README.md @@ -152,6 +152,7 @@ Class | Method | HTTP request | Description - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) - [ArrayTest](docs/ArrayTest.md) - [BasquePig](docs/BasquePig.md) + - [Bathing](docs/Bathing.md) - [Capitalization](docs/Capitalization.md) - [Cat](docs/Cat.md) - [Category](docs/Category.md) @@ -170,6 +171,7 @@ Class | Method | HTTP request | Description - [EnumString1](docs/EnumString1.md) - [EnumString2](docs/EnumString2.md) - [EnumTest](docs/EnumTest.md) + - [Feeding](docs/Feeding.md) - [File](docs/File.md) - [FileSchemaTestClass](docs/FileSchemaTestClass.md) - [FirstRef](docs/FirstRef.md) @@ -205,6 +207,7 @@ Class | Method | HTTP request | Description - [ParentWithOptionalDict](docs/ParentWithOptionalDict.md) - [Pet](docs/Pet.md) - [Pig](docs/Pig.md) + - [PoopCleaning](docs/PoopCleaning.md) - [PropertyNameCollision](docs/PropertyNameCollision.md) - [ReadOnlyFirst](docs/ReadOnlyFirst.md) - [SecondRef](docs/SecondRef.md) @@ -214,6 +217,8 @@ Class | Method | HTTP request | Description - [SpecialModelName](docs/SpecialModelName.md) - [SpecialName](docs/SpecialName.md) - [Tag](docs/Tag.md) + - [Task](docs/Task.md) + - [TaskActivity](docs/TaskActivity.md) - [TestErrorResponsesWithModel400Response](docs/TestErrorResponsesWithModel400Response.md) - [TestErrorResponsesWithModel404Response](docs/TestErrorResponsesWithModel404Response.md) - [TestInlineFreeformAdditionalPropertiesRequest](docs/TestInlineFreeformAdditionalPropertiesRequest.md) diff --git a/samples/openapi3/client/petstore/python/docs/Bathing.md b/samples/openapi3/client/petstore/python/docs/Bathing.md new file mode 100644 index 000000000000..4c4963bf5934 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/Bathing.md @@ -0,0 +1,31 @@ +# Bathing + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**task_name** | **str** | | +**function_name** | **str** | | +**content** | **str** | | + +## Example + +```python +from petstore_api.models.bathing import Bathing + +# TODO update the JSON string below +json = "{}" +# create an instance of Bathing from a JSON string +bathing_instance = Bathing.from_json(json) +# print the JSON string representation of the object +print Bathing.to_json() + +# convert the object into a dict +bathing_dict = bathing_instance.to_dict() +# create an instance of Bathing from a dict +bathing_form_dict = bathing.from_dict(bathing_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python/docs/Feeding.md b/samples/openapi3/client/petstore/python/docs/Feeding.md new file mode 100644 index 000000000000..f0d51f621c29 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/Feeding.md @@ -0,0 +1,31 @@ +# Feeding + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**task_name** | **str** | | +**function_name** | **str** | | +**content** | **str** | | + +## Example + +```python +from petstore_api.models.feeding import Feeding + +# TODO update the JSON string below +json = "{}" +# create an instance of Feeding from a JSON string +feeding_instance = Feeding.from_json(json) +# print the JSON string representation of the object +print Feeding.to_json() + +# convert the object into a dict +feeding_dict = feeding_instance.to_dict() +# create an instance of Feeding from a dict +feeding_form_dict = feeding.from_dict(feeding_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python/docs/PoopCleaning.md b/samples/openapi3/client/petstore/python/docs/PoopCleaning.md new file mode 100644 index 000000000000..9fd6b0c32451 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/PoopCleaning.md @@ -0,0 +1,31 @@ +# PoopCleaning + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**task_name** | **str** | | +**function_name** | **str** | | +**content** | **str** | | + +## Example + +```python +from petstore_api.models.poop_cleaning import PoopCleaning + +# TODO update the JSON string below +json = "{}" +# create an instance of PoopCleaning from a JSON string +poop_cleaning_instance = PoopCleaning.from_json(json) +# print the JSON string representation of the object +print PoopCleaning.to_json() + +# convert the object into a dict +poop_cleaning_dict = poop_cleaning_instance.to_dict() +# create an instance of PoopCleaning from a dict +poop_cleaning_form_dict = poop_cleaning.from_dict(poop_cleaning_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python/docs/Task.md b/samples/openapi3/client/petstore/python/docs/Task.md new file mode 100644 index 000000000000..6cee08c6fe61 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/Task.md @@ -0,0 +1,31 @@ +# Task + +Used to test oneOf enums with only one string value. + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **str** | | +**activity** | [**TaskActivity**](TaskActivity.md) | | + +## Example + +```python +from petstore_api.models.task import Task + +# TODO update the JSON string below +json = "{}" +# create an instance of Task from a JSON string +task_instance = Task.from_json(json) +# print the JSON string representation of the object +print Task.to_json() + +# convert the object into a dict +task_dict = task_instance.to_dict() +# create an instance of Task from a dict +task_form_dict = task.from_dict(task_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python/docs/TaskActivity.md b/samples/openapi3/client/petstore/python/docs/TaskActivity.md new file mode 100644 index 000000000000..37f10f9031ec --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/TaskActivity.md @@ -0,0 +1,31 @@ +# TaskActivity + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**task_name** | **str** | | +**function_name** | **str** | | +**content** | **str** | | + +## Example + +```python +from petstore_api.models.task_activity import TaskActivity + +# TODO update the JSON string below +json = "{}" +# create an instance of TaskActivity from a JSON string +task_activity_instance = TaskActivity.from_json(json) +# print the JSON string representation of the object +print TaskActivity.to_json() + +# convert the object into a dict +task_activity_dict = task_activity_instance.to_dict() +# create an instance of TaskActivity from a dict +task_activity_form_dict = task_activity.from_dict(task_activity_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 f791bc531127..704dcbaffbd6 100755 --- a/samples/openapi3/client/petstore/python/petstore_api/__init__.py +++ b/samples/openapi3/client/petstore/python/petstore_api/__init__.py @@ -51,6 +51,7 @@ from petstore_api.models.array_of_number_only import ArrayOfNumberOnly from petstore_api.models.array_test import ArrayTest from petstore_api.models.basque_pig import BasquePig +from petstore_api.models.bathing import Bathing from petstore_api.models.capitalization import Capitalization from petstore_api.models.cat import Cat from petstore_api.models.category import Category @@ -69,6 +70,7 @@ from petstore_api.models.enum_string1 import EnumString1 from petstore_api.models.enum_string2 import EnumString2 from petstore_api.models.enum_test import EnumTest +from petstore_api.models.feeding import Feeding from petstore_api.models.file import File from petstore_api.models.file_schema_test_class import FileSchemaTestClass from petstore_api.models.first_ref import FirstRef @@ -104,6 +106,7 @@ from petstore_api.models.parent_with_optional_dict import ParentWithOptionalDict from petstore_api.models.pet import Pet from petstore_api.models.pig import Pig +from petstore_api.models.poop_cleaning import PoopCleaning from petstore_api.models.property_name_collision import PropertyNameCollision from petstore_api.models.read_only_first import ReadOnlyFirst from petstore_api.models.second_ref import SecondRef @@ -113,6 +116,8 @@ from petstore_api.models.special_model_name import SpecialModelName from petstore_api.models.special_name import SpecialName from petstore_api.models.tag import Tag +from petstore_api.models.task import Task +from petstore_api.models.task_activity import TaskActivity from petstore_api.models.test_error_responses_with_model400_response import TestErrorResponsesWithModel400Response from petstore_api.models.test_error_responses_with_model404_response import TestErrorResponsesWithModel404Response from petstore_api.models.test_inline_freeform_additional_properties_request import TestInlineFreeformAdditionalPropertiesRequest 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 945dd198de1a..554f557cb05a 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py @@ -27,6 +27,7 @@ from petstore_api.models.array_of_number_only import ArrayOfNumberOnly from petstore_api.models.array_test import ArrayTest from petstore_api.models.basque_pig import BasquePig +from petstore_api.models.bathing import Bathing from petstore_api.models.capitalization import Capitalization from petstore_api.models.cat import Cat from petstore_api.models.category import Category @@ -45,6 +46,7 @@ from petstore_api.models.enum_string1 import EnumString1 from petstore_api.models.enum_string2 import EnumString2 from petstore_api.models.enum_test import EnumTest +from petstore_api.models.feeding import Feeding from petstore_api.models.file import File from petstore_api.models.file_schema_test_class import FileSchemaTestClass from petstore_api.models.first_ref import FirstRef @@ -80,6 +82,7 @@ from petstore_api.models.parent_with_optional_dict import ParentWithOptionalDict from petstore_api.models.pet import Pet from petstore_api.models.pig import Pig +from petstore_api.models.poop_cleaning import PoopCleaning from petstore_api.models.property_name_collision import PropertyNameCollision from petstore_api.models.read_only_first import ReadOnlyFirst from petstore_api.models.second_ref import SecondRef @@ -89,6 +92,8 @@ from petstore_api.models.special_model_name import SpecialModelName from petstore_api.models.special_name import SpecialName from petstore_api.models.tag import Tag +from petstore_api.models.task import Task +from petstore_api.models.task_activity import TaskActivity from petstore_api.models.test_error_responses_with_model400_response import TestErrorResponsesWithModel400Response from petstore_api.models.test_error_responses_with_model404_response import TestErrorResponsesWithModel404Response from petstore_api.models.test_inline_freeform_additional_properties_request import TestInlineFreeformAdditionalPropertiesRequest diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/bathing.py b/samples/openapi3/client/petstore/python/petstore_api/models/bathing.py new file mode 100644 index 000000000000..7ea7084ae9db --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/models/bathing.py @@ -0,0 +1,118 @@ +# 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, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class Bathing(BaseModel): + """ + Bathing + """ # noqa: E501 + task_name: StrictStr + function_name: StrictStr + content: StrictStr + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["task_name", "function_name", "content"] + + @field_validator('task_name') + def task_name_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['cleaning_deep']): + raise ValueError("must be one of enum values ('cleaning_deep')") + return value + + @field_validator('function_name') + def function_name_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['care_nourish']): + raise ValueError("must be one of enum values ('care_nourish')") + return value + + model_config = { + "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 Bathing 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 Bathing from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "task_name": obj.get("task_name"), + "function_name": obj.get("function_name"), + "content": obj.get("content") + }) + # 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/petstore_api/models/enum_arrays.py b/samples/openapi3/client/petstore/python/petstore_api/models/enum_arrays.py index 378abbf93c6d..bd46be86ea60 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/enum_arrays.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/enum_arrays.py @@ -37,7 +37,7 @@ def just_symbol_validate_enum(cls, value): if value is None: return value - if value not in ('>=', '$'): + if value not in set(['>=', '$']): raise ValueError("must be one of enum values ('>=', '$')") return value @@ -48,7 +48,7 @@ def array_enum_validate_enum(cls, value): return value for i in value: - if i not in ('fish', 'crab'): + if i not in set(['fish', 'crab']): raise ValueError("each list item must be one of ('fish', 'crab')") return value diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/enum_test.py b/samples/openapi3/client/petstore/python/petstore_api/models/enum_test.py index 835d3da23303..a3d6f6fc9cc4 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/enum_test.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/enum_test.py @@ -48,14 +48,14 @@ def enum_string_validate_enum(cls, value): if value is None: return value - if value not in ('UPPER', 'lower', ''): + if value not in set(['UPPER', 'lower', '']): raise ValueError("must be one of enum values ('UPPER', 'lower', '')") return value @field_validator('enum_string_required') def enum_string_required_validate_enum(cls, value): """Validates the enum""" - if value not in ('UPPER', 'lower', ''): + if value not in set(['UPPER', 'lower', '']): raise ValueError("must be one of enum values ('UPPER', 'lower', '')") return value @@ -65,7 +65,7 @@ def enum_integer_default_validate_enum(cls, value): if value is None: return value - if value not in (1, 5, 14): + if value not in set([1, 5, 14]): raise ValueError("must be one of enum values (1, 5, 14)") return value @@ -75,7 +75,7 @@ def enum_integer_validate_enum(cls, value): if value is None: return value - if value not in (1, -1): + if value not in set([1, -1]): raise ValueError("must be one of enum values (1, -1)") return value @@ -85,7 +85,7 @@ def enum_number_validate_enum(cls, value): if value is None: return value - if value not in (1.1, -1.2): + if value not in set([1.1, -1.2]): raise ValueError("must be one of enum values (1.1, -1.2)") return value diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/feeding.py b/samples/openapi3/client/petstore/python/petstore_api/models/feeding.py new file mode 100644 index 000000000000..e09b83a21b09 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/models/feeding.py @@ -0,0 +1,118 @@ +# 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, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class Feeding(BaseModel): + """ + Feeding + """ # noqa: E501 + task_name: StrictStr + function_name: StrictStr + content: StrictStr + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["task_name", "function_name", "content"] + + @field_validator('task_name') + def task_name_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['cleaning']): + raise ValueError("must be one of enum values ('cleaning')") + return value + + @field_validator('function_name') + def function_name_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['care_nourish']): + raise ValueError("must be one of enum values ('care_nourish')") + return value + + model_config = { + "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 Feeding 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 Feeding from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "task_name": obj.get("task_name"), + "function_name": obj.get("function_name"), + "content": obj.get("content") + }) + # 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/petstore_api/models/map_test.py b/samples/openapi3/client/petstore/python/petstore_api/models/map_test.py index 3912fd9d66ee..711379c0f16d 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/map_test.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/map_test.py @@ -39,7 +39,7 @@ def map_of_enum_string_validate_enum(cls, value): if value is None: return value - if value not in ('UPPER', 'lower'): + if value not in set(['UPPER', 'lower']): raise ValueError("must be one of enum values ('UPPER', 'lower')") return value diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/order.py b/samples/openapi3/client/petstore/python/petstore_api/models/order.py index d9fa3d4e2f34..19a829bd92db 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/order.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/order.py @@ -42,7 +42,7 @@ def status_validate_enum(cls, value): if value is None: return value - if value not in ('placed', 'approved', 'delivered'): + if value not in set(['placed', 'approved', 'delivered']): raise ValueError("must be one of enum values ('placed', 'approved', 'delivered')") return value diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/pet.py b/samples/openapi3/client/petstore/python/petstore_api/models/pet.py index fe2bf02c789f..eca4a98dcc9a 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/pet.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/pet.py @@ -44,7 +44,7 @@ def status_validate_enum(cls, value): if value is None: return value - if value not in ('available', 'pending', 'sold'): + if value not in set(['available', 'pending', 'sold']): raise ValueError("must be one of enum values ('available', 'pending', 'sold')") return value diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/poop_cleaning.py b/samples/openapi3/client/petstore/python/petstore_api/models/poop_cleaning.py new file mode 100644 index 000000000000..7d881efcd21b --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/models/poop_cleaning.py @@ -0,0 +1,118 @@ +# 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, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class PoopCleaning(BaseModel): + """ + PoopCleaning + """ # noqa: E501 + task_name: StrictStr + function_name: StrictStr + content: StrictStr + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["task_name", "function_name", "content"] + + @field_validator('task_name') + def task_name_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['cleaning']): + raise ValueError("must be one of enum values ('cleaning')") + return value + + @field_validator('function_name') + def function_name_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['care']): + raise ValueError("must be one of enum values ('care')") + return value + + model_config = { + "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 PoopCleaning 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 PoopCleaning from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "task_name": obj.get("task_name"), + "function_name": obj.get("function_name"), + "content": obj.get("content") + }) + # 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/petstore_api/models/special_name.py b/samples/openapi3/client/petstore/python/petstore_api/models/special_name.py index 1322827d7ebf..8ab35951c1ae 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/special_name.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/special_name.py @@ -39,7 +39,7 @@ def var_schema_validate_enum(cls, value): if value is None: return value - if value not in ('available', 'pending', 'sold'): + if value not in set(['available', 'pending', 'sold']): raise ValueError("must be one of enum values ('available', 'pending', 'sold')") return value diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/task.py b/samples/openapi3/client/petstore/python/petstore_api/models/task.py new file mode 100644 index 000000000000..2a58ebaed92e --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/models/task.py @@ -0,0 +1,106 @@ +# 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, StrictStr +from typing import Any, ClassVar, Dict, List +from petstore_api.models.task_activity import TaskActivity +from typing import Optional, Set +from typing_extensions import Self + +class Task(BaseModel): + """ + Used to test oneOf enums with only one string value. + """ # noqa: E501 + id: StrictStr + activity: TaskActivity + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["id", "activity"] + + model_config = { + "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 Task 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, + ) + # override the default output from pydantic by calling `to_dict()` of activity + if self.activity: + _dict['activity'] = self.activity.to_dict() + # 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 Task from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "activity": TaskActivity.from_dict(obj["activity"]) if obj.get("activity") is not None else None + }) + # 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/petstore_api/models/task_activity.py b/samples/openapi3/client/petstore/python/petstore_api/models/task_activity.py new file mode 100644 index 000000000000..b76c2604597c --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/models/task_activity.py @@ -0,0 +1,151 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +import pprint +from pydantic import BaseModel, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional +from petstore_api.models.bathing import Bathing +from petstore_api.models.feeding import Feeding +from petstore_api.models.poop_cleaning import PoopCleaning +from pydantic import StrictStr, Field +from typing import Union, List, Optional, Dict +from typing_extensions import Literal, Self + +TASKACTIVITY_ONE_OF_SCHEMAS = ["Bathing", "Feeding", "PoopCleaning"] + +class TaskActivity(BaseModel): + """ + TaskActivity + """ + # data type: PoopCleaning + oneof_schema_1_validator: Optional[PoopCleaning] = None + # data type: Feeding + oneof_schema_2_validator: Optional[Feeding] = None + # data type: Bathing + oneof_schema_3_validator: Optional[Bathing] = None + actual_instance: Optional[Union[Bathing, Feeding, PoopCleaning]] = None + one_of_schemas: List[str] = Field(default=Literal["Bathing", "Feeding", "PoopCleaning"]) + + model_config = { + "validate_assignment": True, + "protected_namespaces": (), + } + + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @field_validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = TaskActivity.model_construct() + error_messages = [] + match = 0 + # validate data type: PoopCleaning + if not isinstance(v, PoopCleaning): + error_messages.append(f"Error! Input type `{type(v)}` is not `PoopCleaning`") + else: + match += 1 + # validate data type: Feeding + if not isinstance(v, Feeding): + error_messages.append(f"Error! Input type `{type(v)}` is not `Feeding`") + else: + match += 1 + # validate data type: Bathing + if not isinstance(v, Bathing): + error_messages.append(f"Error! Input type `{type(v)}` is not `Bathing`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in TaskActivity with oneOf schemas: Bathing, Feeding, PoopCleaning. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in TaskActivity with oneOf schemas: Bathing, Feeding, PoopCleaning. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + instance = cls.model_construct() + error_messages = [] + match = 0 + + # deserialize data into PoopCleaning + try: + instance.actual_instance = PoopCleaning.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into Feeding + try: + instance.actual_instance = Feeding.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into Bathing + try: + instance.actual_instance = Bathing.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into TaskActivity with oneOf schemas: Bathing, Feeding, PoopCleaning. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into TaskActivity with oneOf schemas: Bathing, Feeding, PoopCleaning. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> Optional[Union[Dict[str, Any], Bathing, Feeding, PoopCleaning]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.model_dump()) + + diff --git a/samples/openapi3/client/petstore/python/test/test_bathing.py b/samples/openapi3/client/petstore/python/test/test_bathing.py new file mode 100644 index 000000000000..583bdcbb09ec --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_bathing.py @@ -0,0 +1,57 @@ +# 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.bathing import Bathing + +class TestBathing(unittest.TestCase): + """Bathing unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Bathing: + """Test Bathing + 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 `Bathing` + """ + model = Bathing() + if include_optional: + return Bathing( + task_name = 'cleaning_deep', + function_name = 'care_nourish', + content = '' + ) + else: + return Bathing( + task_name = 'cleaning_deep', + function_name = 'care_nourish', + content = '', + ) + """ + + def testBathing(self): + """Test Bathing""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_feeding.py b/samples/openapi3/client/petstore/python/test/test_feeding.py new file mode 100644 index 000000000000..a0cdfc8f3460 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_feeding.py @@ -0,0 +1,57 @@ +# 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.feeding import Feeding + +class TestFeeding(unittest.TestCase): + """Feeding unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Feeding: + """Test Feeding + 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 `Feeding` + """ + model = Feeding() + if include_optional: + return Feeding( + task_name = 'cleaning', + function_name = 'care_nourish', + content = '' + ) + else: + return Feeding( + task_name = 'cleaning', + function_name = 'care_nourish', + content = '', + ) + """ + + def testFeeding(self): + """Test Feeding""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_poop_cleaning.py b/samples/openapi3/client/petstore/python/test/test_poop_cleaning.py new file mode 100644 index 000000000000..4c94fddca97a --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_poop_cleaning.py @@ -0,0 +1,57 @@ +# 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.poop_cleaning import PoopCleaning + +class TestPoopCleaning(unittest.TestCase): + """PoopCleaning unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> PoopCleaning: + """Test PoopCleaning + 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 `PoopCleaning` + """ + model = PoopCleaning() + if include_optional: + return PoopCleaning( + task_name = 'cleaning', + function_name = 'care', + content = '' + ) + else: + return PoopCleaning( + task_name = 'cleaning', + function_name = 'care', + content = '', + ) + """ + + def testPoopCleaning(self): + """Test PoopCleaning""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_task.py b/samples/openapi3/client/petstore/python/test/test_task.py new file mode 100644 index 000000000000..bbbc14a39928 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_task.py @@ -0,0 +1,55 @@ +# 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.task import Task + +class TestTask(unittest.TestCase): + """Task unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Task: + """Test Task + 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 `Task` + """ + model = Task() + if include_optional: + return Task( + id = '', + activity = None + ) + else: + return Task( + id = '', + activity = None, + ) + """ + + def testTask(self): + """Test Task""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_task_activity.py b/samples/openapi3/client/petstore/python/test/test_task_activity.py new file mode 100644 index 000000000000..2d56d9c5ad3e --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_task_activity.py @@ -0,0 +1,57 @@ +# 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.task_activity import TaskActivity + +class TestTaskActivity(unittest.TestCase): + """TaskActivity unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TaskActivity: + """Test TaskActivity + 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 `TaskActivity` + """ + model = TaskActivity() + if include_optional: + return TaskActivity( + task_name = 'cleaning_deep', + function_name = 'care_nourish', + content = '' + ) + else: + return TaskActivity( + task_name = 'cleaning_deep', + function_name = 'care_nourish', + content = '', + ) + """ + + def testTaskActivity(self): + """Test TaskActivity""" + # 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 4d3121c32ecbea85edc3ce3ccbb51379e377524a Mon Sep 17 00:00:00 2001 From: William Cheng Date: Wed, 31 Jan 2024 11:46:15 +0800 Subject: [PATCH 08/10] remove sonar workflow which works with jdk17+ only --- .github/workflows/sonar.yml | 26 -------------------------- 1 file changed, 26 deletions(-) delete mode 100644 .github/workflows/sonar.yml diff --git a/.github/workflows/sonar.yml b/.github/workflows/sonar.yml deleted file mode 100644 index 0fa6f44279cd..000000000000 --- a/.github/workflows/sonar.yml +++ /dev/null @@ -1,26 +0,0 @@ -name: Sonar CI -on: - push: - branches: - - master - - '[4-9]+.[0-9]+.x' - - sonar - -jobs: - build: - - runs-on: ubuntu-latest - if: ${{ github.repository_owner == 'OpenAPITools' }} - steps: - - uses: actions/checkout@v4 - - name: Set up JDK 11 - uses: actions/setup-java@v4 - with: - distribution: 'temurin' - java-version: 11 - - name: Compile with Maven - run: ./mvnw -B -q clean install jacoco:report - - name: Jacoco Aggregate - run: ./mvnw jacoco:report-aggregate - - name: Publish to Sonar - run: ./mvnw -B -q -nsu sonar:sonar -Dsonar.projectKey=OpenAPITools_openapi-generator -Dsonar.organization=openapitools -Dsonar.host.url=https://sonarcloud.io -Dsonar.login=${{ secrets.SONAR_LOGIN }} -Dsonar.branch.name=${GITHUB_REF##*/} From 2129b15c8f0598126a7a259106f7018bd302eef2 Mon Sep 17 00:00:00 2001 From: Robert Stoll Date: Wed, 31 Jan 2024 14:35:43 +0100 Subject: [PATCH 09/10] fix require var logging, don't matchGenerated if allOf skipped (#17746) --- .../src/main/java/org/openapitools/codegen/DefaultCodegen.java | 2 +- .../main/java/org/openapitools/codegen/InlineModelResolver.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java index 2f2fdb16183f..9a9da0173b4e 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java @@ -3753,7 +3753,7 @@ protected void addProperties(Map properties, List requir for (String r : required) { if (!properties.containsKey(r)) { - LOGGER.error("Required var %s not in properties", r); + LOGGER.error("Required var {} not in properties", r); } } return; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/InlineModelResolver.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/InlineModelResolver.java index 486eb32a1e0a..9049bfc4bdae 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/InlineModelResolver.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/InlineModelResolver.java @@ -612,8 +612,8 @@ private void flattenComposedChildren(String key, List children, boolean Schema innerModel = modelFromProperty(openAPI, component, innerModelName); // Recurse to create $refs for inner models gatherInlineModels(innerModel, innerModelName); - String existing = matchGenerated(innerModel); if (!skipAllOfInlineSchemas) { + String existing = matchGenerated(innerModel); if (existing == null) { innerModelName = addSchemas(innerModelName, innerModel); Schema schema = new Schema().$ref(innerModelName); From 7c7634dda95eeb015e3a64375abf124f9031fecd Mon Sep 17 00:00:00 2001 From: William Cheng Date: Thu, 1 Feb 2024 17:21:49 +0800 Subject: [PATCH 10/10] add operation id option (#17750) --- bin/configs/java-okhttp-gson.yaml | 3 + docs/customization.md | 7 + .../openapitools/codegen/cmd/ConfigHelp.java | 15 ++ .../openapitools/codegen/cmd/Generate.java | 8 + .../codegen/config/GeneratorSettings.java | 45 ++++ .../OpenApiGeneratorGenerateExtension.kt | 5 + .../gradle/plugin/tasks/GenerateTask.kt | 13 + .../codegen/plugin/CodeGenMojo.java | 11 + .../openapitools/codegen/CodegenConfig.java | 2 + .../openapitools/codegen/DefaultCodegen.java | 13 +- .../codegen/config/CodegenConfigurator.java | 17 ++ .../config/CodegenConfiguratorUtils.java | 13 + .../petstore/java/okhttp-gson/README.md | 4 +- .../petstore/java/okhttp-gson/docs/FakeApi.md | 126 ++++----- .../org/openapitools/client/api/FakeApi.java | 246 +++++++++--------- .../openapitools/client/api/FakeApiTest.java | 197 +++++++------- 16 files changed, 448 insertions(+), 277 deletions(-) diff --git a/bin/configs/java-okhttp-gson.yaml b/bin/configs/java-okhttp-gson.yaml index d3def489a5cd..8b402a580a80 100644 --- a/bin/configs/java-okhttp-gson.yaml +++ b/bin/configs/java-okhttp-gson.yaml @@ -17,3 +17,6 @@ additionalProperties: enumNameMappings: s: LOWER_CASE_S S: UPPER_CASE_S +operationIdNameMappings: + getArrayOfEnums: getFakeArrayofenums + fakeHealthGet: getFakeHealth diff --git a/docs/customization.md b/docs/customization.md index 6b00ae907d52..8e85645773b4 100644 --- a/docs/customization.md +++ b/docs/customization.md @@ -436,6 +436,13 @@ Not all generators support thess features yet. Please give it a try to confirm t NOTE: some generators use `baseName` (original name obtained direclty from OpenAPI spec, e.g. `shipping-date`) mustache tag in the templates so the mapping feature won't work. +To map `operationId` (used in method naming) to something else, use `operationIdNameMappings` option, e.g. + +```sh +java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generate -g java -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -o /tmp/java/ --operation-id-name-mappings getPetById=returnPetById +``` +will name the API method as `returnPetById` instead of `getPetById` obtained from OpenAPI doc/spec. + ## Schema Mapping One can map the schema to something else (e.g. external objects/models outside of the package) using the `schemaMappings` option, e.g. in CLI diff --git a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/ConfigHelp.java b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/ConfigHelp.java index 070ae689611e..32e5032d3ba9 100644 --- a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/ConfigHelp.java +++ b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/ConfigHelp.java @@ -92,6 +92,9 @@ public class ConfigHelp extends OpenApiGeneratorCommand { @Option(name = {"--enum-name-mappings"}, title = "enum name mappings", description = "displays the enum name mappings (none)") private Boolean enumNameMappings; + @Option(name = {"--operation-id-name-mappings"}, title = "operation id name mappings", description = "displays the operation id name mappings (none)") + private Boolean operationIdNameMappings; + @Option(name = {"--openapi-normalizer"}, title = "openapi normalizer rules", description = "displays the OpenAPI normalizer rules (none)") private Boolean openapiNormalizer; @@ -560,6 +563,18 @@ private void generatePlainTextHelp(StringBuilder sb, CodegenConfig config) { sb.append(newline); } + if (Boolean.TRUE.equals(operationIdNameMappings)) { + sb.append(newline).append("OPERATION ID MAPPING").append(newline).append(newline); + Map map = config.operationIdNameMapping() + .entrySet() + .stream() + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> { + throw new IllegalStateException(String.format(Locale.ROOT, "Duplicated options! %s and %s", a, b)); + }, TreeMap::new)); + writePlainTextFromMap(sb, map, optIndent, optNestedIndent, "operation id name", "Mapped to"); + sb.append(newline); + } + if (Boolean.TRUE.equals(openapiNormalizer)) { sb.append(newline).append("OPENAPI NORMALIZER RULES").append(newline).append(newline); Map map = config.openapiNormalizer() diff --git a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Generate.java b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Generate.java index 963b626269c6..0f9ec680e1c6 100644 --- a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Generate.java +++ b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Generate.java @@ -223,6 +223,13 @@ public class Generate extends OpenApiGeneratorCommand { + " You can also have multiple occurrences of this option.") private List enumNameMappings = new ArrayList<>(); + @Option( + name = {"--operation-id-name-mappings"}, + title = "operation id name mappings", + description = "specifies mappings between the operation id name and the new name in the format of operation_id_name=AnotherName,operation_id_name2=OtherName2." + + " You can also have multiple occurrences of this option.") + private List operationIdNameMappings = new ArrayList<>(); + @Option( name = {"--openapi-normalizer"}, title = "OpenAPI normalizer rules", @@ -507,6 +514,7 @@ public void execute() { applyParameterNameMappingsKvpList(parameterNameMappings, configurator); applyModelNameMappingsKvpList(modelNameMappings, configurator); applyEnumNameMappingsKvpList(enumNameMappings, configurator); + applyOperationIdNameMappingsKvpList(operationIdNameMappings, configurator); applyOpenAPINormalizerKvpList(openapiNormalizer, configurator); applyTypeMappingsKvpList(typeMappings, configurator); applyAdditionalPropertiesKvpList(additionalProperties, configurator); diff --git a/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/config/GeneratorSettings.java b/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/config/GeneratorSettings.java index 5ba28f278c8b..1f7e9e824a4c 100644 --- a/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/config/GeneratorSettings.java +++ b/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/config/GeneratorSettings.java @@ -57,6 +57,7 @@ public final class GeneratorSettings implements Serializable { private final Map parameterNameMappings; private final Map modelNameMappings; private final Map enumNameMappings; + private final Map operationIdNameMappings; private final Map openapiNormalizer; private final Set languageSpecificPrimitives; private final Set openapiGeneratorIgnoreList; @@ -306,6 +307,15 @@ public Map getEnumNameMappings() { return enumNameMappings; } + /** + * Gets operation id name mappings between an operation id name and the new name. + * + * @return the operation id name mappings + */ + public Map getOperationIdNameMappings() { + return operationIdNameMappings; + } + /** * Gets OpenAPI normalizer rules * @@ -446,6 +456,7 @@ private GeneratorSettings(Builder builder) { parameterNameMappings = Collections.unmodifiableMap(builder.parameterNameMappings); modelNameMappings = Collections.unmodifiableMap(builder.modelNameMappings); enumNameMappings = Collections.unmodifiableMap(builder.enumNameMappings); + operationIdNameMappings = Collections.unmodifiableMap(builder.operationIdNameMappings); openapiNormalizer = Collections.unmodifiableMap(builder.openapiNormalizer); languageSpecificPrimitives = Collections.unmodifiableSet(builder.languageSpecificPrimitives); openapiGeneratorIgnoreList = Collections.unmodifiableSet(builder.openapiGeneratorIgnoreList); @@ -525,6 +536,7 @@ public GeneratorSettings() { parameterNameMappings = Collections.unmodifiableMap(new HashMap<>(0)); modelNameMappings = Collections.unmodifiableMap(new HashMap<>(0)); enumNameMappings = Collections.unmodifiableMap(new HashMap<>(0)); + operationIdNameMappings = Collections.unmodifiableMap(new HashMap<>(0)); openapiNormalizer = Collections.unmodifiableMap(new HashMap<>(0)); languageSpecificPrimitives = Collections.unmodifiableSet(new HashSet<>(0)); openapiGeneratorIgnoreList = Collections.unmodifiableSet(new HashSet<>(0)); @@ -599,6 +611,9 @@ public static Builder newBuilder(GeneratorSettings copy) { if (copy.getEnumNameMappings() != null) { builder.enumNameMappings.putAll(copy.getEnumNameMappings()); } + if (copy.getOperationIdNameMappings() != null) { + builder.operationIdNameMappings.putAll(copy.getOperationIdNameMappings()); + } if (copy.getOpenAPINormalizer() != null) { builder.openapiNormalizer.putAll(copy.getOpenAPINormalizer()); } @@ -651,6 +666,7 @@ public static final class Builder { private Map parameterNameMappings; private Map modelNameMappings; private Map enumNameMappings; + private Map operationIdNameMappings; private Map openapiNormalizer; private Set languageSpecificPrimitives; private Set openapiGeneratorIgnoreList; @@ -677,6 +693,7 @@ public Builder() { parameterNameMappings = new HashMap<>(); modelNameMappings = new HashMap<>(); enumNameMappings = new HashMap<>(); + operationIdNameMappings = new HashMap<>(); openapiNormalizer = new HashMap<>(); languageSpecificPrimitives = new HashSet<>(); openapiGeneratorIgnoreList = new HashSet<>(); @@ -1103,6 +1120,32 @@ public Builder withEnumNameMapping(String key, String value) { return this; } + /** + * Sets the {@code operationIdNameMappings} and returns a reference to this Builder so that the methods can be chained together. + * + * @param operationIdNameMappings the {@code operationIdNameMappings} to set + * @return a reference to this Builder + */ + public Builder withOperationIdNameMappings(Map operationIdNameMappings) { + this.operationIdNameMappings = operationIdNameMappings; + return this; + } + + /** + * Sets a single {@code operationIdNameMappings} and returns a reference to this Builder so that the methods can be chained together. + * + * @param key A key for the name mapping + * @param value The value of name mapping + * @return a reference to this Builder + */ + public Builder withOperationIdNameMapping(String key, String value) { + if (this.operationIdNameMappings == null) { + this.operationIdNameMappings = new HashMap<>(); + } + this.operationIdNameMappings.put(key, value); + return this; + } + /** * Sets the {@code openapiNormalizer} and returns a reference to this Builder so that the methods can be chained together. * @@ -1346,6 +1389,7 @@ public boolean equals(Object o) { Objects.equals(getParameterNameMappings(), that.getParameterNameMappings()) && Objects.equals(getModelNameMappings(), that.getModelNameMappings()) && Objects.equals(getEnumNameMappings(), that.getEnumNameMappings()) && + Objects.equals(getOperationIdNameMappings(), that.getOperationIdNameMappings()) && Objects.equals(getOpenAPINormalizer(), that.getOpenAPINormalizer()) && Objects.equals(getLanguageSpecificPrimitives(), that.getLanguageSpecificPrimitives()) && Objects.equals(getOpenAPIGeneratorIgnoreList(), that.getOpenAPIGeneratorIgnoreList()) && @@ -1383,6 +1427,7 @@ public int hashCode() { getParameterNameMappings(), getModelNameMappings(), getEnumNameMappings(), + getOperationIdNameMappings(), getOpenAPINormalizer(), getLanguageSpecificPrimitives(), getOpenAPIGeneratorIgnoreList(), diff --git a/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/extensions/OpenApiGeneratorGenerateExtension.kt b/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/extensions/OpenApiGeneratorGenerateExtension.kt index 6270c8df6a3a..236453a87094 100644 --- a/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/extensions/OpenApiGeneratorGenerateExtension.kt +++ b/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/extensions/OpenApiGeneratorGenerateExtension.kt @@ -192,6 +192,11 @@ open class OpenApiGeneratorGenerateExtension(project: Project) { */ val enumNameMappings = project.objects.mapProperty() + /** + * Specifies mappings between an operation id name and the new name + */ + val operationIdNameMappings = project.objects.mapProperty() + /** * Specifies mappings (rules) in OpenAPI normalizer */ diff --git a/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/GenerateTask.kt b/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/GenerateTask.kt index 1d4cefb7ca19..7e0217a0501c 100644 --- a/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/GenerateTask.kt +++ b/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/GenerateTask.kt @@ -307,6 +307,13 @@ open class GenerateTask @Inject constructor(private val objectFactory: ObjectFac @Input val enumNameMappings = project.objects.mapProperty() + /** + * Specifies mappings between the operation id name and the new name + */ + @Optional + @Input + val operationIdNameMappings = project.objects.mapProperty() + /** * Specifies mappings (rules) in OpenAPI normalizer */ @@ -872,6 +879,12 @@ open class GenerateTask @Inject constructor(private val objectFactory: ObjectFac } } + if (operationIdNameMappings.isPresent) { + operationIdNameMappings.get().forEach { entry -> + configurator.addOperationIdNameMapping(entry.key, entry.value) + } + } + if (openapiNormalizer.isPresent) { openapiNormalizer.get().forEach { entry -> configurator.addOpenAPINormalizer(entry.key, entry.value) diff --git a/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java b/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java index b06aface93e7..4a7be458a9fb 100644 --- a/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java +++ b/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java @@ -356,6 +356,12 @@ public class CodeGenMojo extends AbstractMojo { @Parameter(name = "enumNameMappings", property = "openapi.generator.maven.plugin.enumNameMappings") private List enumNameMappings; + /** + * A map of operation id names and the new names + */ + @Parameter(name = "operationIdNameMappings", property = "openapi.generator.maven.plugin.operationIdNameMappings") + private List operationIdNameMappings; + /** * A set of rules for OpenAPI normalizer */ @@ -857,6 +863,11 @@ public void execute() throws MojoExecutionException { applyEnumNameMappingsKvpList(enumNameMappings, configurator); } + // Apply Operation ID Name Mappings + if (operationIdNameMappings != null && (configOptions == null || !configOptions.containsKey("operation-id-name-mappings"))) { + applyOperationIdNameMappingsKvpList(operationIdNameMappings, configurator); + } + // Apply OpenAPI normalizer rules if (openapiNormalizer != null && (configOptions == null || !configOptions.containsKey("openapi-normalizer"))) { applyOpenAPINormalizerKvpList(openapiNormalizer, configurator); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java index ccb63c22e556..94a88df56cf8 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java @@ -158,6 +158,8 @@ public interface CodegenConfig { Map enumNameMapping(); + Map operationIdNameMapping(); + Map openapiNormalizer(); Map apiTemplateFiles(); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java index 9a9da0173b4e..2cf0cba46e39 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java @@ -177,6 +177,8 @@ public class DefaultCodegen implements CodegenConfig { protected Map modelNameMapping = new HashMap<>(); // a map to store the mapping between enum name and the name provided by the user protected Map enumNameMapping = new HashMap<>(); + // a map to store the mapping between operation id name and the name provided by the user + protected Map operationIdNameMapping = new HashMap<>(); // a map to store the rules in OpenAPI Normalizer protected Map openapiNormalizer = new HashMap<>(); protected String modelPackage = "", apiPackage = "", fileSuffix; @@ -1271,6 +1273,11 @@ public Map enumNameMapping() { return enumNameMapping; } + @Override + public Map operationIdNameMapping() { + return operationIdNameMapping; + } + @Override public Map openapiNormalizer() { return openapiNormalizer; @@ -4551,7 +4558,11 @@ public CodegenOperation fromOperation(String path, op.path = path; } - op.operationId = toOperationId(operationId); + if (operationIdNameMapping.containsKey(operationId)) { + op.operationId = operationIdNameMapping.get(operationId); + } else { + op.operationId = toOperationId(operationId); + } op.summary = escapeText(operation.getSummary()); op.unescapedNotes = operation.getDescription(); op.notes = escapeText(operation.getDescription()); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java index dd9bdc161224..bee2393d753a 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java @@ -75,6 +75,7 @@ public class CodegenConfigurator { private Map parameterNameMappings = new HashMap<>(); private Map modelNameMappings = new HashMap<>(); private Map enumNameMappings = new HashMap<>(); + private Map operationIdNameMappings = new HashMap<>(); private Map openapiNormalizer = new HashMap<>(); private Set languageSpecificPrimitives = new HashSet<>(); private Set openapiGeneratorIgnoreList = new HashSet<>(); @@ -141,6 +142,9 @@ public static CodegenConfigurator fromFile(String configFile, Module... modules) if(generatorSettings.getEnumNameMappings() != null) { configurator.enumNameMappings.putAll(generatorSettings.getEnumNameMappings()); } + if(generatorSettings.getOperationIdNameMappings() != null) { + configurator.operationIdNameMappings.putAll(generatorSettings.getOperationIdNameMappings()); + } if(generatorSettings.getOpenAPINormalizer() != null) { configurator.openapiNormalizer.putAll(generatorSettings.getOpenAPINormalizer()); } @@ -258,6 +262,12 @@ public CodegenConfigurator addEnumNameMapping(String key, String value) { return this; } + public CodegenConfigurator addOperationIdNameMapping(String key, String value) { + this.operationIdNameMappings.put(key, value); + generatorSettingsBuilder.withOperationIdNameMapping(key, value); + return this; + } + public CodegenConfigurator addOpenAPINormalizer(String key, String value) { this.openapiNormalizer.put(key, value); generatorSettingsBuilder.withOpenAPINormalizer(key, value); @@ -466,6 +476,12 @@ public CodegenConfigurator setEnumNameMappings(Map enumNameMappi return this; } + public CodegenConfigurator setOperationIdNameMappings(Map operationIdNameMappings) { + this.operationIdNameMappings = operationIdNameMappings; + generatorSettingsBuilder.withOperationIdNameMappings(operationIdNameMappings); + return this; + } + public CodegenConfigurator setOpenAPINormalizer(Map openapiNormalizer) { this.openapiNormalizer = openapiNormalizer; generatorSettingsBuilder.withOpenAPINormalizer(openapiNormalizer); @@ -762,6 +778,7 @@ public ClientOptInput toClientOptInput() { config.parameterNameMapping().putAll(generatorSettings.getParameterNameMappings()); config.modelNameMapping().putAll(generatorSettings.getModelNameMappings()); config.enumNameMapping().putAll(generatorSettings.getEnumNameMappings()); + config.operationIdNameMapping().putAll(generatorSettings.getOperationIdNameMappings()); config.openapiNormalizer().putAll(generatorSettings.getOpenAPINormalizer()); config.languageSpecificPrimitives().addAll(generatorSettings.getLanguageSpecificPrimitives()); config.openapiGeneratorIgnoreList().addAll(generatorSettings.getOpenAPIGeneratorIgnoreList()); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfiguratorUtils.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfiguratorUtils.java index 21cbde34c9a2..962b1f4df617 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfiguratorUtils.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfiguratorUtils.java @@ -172,6 +172,19 @@ public static void applyEnumNameMappingsKvp(String enumNameMappings, CodegenConf } } + public static void applyOperationIdNameMappingsKvpList(List operationIdNameMappings, CodegenConfigurator configurator) { + for (String propString : operationIdNameMappings) { + applyOperationIdNameMappingsKvp(propString, configurator); + } + } + + public static void applyOperationIdNameMappingsKvp(String operationIdNameMappings, CodegenConfigurator configurator) { + final Map map = createMapFromKeyValuePairs(operationIdNameMappings); + for (Map.Entry entry : map.entrySet()) { + configurator.addOperationIdNameMapping(entry.getKey().trim(), entry.getValue().trim()); + } + } + public static void applyOpenAPINormalizerKvpList(List openapiNormalizer, CodegenConfigurator configurator) { for (String propString : openapiNormalizer) { applyOpenAPINormalizerKvp(propString, configurator); diff --git a/samples/client/petstore/java/okhttp-gson/README.md b/samples/client/petstore/java/okhttp-gson/README.md index f3ed707b0116..70c7275daf49 100644 --- a/samples/client/petstore/java/okhttp-gson/README.md +++ b/samples/client/petstore/java/okhttp-gson/README.md @@ -118,12 +118,12 @@ Class | Method | HTTP request | Description *AnotherFakeApi* | [**getParameterStringNumber**](docs/AnotherFakeApi.md#getParameterStringNumber) | **GET** /fake/parameter-string-number | parameter string number *AnotherFakeApi* | [**nullRequestBody**](docs/AnotherFakeApi.md#nullRequestBody) | **GET** /fake/null-request-body | null request body *DefaultApi* | [**fooGet**](docs/DefaultApi.md#fooGet) | **GET** /foo | -*FakeApi* | [**fakeHealthGet**](docs/FakeApi.md#fakeHealthGet) | **GET** /fake/health | Health check endpoint *FakeApi* | [**fakeOuterBooleanSerialize**](docs/FakeApi.md#fakeOuterBooleanSerialize) | **POST** /fake/outer/boolean | *FakeApi* | [**fakeOuterCompositeSerialize**](docs/FakeApi.md#fakeOuterCompositeSerialize) | **POST** /fake/outer/composite | *FakeApi* | [**fakeOuterNumberSerialize**](docs/FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | *FakeApi* | [**fakeOuterStringSerialize**](docs/FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | -*FakeApi* | [**getArrayOfEnums**](docs/FakeApi.md#getArrayOfEnums) | **GET** /fake/array-of-enums | Array of Enums +*FakeApi* | [**getFakeArrayofenums**](docs/FakeApi.md#getFakeArrayofenums) | **GET** /fake/array-of-enums | Array of Enums +*FakeApi* | [**getFakeHealth**](docs/FakeApi.md#getFakeHealth) | **GET** /fake/health | Health check endpoint *FakeApi* | [**getParameterNameMapping**](docs/FakeApi.md#getParameterNameMapping) | **GET** /fake/parameter-name-mapping | parameter name mapping test *FakeApi* | [**testAdditionalPropertiesReference**](docs/FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *FakeApi* | [**testBodyWithFileSchema**](docs/FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | diff --git a/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md b/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md index d3f35fd2f2fe..a2446c0e16b0 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md +++ b/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md @@ -4,12 +4,12 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | Method | HTTP request | Description | |------------- | ------------- | -------------| -| [**fakeHealthGet**](FakeApi.md#fakeHealthGet) | **GET** /fake/health | Health check endpoint | | [**fakeOuterBooleanSerialize**](FakeApi.md#fakeOuterBooleanSerialize) | **POST** /fake/outer/boolean | | | [**fakeOuterCompositeSerialize**](FakeApi.md#fakeOuterCompositeSerialize) | **POST** /fake/outer/composite | | | [**fakeOuterNumberSerialize**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | | | [**fakeOuterStringSerialize**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | | -| [**getArrayOfEnums**](FakeApi.md#getArrayOfEnums) | **GET** /fake/array-of-enums | Array of Enums | +| [**getFakeArrayofenums**](FakeApi.md#getFakeArrayofenums) | **GET** /fake/array-of-enums | Array of Enums | +| [**getFakeHealth**](FakeApi.md#getFakeHealth) | **GET** /fake/health | Health check endpoint | | [**getParameterNameMapping**](FakeApi.md#getParameterNameMapping) | **GET** /fake/parameter-name-mapping | parameter name mapping test | | [**testAdditionalPropertiesReference**](FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**testBodyWithFileSchema**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | | @@ -25,62 +25,6 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**testStringMapReference**](FakeApi.md#testStringMapReference) | **POST** /fake/stringMap-reference | test referenced string map | - -# **fakeHealthGet** -> HealthCheckResult fakeHealthGet() - -Health check endpoint - -### Example -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - FakeApi apiInstance = new FakeApi(defaultClient); - try { - HealthCheckResult result = apiInstance.fakeHealthGet(); - System.out.println(result); - } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#fakeHealthGet"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters -This endpoint does not need any parameter. - -### Return type - -[**HealthCheckResult**](HealthCheckResult.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | The instance started successfully | - | - # **fakeOuterBooleanSerialize** > Boolean fakeOuterBooleanSerialize(body) @@ -329,9 +273,9 @@ No authorization required |-------------|-------------|------------------| | **200** | Output string | - | - -# **getArrayOfEnums** -> List<OuterEnum> getArrayOfEnums() + +# **getFakeArrayofenums** +> List<OuterEnum> getFakeArrayofenums() Array of Enums @@ -351,10 +295,10 @@ public class Example { FakeApi apiInstance = new FakeApi(defaultClient); try { - List result = apiInstance.getArrayOfEnums(); + List result = apiInstance.getFakeArrayofenums(); System.out.println(result); } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#getArrayOfEnums"); + System.err.println("Exception when calling FakeApi#getFakeArrayofenums"); System.err.println("Status code: " + e.getCode()); System.err.println("Reason: " + e.getResponseBody()); System.err.println("Response headers: " + e.getResponseHeaders()); @@ -385,6 +329,62 @@ No authorization required |-------------|-------------|------------------| | **200** | Got named array of enums | - | + +# **getFakeHealth** +> HealthCheckResult getFakeHealth() + +Health check endpoint + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + try { + HealthCheckResult result = apiInstance.getFakeHealth(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#getFakeHealth"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**HealthCheckResult**](HealthCheckResult.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | The instance started successfully | - | + # **getParameterNameMapping** > getParameterNameMapping(underscoreType, type, typeWithUnderscore) diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/FakeApi.java index b6d823e656d1..96c9b88e2843 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/FakeApi.java @@ -82,119 +82,6 @@ public void setCustomBaseUrl(String customBaseUrl) { this.localCustomBaseUrl = customBaseUrl; } - /** - * Build call for fakeHealthGet - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - -
Status Code Description Response Headers
200 The instance started successfully -
- */ - public okhttp3.Call fakeHealthGetCall(final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/fake/health"; - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call fakeHealthGetValidateBeforeCall(final ApiCallback _callback) throws ApiException { - return fakeHealthGetCall(_callback); - - } - - /** - * Health check endpoint - * - * @return HealthCheckResult - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - -
Status Code Description Response Headers
200 The instance started successfully -
- */ - public HealthCheckResult fakeHealthGet() throws ApiException { - ApiResponse localVarResp = fakeHealthGetWithHttpInfo(); - return localVarResp.getData(); - } - - /** - * Health check endpoint - * - * @return ApiResponse<HealthCheckResult> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - -
Status Code Description Response Headers
200 The instance started successfully -
- */ - public ApiResponse fakeHealthGetWithHttpInfo() throws ApiException { - okhttp3.Call localVarCall = fakeHealthGetValidateBeforeCall(null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Health check endpoint (asynchronously) - * - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - -
Status Code Description Response Headers
200 The instance started successfully -
- */ - public okhttp3.Call fakeHealthGetAsync(final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = fakeHealthGetValidateBeforeCall(_callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } /** * Build call for fakeOuterBooleanSerialize * @param body Input boolean as post body (optional) @@ -668,7 +555,7 @@ public okhttp3.Call fakeOuterStringSerializeAsync(String body, final ApiCallback return localVarCall; } /** - * Build call for getArrayOfEnums + * Build call for getFakeArrayofenums * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object @@ -678,7 +565,7 @@ public okhttp3.Call fakeOuterStringSerializeAsync(String body, final ApiCallback 200 Got named array of enums - */ - public okhttp3.Call getArrayOfEnumsCall(final ApiCallback _callback) throws ApiException { + public okhttp3.Call getFakeArrayofenumsCall(final ApiCallback _callback) throws ApiException { String basePath = null; // Operation Servers String[] localBasePaths = new String[] { }; @@ -723,8 +610,8 @@ public okhttp3.Call getArrayOfEnumsCall(final ApiCallback _callback) throws ApiE } @SuppressWarnings("rawtypes") - private okhttp3.Call getArrayOfEnumsValidateBeforeCall(final ApiCallback _callback) throws ApiException { - return getArrayOfEnumsCall(_callback); + private okhttp3.Call getFakeArrayofenumsValidateBeforeCall(final ApiCallback _callback) throws ApiException { + return getFakeArrayofenumsCall(_callback); } @@ -739,8 +626,8 @@ private okhttp3.Call getArrayOfEnumsValidateBeforeCall(final ApiCallback _callba 200 Got named array of enums - */ - public List getArrayOfEnums() throws ApiException { - ApiResponse> localVarResp = getArrayOfEnumsWithHttpInfo(); + public List getFakeArrayofenums() throws ApiException { + ApiResponse> localVarResp = getFakeArrayofenumsWithHttpInfo(); return localVarResp.getData(); } @@ -755,8 +642,8 @@ public List getArrayOfEnums() throws ApiException { 200 Got named array of enums - */ - public ApiResponse> getArrayOfEnumsWithHttpInfo() throws ApiException { - okhttp3.Call localVarCall = getArrayOfEnumsValidateBeforeCall(null); + public ApiResponse> getFakeArrayofenumsWithHttpInfo() throws ApiException { + okhttp3.Call localVarCall = getFakeArrayofenumsValidateBeforeCall(null); Type localVarReturnType = new TypeToken>(){}.getType(); return localVarApiClient.execute(localVarCall, localVarReturnType); } @@ -773,13 +660,126 @@ public ApiResponse> getArrayOfEnumsWithHttpInfo() throws ApiExce 200 Got named array of enums - */ - public okhttp3.Call getArrayOfEnumsAsync(final ApiCallback> _callback) throws ApiException { + public okhttp3.Call getFakeArrayofenumsAsync(final ApiCallback> _callback) throws ApiException { - okhttp3.Call localVarCall = getArrayOfEnumsValidateBeforeCall(_callback); + okhttp3.Call localVarCall = getFakeArrayofenumsValidateBeforeCall(_callback); Type localVarReturnType = new TypeToken>(){}.getType(); localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } + /** + * Build call for getFakeHealth + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 The instance started successfully -
+ */ + public okhttp3.Call getFakeHealthCall(final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/fake/health"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call getFakeHealthValidateBeforeCall(final ApiCallback _callback) throws ApiException { + return getFakeHealthCall(_callback); + + } + + /** + * Health check endpoint + * + * @return HealthCheckResult + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 The instance started successfully -
+ */ + public HealthCheckResult getFakeHealth() throws ApiException { + ApiResponse localVarResp = getFakeHealthWithHttpInfo(); + return localVarResp.getData(); + } + + /** + * Health check endpoint + * + * @return ApiResponse<HealthCheckResult> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 The instance started successfully -
+ */ + public ApiResponse getFakeHealthWithHttpInfo() throws ApiException { + okhttp3.Call localVarCall = getFakeHealthValidateBeforeCall(null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Health check endpoint (asynchronously) + * + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 The instance started successfully -
+ */ + public okhttp3.Call getFakeHealthAsync(final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = getFakeHealthValidateBeforeCall(_callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } /** * Build call for getParameterNameMapping * @param underscoreType _type (required) diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/FakeApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/FakeApiTest.java index 4dea80f5e403..9a44aacd233a 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/FakeApiTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/FakeApiTest.java @@ -23,9 +23,10 @@ import java.time.OffsetDateTime; import org.openapitools.client.model.OuterComposite; import org.openapitools.client.model.OuterEnum; +import org.openapitools.client.model.TestInlineFreeformAdditionalPropertiesRequest; import org.openapitools.client.model.User; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.HashMap; @@ -40,148 +41,147 @@ public class FakeApiTest { private final FakeApi api = new FakeApi(); - - /** - * Health check endpoint - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void fakeHealthGetTest() throws ApiException { - HealthCheckResult response = api.fakeHealthGet(); - // TODO: test validations - } - /** - * - * * Test serialization of outer boolean types * - * @throws ApiException - * if the Api call fails + * @throws ApiException if the Api call fails */ @Test public void fakeOuterBooleanSerializeTest() throws ApiException { Boolean body = null; - Boolean response = api.fakeOuterBooleanSerialize(body); + Boolean response = api.fakeOuterBooleanSerialize(body); // TODO: test validations } - + /** - * - * * Test serialization of object with outer number type * - * @throws ApiException - * if the Api call fails + * @throws ApiException if the Api call fails */ @Test public void fakeOuterCompositeSerializeTest() throws ApiException { OuterComposite outerComposite = null; - OuterComposite response = api.fakeOuterCompositeSerialize(outerComposite); + OuterComposite response = api.fakeOuterCompositeSerialize(outerComposite); // TODO: test validations } - + /** - * - * * Test serialization of outer number types * - * @throws ApiException - * if the Api call fails + * @throws ApiException if the Api call fails */ @Test public void fakeOuterNumberSerializeTest() throws ApiException { BigDecimal body = null; - BigDecimal response = api.fakeOuterNumberSerialize(body); + BigDecimal response = api.fakeOuterNumberSerialize(body); // TODO: test validations } - + /** - * - * * Test serialization of outer string types * - * @throws ApiException - * if the Api call fails + * @throws ApiException if the Api call fails */ @Test public void fakeOuterStringSerializeTest() throws ApiException { String body = null; - String response = api.fakeOuterStringSerialize(body); + String response = api.fakeOuterStringSerialize(body); // TODO: test validations } - + /** * Array of Enums * - * + * @throws ApiException if the Api call fails + */ + @Test + public void getFakeArrayofenumsTest() throws ApiException { + List response = api.getFakeArrayofenums(); + // TODO: test validations + } + + /** + * Health check endpoint + * + * @throws ApiException if the Api call fails + */ + @Test + public void getFakeHealthTest() throws ApiException { + HealthCheckResult response = api.getFakeHealth(); + // TODO: test validations + } + + /** + * parameter name mapping test * - * @throws ApiException - * if the Api call fails + * @throws ApiException if the Api call fails */ @Test - public void getArrayOfEnumsTest() throws ApiException { - List response = api.getArrayOfEnums(); + public void getParameterNameMappingTest() throws ApiException { + Long underscoreType = null; + String type = null; + String typeWithUnderscore = null; + api.getParameterNameMapping(underscoreType, type, typeWithUnderscore); // TODO: test validations } - + /** + * test referenced additionalProperties + * * * + * @throws ApiException if the Api call fails + */ + @Test + public void testAdditionalPropertiesReferenceTest() throws ApiException { + Map requestBody = null; + api.testAdditionalPropertiesReference(requestBody); + // TODO: test validations + } + + /** * For this test, the body for this request much reference a schema named `File`. * - * @throws ApiException - * if the Api call fails + * @throws ApiException if the Api call fails */ @Test public void testBodyWithFileSchemaTest() throws ApiException { FileSchemaTestClass fileSchemaTestClass = null; - api.testBodyWithFileSchema(fileSchemaTestClass); + api.testBodyWithFileSchema(fileSchemaTestClass); // TODO: test validations } - + /** - * - * - * - * - * @throws ApiException - * if the Api call fails + * @throws ApiException if the Api call fails */ @Test public void testBodyWithQueryParamsTest() throws ApiException { String query = null; User user = null; - api.testBodyWithQueryParams(query, user); + api.testBodyWithQueryParams(query, user); // TODO: test validations } - + /** * To test \"client\" model * * To test \"client\" model * - * @throws ApiException - * if the Api call fails + * @throws ApiException if the Api call fails */ @Test public void testClientModelTest() throws ApiException { Client client = null; - Client response = api.testClientModel(client); + Client response = api.testClientModel(client); // TODO: test validations } - + /** * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * - * @throws ApiException - * if the Api call fails + * @throws ApiException if the Api call fails */ @Test public void testEndpointParametersTest() throws ApiException { @@ -199,17 +199,16 @@ public void testEndpointParametersTest() throws ApiException { OffsetDateTime dateTime = null; String password = null; String paramCallback = null; - api.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); + api.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); // TODO: test validations } - + /** * To test enum parameters * * To test enum parameters * - * @throws ApiException - * if the Api call fails + * @throws ApiException if the Api call fails */ @Test public void testEnumParametersTest() throws ApiException { @@ -221,17 +220,16 @@ public void testEnumParametersTest() throws ApiException { Double enumQueryDouble = null; List enumFormStringArray = null; String enumFormString = null; - api.testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); + api.testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); // TODO: test validations } - + /** * Fake endpoint to test group parameters (optional) * * Fake endpoint to test group parameters (optional) * - * @throws ApiException - * if the Api call fails + * @throws ApiException if the Api call fails */ @Test public void testGroupParametersTest() throws ApiException { @@ -241,52 +239,61 @@ public void testGroupParametersTest() throws ApiException { Integer stringGroup = null; Boolean booleanGroup = null; Long int64Group = null; - api.testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group) + api.testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group) .stringGroup(stringGroup) .booleanGroup(booleanGroup) .int64Group(int64Group) .execute(); // TODO: test validations } - + /** * test inline additionalProperties * * * - * @throws ApiException - * if the Api call fails + * @throws ApiException if the Api call fails */ @Test public void testInlineAdditionalPropertiesTest() throws ApiException { Map requestBody = null; - api.testInlineAdditionalProperties(requestBody); + api.testInlineAdditionalProperties(requestBody); + // TODO: test validations + } + + /** + * test inline free-form additionalProperties + * + * + * + * @throws ApiException if the Api call fails + */ + @Test + public void testInlineFreeformAdditionalPropertiesTest() throws ApiException { + TestInlineFreeformAdditionalPropertiesRequest testInlineFreeformAdditionalPropertiesRequest = null; + api.testInlineFreeformAdditionalProperties(testInlineFreeformAdditionalPropertiesRequest); // TODO: test validations } - + /** * test json serialization of form data * * * - * @throws ApiException - * if the Api call fails + * @throws ApiException if the Api call fails */ @Test public void testJsonFormDataTest() throws ApiException { String param = null; String param2 = null; - api.testJsonFormData(param, param2); + api.testJsonFormData(param, param2); // TODO: test validations } - + /** - * - * * To test the collection format in query parameters * - * @throws ApiException - * if the Api call fails + * @throws ApiException if the Api call fails */ @Test public void testQueryParameterCollectionFormatTest() throws ApiException { @@ -295,8 +302,22 @@ public void testQueryParameterCollectionFormatTest() throws ApiException { List http = null; List url = null; List context = null; - api.testQueryParameterCollectionFormat(pipe, ioutil, http, url, context); + api.testQueryParameterCollectionFormat(pipe, ioutil, http, url, context); + // TODO: test validations + } + + /** + * test referenced string map + * + * + * + * @throws ApiException if the Api call fails + */ + @Test + public void testStringMapReferenceTest() throws ApiException { + Map requestBody = null; + api.testStringMapReference(requestBody); // TODO: test validations } - + }