diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java index bd44e898ec82..b193ec296628 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java @@ -69,7 +69,8 @@ public class JavaClientCodegenTest { // This is the kind of information that ideally would be defined and available system-wide - @Getter enum Library { + @Getter + enum Library { APACHE_HTTPCLIENT("apache-httpclient", Serializer.JACKSON), FEIGN("feign", Serializer.JACKSON, Set.of(Serializer.GSON)), GOOGLE_API_CLIENT("google-api-client", Serializer.JACKSON), @@ -93,7 +94,7 @@ public class JavaClientCodegenTest { Library(String identifier, Serializer defaultSerializer) { this(identifier, defaultSerializer, Set.of()); } - + Library(String identifier, Serializer defaultSerializer, Set otherSupportedSerializers) { otherSupportedSerializers = new HashSet<>(otherSupportedSerializers); otherSupportedSerializers.add(defaultSerializer); @@ -105,35 +106,41 @@ public class JavaClientCodegenTest { enum Serializer { GSON, JACKSON, JSONB; + public String toString() { return this.name().toLowerCase(Locale.ROOT); } } - @DataProvider Iterator supportedLibraries() { + @DataProvider + Iterator supportedLibraries() { return Arrays.stream(Library.values()).iterator(); } - @DataProvider Iterator librariesSupportingGson() { + @DataProvider + Iterator librariesSupportingGson() { return Arrays.stream(Library.values()) - .filter(library -> library.getSupportedSerializers().contains(Serializer.GSON)) - .iterator(); + .filter(library -> library.getSupportedSerializers().contains(Serializer.GSON)) + .iterator(); } - @DataProvider Iterator librariesSupportingJackson() { + @DataProvider + Iterator librariesSupportingJackson() { return Arrays.stream(Library.values()) - .filter(library -> library.getSupportedSerializers().contains(Serializer.JACKSON)) - .iterator(); + .filter(library -> library.getSupportedSerializers().contains(Serializer.JACKSON)) + .iterator(); } - @DataProvider Iterator librariesNotSupportingJackson() { + @DataProvider + Iterator librariesNotSupportingJackson() { return Arrays.stream(Library.values()) - .filter(library -> !library.getSupportedSerializers().contains(Serializer.JACKSON)) - .iterator(); + .filter(library -> !library.getSupportedSerializers().contains(Serializer.JACKSON)) + .iterator(); } - - @Test public void arraysInRequestBody() { + + @Test + public void arraysInRequestBody() { OpenAPI openAPI = TestUtils.createOpenAPI(); final JavaClientCodegen codegen = new JavaClientCodegen(); codegen.setOpenAPI(openAPI); @@ -141,8 +148,8 @@ public String toString() { RequestBody body1 = new RequestBody(); body1.setDescription("A list of ids"); body1.setContent(new Content().addMediaType( - "application/json", - new MediaType().schema(new ArraySchema().items(new StringSchema())) + "application/json", + new MediaType().schema(new ArraySchema().items(new StringSchema())) )); CodegenParameter codegenParameter1 = codegen.fromRequestBody(body1, new HashSet<>(), null); Assertions.assertEquals(codegenParameter1.description, "A list of ids"); @@ -152,8 +159,8 @@ public String toString() { RequestBody body2 = new RequestBody(); body2.setDescription("A list of list of values"); body2.setContent(new Content().addMediaType( - "application/json", - new MediaType().schema(new ArraySchema().items(new ArraySchema().items(new IntegerSchema()))) + "application/json", + new MediaType().schema(new ArraySchema().items(new ArraySchema().items(new IntegerSchema()))) )); CodegenParameter codegenParameter2 = codegen.fromRequestBody(body2, new HashSet<>(), null); Assertions.assertEquals(codegenParameter2.description, "A list of list of values"); @@ -282,27 +289,29 @@ public void testAdditionalPropertiesPutForConfigValues() throws Exception { Assertions.assertEquals(codegen.getSerializationLibrary(), JavaClientCodegen.SERIALIZATION_LIBRARY_JACKSON); } - @Test public void testGeneratedAuthClassesJersey() { + @Test + public void testGeneratedAuthClassesJersey() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.JERSEY3) - .setAdditionalProperties(Map.of(CodegenConstants.API_PACKAGE, "xyz.abcdef.api")) - .setInputSpec("src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml") - .setOutputDir(output.toString().replace("\\", "/")); + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.JERSEY3) + .setAdditionalProperties(Map.of(CodegenConstants.API_PACKAGE, "xyz.abcdef.api")) + .setInputSpec("src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml") + .setOutputDir(output.toString().replace("\\", "/")); List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); assertThat(files).contains( - output.resolve("src/main/java/xyz/abcdef/auth/ApiKeyAuth.java").toFile(), - output.resolve("src/main/java/xyz/abcdef/auth/Authentication.java").toFile(), - output.resolve("src/main/java/xyz/abcdef/auth/HttpBasicAuth.java").toFile(), - output.resolve("src/main/java/xyz/abcdef/auth/HttpBearerAuth.java").toFile(), - output.resolve("src/main/java/xyz/abcdef/auth/HttpSignatureAuth.java").toFile() + output.resolve("src/main/java/xyz/abcdef/auth/ApiKeyAuth.java").toFile(), + output.resolve("src/main/java/xyz/abcdef/auth/Authentication.java").toFile(), + output.resolve("src/main/java/xyz/abcdef/auth/HttpBasicAuth.java").toFile(), + output.resolve("src/main/java/xyz/abcdef/auth/HttpBearerAuth.java").toFile(), + output.resolve("src/main/java/xyz/abcdef/auth/HttpSignatureAuth.java").toFile() ); } - @Test public void testImportMappingResult() { + @Test + public void testImportMappingResult() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .addTypeMapping("OffsetDateTime", "Instant") @@ -314,7 +323,7 @@ public void testAdditionalPropertiesPutForConfigValues() throws Exception { new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); assertThat(output.resolve("src/main/java/org/openapitools/client/api/QueryApi.java")) - .content().contains("import java.time.Instant;"); + .content().contains("import java.time.Instant;"); } @Test @@ -326,7 +335,8 @@ public void testSupportedSecuritySchemesJersey() { Assertions.assertTrue(codegen.getFeatureSet().getSecurityFeatures().contains(SecurityFeature.SignatureAuth)); } - @Test public void testPackageNamesSetInvokerDerivedFromApi() { + @Test + public void testPackageNamesSetInvokerDerivedFromApi() { final JavaClientCodegen codegen = new JavaClientCodegen(); codegen.additionalProperties().put(CodegenConstants.MODEL_PACKAGE, "xyz.yyyyy.zzzzzzz.mmmmm.model"); codegen.additionalProperties().put(CodegenConstants.API_PACKAGE, "xyz.yyyyy.zzzzzzz.aaaaa.api"); @@ -339,10 +349,11 @@ public void testSupportedSecuritySchemesJersey() { configAssert.assertValue(CodegenConstants.INVOKER_PACKAGE, codegen::getInvokerPackage, "xyz.yyyyy.zzzzzzz.aaaaa"); } - @Test public void testPackageNamesSetInvokerDerivedFromModel() { + @Test + public void testPackageNamesSetInvokerDerivedFromModel() { final JavaClientCodegen codegen = new JavaClientCodegen(); codegen.additionalProperties().put(CodegenConstants.MODEL_PACKAGE, "xyz.yyyyy.zzzzzzz.mmmmm.model"); - + codegen.processOpts(); ConfigAssert configAssert = new ConfigAssert(codegen.additionalProperties()); @@ -351,17 +362,19 @@ public void testSupportedSecuritySchemesJersey() { configAssert.assertValue(CodegenConstants.INVOKER_PACKAGE, codegen::getInvokerPackage, "xyz.yyyyy.zzzzzzz.mmmmm"); } - @Test public void testGetSchemaTypeWithComposedSchemaWithAllOf() { + @Test + public void testGetSchemaTypeWithComposedSchemaWithAllOf() { final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/2_0/composed-allof.yaml"); Operation operation = openAPI.getPaths().get("/ping").getPost(); CodegenOperation co = new JavaClientCodegen().fromOperation("/ping", "POST", operation, null); assertThat(co.allParams).hasSize(1) - .first().hasFieldOrPropertyWithValue("baseType", "MessageEventCoreWithTimeListEntries"); + .first().hasFieldOrPropertyWithValue("baseType", "MessageEventCoreWithTimeListEntries"); } - @Test public void updateCodegenPropertyEnum() { + @Test + public void updateCodegenPropertyEnum() { final JavaClientCodegen codegen = new JavaClientCodegen(); CodegenProperty array = codegenPropertyWithArrayOfIntegerValues(); @@ -375,7 +388,8 @@ public void testSupportedSecuritySchemesJersey() { Assertions.assertEquals(testedEnumVar.getOrDefault("value", ""), "1"); } - @Test public void updateCodegenPropertyEnumWithCustomNames() { + @Test + public void updateCodegenPropertyEnumWithCustomNames() { final JavaClientCodegen codegen = new JavaClientCodegen(); CodegenProperty array = codegenPropertyWithArrayOfIntegerValues(); array.getItems().setVendorExtensions(Map.of("x-enum-varnames", Collections.singletonList("ONE"))); @@ -390,7 +404,8 @@ public void testSupportedSecuritySchemesJersey() { Assertions.assertEquals(testedEnumVar.getOrDefault("value", ""), "1"); } - @Test public void testGeneratePing() { + @Test + public void testGeneratePing() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") @@ -403,112 +418,114 @@ public void testSupportedSecuritySchemesJersey() { validateJavaSourceFiles(files); assertThat(files).hasSize(40).map(File::toPath).contains( - output.resolve(".gitignore"), - output.resolve(".openapi-generator-ignore"), - output.resolve(".openapi-generator/FILES"), - output.resolve(".openapi-generator/VERSION"), - output.resolve(".travis.yml"), - output.resolve("build.gradle"), - output.resolve("build.sbt"), - output.resolve("docs/DefaultApi.md"), - output.resolve("git_push.sh"), - output.resolve("gradle.properties"), - output.resolve("gradle/wrapper/gradle-wrapper.jar"), - output.resolve("gradle/wrapper/gradle-wrapper.properties"), - output.resolve("gradlew.bat"), - output.resolve("gradlew"), - output.resolve("pom.xml"), - output.resolve("README.md"), - output.resolve("settings.gradle"), - output.resolve("api/openapi.yaml"), - output.resolve("src/main/AndroidManifest.xml"), - output.resolve("src/main/java/xyz/abcdef/api/DefaultApi.java"), - output.resolve("src/main/java/xyz/abcdef/ApiCallback.java"), - output.resolve("src/main/java/xyz/abcdef/ApiClient.java"), - output.resolve("src/main/java/xyz/abcdef/ApiException.java"), - output.resolve("src/main/java/xyz/abcdef/ApiResponse.java"), - output.resolve("src/main/java/xyz/abcdef/ServerVariable.java"), - output.resolve("src/main/java/xyz/abcdef/auth/ApiKeyAuth.java"), - output.resolve("src/main/java/xyz/abcdef/ServerConfiguration.java"), - output.resolve("src/main/java/xyz/abcdef/auth/Authentication.java"), - output.resolve("src/main/java/xyz/abcdef/auth/HttpBasicAuth.java"), - output.resolve("src/main/java/xyz/abcdef/auth/HttpBearerAuth.java"), - output.resolve("src/main/java/xyz/abcdef/Configuration.java"), - output.resolve("src/main/java/xyz/abcdef/GzipRequestInterceptor.java"), - output.resolve("src/main/java/xyz/abcdef/JSON.java"), - output.resolve("src/main/java/xyz/abcdef/ProgressRequestBody.java"), - output.resolve("src/main/java/xyz/abcdef/Pair.java"), - output.resolve("src/main/java/xyz/abcdef/ProgressResponseBody.java"), - output.resolve("src/main/java/xyz/abcdef/StringUtil.java"), - output.resolve("src/test/java/xyz/abcdef/api/DefaultApiTest.java") + output.resolve(".gitignore"), + output.resolve(".openapi-generator-ignore"), + output.resolve(".openapi-generator/FILES"), + output.resolve(".openapi-generator/VERSION"), + output.resolve(".travis.yml"), + output.resolve("build.gradle"), + output.resolve("build.sbt"), + output.resolve("docs/DefaultApi.md"), + output.resolve("git_push.sh"), + output.resolve("gradle.properties"), + output.resolve("gradle/wrapper/gradle-wrapper.jar"), + output.resolve("gradle/wrapper/gradle-wrapper.properties"), + output.resolve("gradlew.bat"), + output.resolve("gradlew"), + output.resolve("pom.xml"), + output.resolve("README.md"), + output.resolve("settings.gradle"), + output.resolve("api/openapi.yaml"), + output.resolve("src/main/AndroidManifest.xml"), + output.resolve("src/main/java/xyz/abcdef/api/DefaultApi.java"), + output.resolve("src/main/java/xyz/abcdef/ApiCallback.java"), + output.resolve("src/main/java/xyz/abcdef/ApiClient.java"), + output.resolve("src/main/java/xyz/abcdef/ApiException.java"), + output.resolve("src/main/java/xyz/abcdef/ApiResponse.java"), + output.resolve("src/main/java/xyz/abcdef/ServerVariable.java"), + output.resolve("src/main/java/xyz/abcdef/auth/ApiKeyAuth.java"), + output.resolve("src/main/java/xyz/abcdef/ServerConfiguration.java"), + output.resolve("src/main/java/xyz/abcdef/auth/Authentication.java"), + output.resolve("src/main/java/xyz/abcdef/auth/HttpBasicAuth.java"), + output.resolve("src/main/java/xyz/abcdef/auth/HttpBearerAuth.java"), + output.resolve("src/main/java/xyz/abcdef/Configuration.java"), + output.resolve("src/main/java/xyz/abcdef/GzipRequestInterceptor.java"), + output.resolve("src/main/java/xyz/abcdef/JSON.java"), + output.resolve("src/main/java/xyz/abcdef/ProgressRequestBody.java"), + output.resolve("src/main/java/xyz/abcdef/Pair.java"), + output.resolve("src/main/java/xyz/abcdef/ProgressResponseBody.java"), + output.resolve("src/main/java/xyz/abcdef/StringUtil.java"), + output.resolve("src/test/java/xyz/abcdef/api/DefaultApiTest.java") ); assertThat(output.resolve("src/main/java/xyz/abcdef/api/DefaultApi.java")).content() - .contains("public class DefaultApi"); + .contains("public class DefaultApi"); } - @Test public void testGeneratePingSomeObj(){ + @Test + public void testGeneratePingSomeObj() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .addAdditionalProperty(CodegenConstants.MODEL_PACKAGE, "zz.yyyy.model.xxxx") - .addAdditionalProperty(CodegenConstants.API_PACKAGE, "zz.yyyy.api.xxxx") - .addAdditionalProperty(CodegenConstants.INVOKER_PACKAGE, "zz.yyyy.invoker.xxxx") - .addAdditionalProperty(AbstractJavaCodegen.BOOLEAN_GETTER_PREFIX, "is") - .setLibrary(JavaClientCodegen.OKHTTP_GSON) - .setInputSpec("src/test/resources/3_0/pingSomeObj.yaml") - .setOutputDir(output.toString().replace("\\", "/")); + .setGeneratorName("java") + .addAdditionalProperty(CodegenConstants.MODEL_PACKAGE, "zz.yyyy.model.xxxx") + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "zz.yyyy.api.xxxx") + .addAdditionalProperty(CodegenConstants.INVOKER_PACKAGE, "zz.yyyy.invoker.xxxx") + .addAdditionalProperty(AbstractJavaCodegen.BOOLEAN_GETTER_PREFIX, "is") + .setLibrary(JavaClientCodegen.OKHTTP_GSON) + .setInputSpec("src/test/resources/3_0/pingSomeObj.yaml") + .setOutputDir(output.toString().replace("\\", "/")); List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); assertThat(output.resolve("src/main/java/zz/yyyy/model/xxxx/SomeObj.java")).content() - .contains("public class SomeObj", "Boolean isActive()"); + .contains("public class SomeObj", "Boolean isActive()"); assertThat(files).hasSize(43).map(File::toPath).contains( - output.resolve(".gitignore"), - output.resolve(".openapi-generator-ignore"), - output.resolve(".openapi-generator/FILES"), - output.resolve(".openapi-generator/VERSION"), - output.resolve(".travis.yml"), - output.resolve("build.gradle"), - output.resolve("build.sbt"), - output.resolve("docs/PingApi.md"), - output.resolve("docs/SomeObj.md"), - output.resolve("git_push.sh"), - output.resolve("gradle.properties"), - output.resolve("gradle/wrapper/gradle-wrapper.jar"), - output.resolve("gradle/wrapper/gradle-wrapper.properties"), - output.resolve("gradlew.bat"), - output.resolve("gradlew"), - output.resolve("pom.xml"), - output.resolve("README.md"), - output.resolve("settings.gradle"), - output.resolve("api/openapi.yaml"), - output.resolve("src/main/AndroidManifest.xml"), - output.resolve("src/main/java/zz/yyyy/api/xxxx/PingApi.java"), - output.resolve("src/main/java/zz/yyyy/invoker/xxxx/ApiCallback.java"), - output.resolve("src/main/java/zz/yyyy/invoker/xxxx/ApiClient.java"), - output.resolve("src/main/java/zz/yyyy/invoker/xxxx/ApiException.java"), - output.resolve("src/main/java/zz/yyyy/invoker/xxxx/ApiResponse.java"), - output.resolve("src/main/java/zz/yyyy/invoker/xxxx/ServerConfiguration.java"), - output.resolve("src/main/java/zz/yyyy/invoker/xxxx/ServerVariable.java"), - output.resolve("src/main/java/zz/yyyy/invoker/xxxx/auth/ApiKeyAuth.java"), - output.resolve("src/main/java/zz/yyyy/invoker/xxxx/auth/Authentication.java"), - output.resolve("src/main/java/zz/yyyy/invoker/xxxx/auth/HttpBasicAuth.java"), - output.resolve("src/main/java/zz/yyyy/invoker/xxxx/auth/HttpBearerAuth.java"), - output.resolve("src/main/java/zz/yyyy/invoker/xxxx/Configuration.java"), - output.resolve("src/main/java/zz/yyyy/invoker/xxxx/GzipRequestInterceptor.java"), - output.resolve("src/main/java/zz/yyyy/invoker/xxxx/JSON.java"), - output.resolve("src/main/java/zz/yyyy/invoker/xxxx/Pair.java"), - output.resolve("src/main/java/zz/yyyy/invoker/xxxx/ProgressRequestBody.java"), - output.resolve("src/main/java/zz/yyyy/invoker/xxxx/ProgressResponseBody.java"), - output.resolve("src/main/java/zz/yyyy/invoker/xxxx/StringUtil.java"), - output.resolve("src/main/java/zz/yyyy/model/xxxx/SomeObj.java"), - output.resolve("src/test/java/zz/yyyy/api/xxxx/PingApiTest.java"), - output.resolve("src/test/java/zz/yyyy/model/xxxx/SomeObjTest.java") + output.resolve(".gitignore"), + output.resolve(".openapi-generator-ignore"), + output.resolve(".openapi-generator/FILES"), + output.resolve(".openapi-generator/VERSION"), + output.resolve(".travis.yml"), + output.resolve("build.gradle"), + output.resolve("build.sbt"), + output.resolve("docs/PingApi.md"), + output.resolve("docs/SomeObj.md"), + output.resolve("git_push.sh"), + output.resolve("gradle.properties"), + output.resolve("gradle/wrapper/gradle-wrapper.jar"), + output.resolve("gradle/wrapper/gradle-wrapper.properties"), + output.resolve("gradlew.bat"), + output.resolve("gradlew"), + output.resolve("pom.xml"), + output.resolve("README.md"), + output.resolve("settings.gradle"), + output.resolve("api/openapi.yaml"), + output.resolve("src/main/AndroidManifest.xml"), + output.resolve("src/main/java/zz/yyyy/api/xxxx/PingApi.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/ApiCallback.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/ApiClient.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/ApiException.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/ApiResponse.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/ServerConfiguration.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/ServerVariable.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/auth/ApiKeyAuth.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/auth/Authentication.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/auth/HttpBasicAuth.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/auth/HttpBearerAuth.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/Configuration.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/GzipRequestInterceptor.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/JSON.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/Pair.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/ProgressRequestBody.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/ProgressResponseBody.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/StringUtil.java"), + output.resolve("src/main/java/zz/yyyy/model/xxxx/SomeObj.java"), + output.resolve("src/test/java/zz/yyyy/api/xxxx/PingApiTest.java"), + output.resolve("src/test/java/zz/yyyy/model/xxxx/SomeObjTest.java") ); } - @Test public void testJdkHttpClient() { + @Test + public void testJdkHttpClient() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") @@ -522,46 +539,48 @@ public void testSupportedSecuritySchemesJersey() { assertThat(files).hasSize(32); validateJavaSourceFiles(files); assertThat(output.resolve("src/main/java/xyz/abcdef/api/DefaultApi.java")).content().contains( - "public class DefaultApi", - "import java.net.http.HttpClient;", - "import java.net.http.HttpRequest;", - "import java.net.http.HttpResponse;" + "public class DefaultApi", + "import java.net.http.HttpClient;", + "import java.net.http.HttpRequest;", + "import java.net.http.HttpResponse;" ); assertThat(output.resolve("src/main/java/xyz/abcdef/ApiClient.java")).content().contains( - "public class ApiClient", - "import java.net.http.HttpClient;", - "import java.net.http.HttpRequest;" + "public class ApiClient", + "import java.net.http.HttpClient;", + "import java.net.http.HttpRequest;" ); } - @Test public void testJdkHttpClientWithUseBeanValidationEnabled() { + @Test + public void testJdkHttpClientWithUseBeanValidationEnabled() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.NATIVE) - .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") - .addAdditionalProperty(JavaClientCodegen.USE_BEANVALIDATION, true) - .addAdditionalProperty(JavaClientCodegen.USE_JAKARTA_EE, true) - .setInputSpec("src/test/resources/3_1/issue-17485.yaml") - .setOutputDir(output.toString().replace("\\", "/")); + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.NATIVE) + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.USE_BEANVALIDATION, true) + .addAdditionalProperty(JavaClientCodegen.USE_JAKARTA_EE, true) + .setInputSpec("src/test/resources/3_1/issue-17485.yaml") + .setOutputDir(output.toString().replace("\\", "/")); List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); assertThat(output.resolve("src/main/java/xyz/abcdef/api/UserApi.java")).content() - .contains("@Pattern", "import jakarta.validation.constraints.*"); + .contains("@Pattern", "import jakarta.validation.constraints.*"); } - @Test public void testJdkHttpClientWithAndWithoutDiscriminator() { + @Test + public void testJdkHttpClientWithAndWithoutDiscriminator() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.NATIVE) - .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") - .addAdditionalProperty(CodegenConstants.MODEL_PACKAGE, "xyz.abcdef.model") - .addAdditionalProperty(CodegenConstants.INVOKER_PACKAGE, "xyz.abcdef.invoker") - .setInputSpec("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml") - .setOutputDir(output.toString().replace("\\", "/")); + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.NATIVE) + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(CodegenConstants.MODEL_PACKAGE, "xyz.abcdef.model") + .addAdditionalProperty(CodegenConstants.INVOKER_PACKAGE, "xyz.abcdef.invoker") + .setInputSpec("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml") + .setOutputDir(output.toString().replace("\\", "/")); DefaultGenerator generator = new DefaultGenerator(); generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true"); @@ -574,15 +593,16 @@ public void testSupportedSecuritySchemesJersey() { .contains("import xyz.abcdef.invoker.JSON;"); } - @Test public void testJdkHttpAsyncClient() { + @Test + public void testJdkHttpAsyncClient() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") - .addAdditionalProperty(JavaClientCodegen.ASYNC_NATIVE, true) - .setLibrary(JavaClientCodegen.NATIVE) - .setInputSpec("src/test/resources/3_0/pingSomeObj.yaml") - .setOutputDir(output.toString().replace("\\", "/")); + .setGeneratorName("java") + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.ASYNC_NATIVE, true) + .setLibrary(JavaClientCodegen.NATIVE) + .setInputSpec("src/test/resources/3_0/pingSomeObj.yaml") + .setOutputDir(output.toString().replace("\\", "/")); List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); @@ -590,16 +610,16 @@ public void testSupportedSecuritySchemesJersey() { validateJavaSourceFiles(files); assertThat(output.resolve("src/main/java/xyz/abcdef/api/PingApi.java")).content().contains( - "public class PingApi", - "import java.net.http.HttpClient;", - "import java.net.http.HttpRequest;", - "import java.net.http.HttpResponse;", - "import java.util.concurrent.CompletableFuture;" + "public class PingApi", + "import java.net.http.HttpClient;", + "import java.net.http.HttpRequest;", + "import java.net.http.HttpResponse;", + "import java.util.concurrent.CompletableFuture;" ); assertThat(output.resolve("src/main/java/xyz/abcdef/ApiClient.java")).content().contains( - "public class ApiClient", - "import java.net.http.HttpClient;", - "import java.net.http.HttpRequest;" + "public class ApiClient", + "import java.net.http.HttpClient;", + "import java.net.http.HttpRequest;" ); } @@ -655,7 +675,8 @@ public void testAuthorizationScopeValues_Issue392() { assertEquals(postScopes.size(), 2, "POST scopes don't match. actual:" + postScopes); } - @Test public void testAuthorizationScopeValues_Issue6733() { + @Test + public void testAuthorizationScopeValues_Issue6733() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") @@ -678,14 +699,15 @@ public void testAuthorizationScopeValues_Issue392() { Assertions.assertEquals(files.size(), 1); } - @Test public void testTypedAndNonTypedComposedSchemaGeneration_3_1() { + @Test + public void testTypedAndNonTypedComposedSchemaGeneration_3_1() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.RESTEASY) - .setValidateSpec(false) - .setInputSpec("src/test/resources/3_1/composed-schemas-with-and-without-type.yaml") - .setOutputDir(output.toString().replace("\\", "/")); + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.RESTEASY) + .setValidateSpec(false) + .setInputSpec("src/test/resources/3_1/composed-schemas-with-and-without-type.yaml") + .setOutputDir(output.toString().replace("\\", "/")); DefaultGenerator generator = new DefaultGenerator(); generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true"); @@ -700,7 +722,8 @@ public void testAuthorizationScopeValues_Issue392() { Assertions.assertEquals(files.size(), 9); } - @Test public void testMultiPartSpecifiesFileName_Issue17367() throws IOException { + @Test + public void testMultiPartSpecifiesFileName_Issue17367() throws IOException { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") @@ -717,7 +740,7 @@ public void testAuthorizationScopeValues_Issue392() { generator.setGeneratorPropertyDefault(CodegenConstants.SUPPORTING_FILES, "true"); generator.setGenerateMetadata(false); List files = generator.opts(configurator.toClientOptInput()).generate(); - + validateJavaSourceFiles(files); File apiClient = files.stream() .filter(f -> f.getName().equals("ApiClient.java")) @@ -727,28 +750,30 @@ public void testAuthorizationScopeValues_Issue392() { // https://docs.jboss.org/resteasy/docs/6.2.5.Final/javadocs/org/jboss/resteasy/plugins/providers/multipart/MultipartFormDataOutput.html#addFormData(java.lang.String,java.lang.Object,jakarta.ws.rs.core.MediaType,java.lang.String) assertTrue(contents.anyMatch(l -> l.matches( ".*multipart\\.addFormData\\(param.getKey\\(\\),\\s*" + - "new\\s+FileInputStream\\(file\\),\\s*" + - "MediaType\\.APPLICATION_OCTET_STREAM_TYPE,\\s*" + - "file.getName\\(\\)\\);.*"))); + "new\\s+FileInputStream\\(file\\),\\s*" + + "MediaType\\.APPLICATION_OCTET_STREAM_TYPE,\\s*" + + "file.getName\\(\\)\\);.*"))); } - @Test public void testAuthorizationsMethodsSizeWhenFiltered() { + @Test + public void testAuthorizationsMethodsSizeWhenFiltered() { final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/issue4584.yaml"); final ClientOptInput clientOptInput = new ClientOptInput().openAPI(openAPI).config(new JavaClientCodegen()); final DefaultGenerator defaultGenerator = new DefaultGenerator(); defaultGenerator.opts(clientOptInput); - + final List codegenOperations = defaultGenerator.processPaths(openAPI.getPaths()).get("Pet"); final CodegenOperation getCodegenOperation = codegenOperations.stream() - .filter(it -> it.httpMethod.equals("GET")) - .collect(Collectors.toList()) - .get(0); + .filter(it -> it.httpMethod.equals("GET")) + .collect(Collectors.toList()) + .get(0); assertTrue(getCodegenOperation.hasAuthMethods); assertEquals(getCodegenOperation.authMethods.size(), 2); } - @Test public void testFreeFormObjects() { + @Test + public void testFreeFormObjects() { final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/issue796.yaml"); JavaClientCodegen codegen = new JavaClientCodegen(); @@ -783,7 +808,8 @@ public void testAuthorizationScopeValues_Issue392() { /** * See https://github.com/OpenAPITools/openapi-generator/issues/3589 */ - @Test public void testSchemaMapping() throws IOException { + @Test + public void testSchemaMapping() throws IOException { final Path output = newTempFolder(); final ClientOptInput clientOptInput = new CodegenConfigurator() .setGeneratorName("java") @@ -805,7 +831,7 @@ public void testAuthorizationScopeValues_Issue392() { validateJavaSourceFiles(files); Assertions.assertEquals(clientOptInput.getConfig().schemaMapping().get("TypeAlias"), "foo.bar.TypeAlias"); assertThat(files).hasSize(1) - .contains(output.resolve("src/main/java/org/openapitools/client/model/ParentType.java").toFile()); + .contains(output.resolve("src/main/java/org/openapitools/client/model/ParentType.java").toFile()); File file = files.stream().filter(f -> f.getName().endsWith("ParentType.java")).findFirst().get(); String parentTypeContents = Files.readString(file.toPath()); @@ -819,26 +845,28 @@ public void testAuthorizationScopeValues_Issue392() { Assertions.assertEquals(fieldMatcher.group(1), "foo.bar.TypeAlias"); } - @Test public void testBearerAuth() { + @Test + public void testBearerAuth() { final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/pingBearerAuth.yaml"); List security = new JavaClientCodegen().fromSecurity(openAPI.getComponents().getSecuritySchemes()); - + assertThat(security).hasSize(1) - .first() - .hasFieldOrPropertyWithValue("isBasic", Boolean.TRUE) - .hasFieldOrPropertyWithValue("isBasicBasic", Boolean.FALSE) - .hasFieldOrPropertyWithValue("isBasicBearer", Boolean.TRUE); + .first() + .hasFieldOrPropertyWithValue("isBasic", Boolean.TRUE) + .hasFieldOrPropertyWithValue("isBasicBasic", Boolean.FALSE) + .hasFieldOrPropertyWithValue("isBasicBearer", Boolean.TRUE); } - @Test public void testVertXAuthInfoWithHyphenSeparatedSecurityScheme() { + @Test + public void testVertXAuthInfoWithHyphenSeparatedSecurityScheme() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.VERTX) - .setAdditionalProperties(Map.of(CodegenConstants.API_PACKAGE, "xyz.abcdef.api")) - .setInputSpec("src/test/resources/3_0/ping-with-hyphen-separated-security-scheme.yaml") - .setOutputDir(output.toString().replace("\\", "/")); + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.VERTX) + .setAdditionalProperties(Map.of(CodegenConstants.API_PACKAGE, "xyz.abcdef.api")) + .setInputSpec("src/test/resources/3_0/ping-with-hyphen-separated-security-scheme.yaml") + .setOutputDir(output.toString().replace("\\", "/")); List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); @@ -849,11 +877,11 @@ public void testAuthorizationScopeValues_Issue392() { // Test that the name was correctly transformed to camelCase // starting with an uppercase letter assertThat(output.resolve("src/main/java/xyz/abcdef/ApiClient.java")).content() - .contains( - "public static class AuthInfo {", - "public void addHyphenatedNameTestAuthentication(String bearerToken) {", - "public static AuthInfo forHyphenatedNameTestAuthentication(String bearerToken) {" - ); + .contains( + "public static class AuthInfo {", + "public void addHyphenatedNameTestAuthentication(String bearerToken) {", + "public static AuthInfo forHyphenatedNameTestAuthentication(String bearerToken) {" + ); } private CodegenProperty codegenPropertyWithArrayOfIntegerValues() { @@ -1042,7 +1070,8 @@ public void testAnyType() { * We will contact the contributor of the following test to see if the fix will break their use cases and * how we can fix it accordingly. */ - @Test(enabled = false) public void testRestTemplateFormMultipart() { + @Test(enabled = false) + public void testRestTemplateFormMultipart() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") @@ -1055,19 +1084,19 @@ public void testAnyType() { validateJavaSourceFiles(files); assertThat(output.resolve("src/main/java/xyz/abcdef/api/MultipartApi.java")).content() - .contains( - "multipartArrayWithHttpInfo(List files)", - "formParams.addAll(\"files\"," - + " files.stream().map(FileSystemResource::new).collect(Collectors.toList()));", + .contains( + "multipartArrayWithHttpInfo(List files)", + "formParams.addAll(\"files\"," + + " files.stream().map(FileSystemResource::new).collect(Collectors.toList()));", - // mixed - "multipartMixedWithHttpInfo(File file, MultipartMixedMarker marker)", - "formParams.add(\"file\", new FileSystemResource(file));", + // mixed + "multipartMixedWithHttpInfo(File file, MultipartMixedMarker marker)", + "formParams.add(\"file\", new FileSystemResource(file));", - // single file - "multipartSingleWithHttpInfo(File file)", - "formParams.add(\"file\", new FileSystemResource(file));" - ); + // single file + "multipartSingleWithHttpInfo(File file)", + "formParams.add(\"file\", new FileSystemResource(file));" + ); } /** @@ -1077,7 +1106,8 @@ public void testAnyType() { * We will contact the contributor of the following test to see if the fix will break their use cases and * how we can fix it accordingly. */ - @Test(enabled = false) public void testWebClientFormMultipart() { + @Test(enabled = false) + public void testWebClientFormMultipart() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") @@ -1090,32 +1120,32 @@ public void testAnyType() { validateJavaSourceFiles(files); assertThat(output.resolve("src/main/java/xyz/abcdef/api/MultipartApi.java")).content() - .contains( - // multiple files - "multipartArray(List files)", - "formParams.addAll(\"files\"," - + " files.stream().map(FileSystemResource::new).collect(Collectors.toList()));", - - // mixed - "multipartMixed(File file, MultipartMixedMarker marker)", - "formParams.add(\"file\", new FileSystemResource(file));", - - // single file - "multipartSingle(File file)", - "formParams.add(\"file\", new FileSystemResource(file));" - ); + .contains( + // multiple files + "multipartArray(List files)", + "formParams.addAll(\"files\"," + + " files.stream().map(FileSystemResource::new).collect(Collectors.toList()));", + + // mixed + "multipartMixed(File file, MultipartMixedMarker marker)", + "formParams.add(\"file\", new FileSystemResource(file));", + + // single file + "multipartSingle(File file)", + "formParams.add(\"file\", new FileSystemResource(file));" + ); } @Test public void shouldGenerateBlockingAndNoBlockingOperationsForWebClient() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") - .addAdditionalProperty(JavaClientCodegen.WEBCLIENT_BLOCKING_OPERATIONS, true) - .setLibrary(JavaClientCodegen.WEBCLIENT) - .setInputSpec("src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml") - .setOutputDir(output.toString().replace("\\", "/")); + .setGeneratorName("java") + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.WEBCLIENT_BLOCKING_OPERATIONS, true) + .setLibrary(JavaClientCodegen.WEBCLIENT) + .setInputSpec("src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml") + .setOutputDir(output.toString().replace("\\", "/")); DefaultGenerator generator = new DefaultGenerator(); Map files = generator.opts(configurator.toClientOptInput()).generate().stream() @@ -1136,7 +1166,8 @@ public void shouldGenerateBlockingAndNoBlockingOperationsForWebClient() { "List"); // explicit 'x-webclient-blocking: true' which overrides global config } - @Test public void testAllowModelWithNoProperties() { + @Test + public void testAllowModelWithNoProperties() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") @@ -1148,12 +1179,12 @@ public void shouldGenerateBlockingAndNoBlockingOperationsForWebClient() { validateJavaSourceFiles(files); assertThat(output.resolve("src/main/java/org/openapitools/client/model/RealCommand.java")) - .content().contains("class RealCommand {"); + .content().contains("class RealCommand {"); assertThat(output.resolve("src/main/java/org/openapitools/client/model/Command.java")) - .content().contains("class Command {"); + .content().contains("class Command {"); assertThat(files).hasSize(49).contains( - output.resolve("src/main/java/org/openapitools/client/model/RealCommand.java").toFile(), - output.resolve("src/main/java/org/openapitools/client/model/Command.java").toFile() + output.resolve("src/main/java/org/openapitools/client/model/RealCommand.java").toFile(), + output.resolve("src/main/java/org/openapitools/client/model/Command.java").toFile() ); } @@ -1164,40 +1195,42 @@ public void shouldGenerateBlockingAndNoBlockingOperationsForWebClient() { * We will contact the contributor of the following test to see if the fix will break their use cases and * how we can fix it accordingly. */ - @Test(enabled = false) public void testRestTemplateWithUseAbstractionForFiles() { + @Test(enabled = false) + public void testRestTemplateWithUseAbstractionForFiles() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") - .addAdditionalProperty(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true) - .setLibrary(JavaClientCodegen.RESTTEMPLATE) - .setInputSpec("src/test/resources/3_0/form-multipart-binary-array.yaml") - .setOutputDir(output.toString().replace("\\", "/")); + .setGeneratorName("java") + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true) + .setLibrary(JavaClientCodegen.RESTTEMPLATE) + .setInputSpec("src/test/resources/3_0/form-multipart-binary-array.yaml") + .setOutputDir(output.toString().replace("\\", "/")); List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); assertThat(output.resolve("/src/main/java/xyz/abcdef/api/MultipartApi.java")).content().contains( - // multiple files - "multipartArray(java.util.Collection files)", - "multipartArrayWithHttpInfo(java.util.Collection" - + " files)", - "formParams.addAll(\"files\", files.stream().collect(Collectors.toList()));", - - // mixed - "multipartMixed(org.springframework.core.io.Resource file, MultipartMixedMarker marker)", - "multipartMixedWithHttpInfo(org.springframework.core.io.Resource file, MultipartMixedMarker" - + " marker)", - "formParams.add(\"file\", file);", - - // single file - "multipartSingle(org.springframework.core.io.Resource file)", - "multipartSingleWithHttpInfo(org.springframework.core.io.Resource file)", - "formParams.add(\"file\", file);" + // multiple files + "multipartArray(java.util.Collection files)", + "multipartArrayWithHttpInfo(java.util.Collection" + + " files)", + "formParams.addAll(\"files\", files.stream().collect(Collectors.toList()));", + + // mixed + "multipartMixed(org.springframework.core.io.Resource file, MultipartMixedMarker marker)", + "multipartMixedWithHttpInfo(org.springframework.core.io.Resource file, MultipartMixedMarker" + + " marker)", + "formParams.add(\"file\", file);", + + // single file + "multipartSingle(org.springframework.core.io.Resource file)", + "multipartSingleWithHttpInfo(org.springframework.core.io.Resource file)", + "formParams.add(\"file\", file);" ); } - @Test void testNotDuplicateOauth2FlowsScopes() { + @Test + void testNotDuplicateOauth2FlowsScopes() { final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/issue_7614.yaml"); final ClientOptInput clientOptInput = new ClientOptInput().openAPI(openAPI).config(new JavaClientCodegen()); final DefaultGenerator defaultGenerator = new DefaultGenerator(); @@ -1209,18 +1242,18 @@ public void shouldGenerateBlockingAndNoBlockingOperationsForWebClient() { final CodegenOperation getWithBasicAuthAndOauth = getByOperationId(codegenOperations, "getWithBasicAuthAndOauth"); assertEquals(getWithBasicAuthAndOauth.authMethods.size(), 3); assertEquals(getWithBasicAuthAndOauth.authMethods.get(0).name, "basic_auth"); - + final Map passwordFlowScope = getWithBasicAuthAndOauth.authMethods.get(1).scopes.get(0); assertEquals(passwordFlowScope.get("scope"), "something:create"); assertEquals(passwordFlowScope.get("description"), "create from password flow"); - + final Map clientCredentialsFlow = getWithBasicAuthAndOauth.authMethods.get(2).scopes.get(0); assertEquals(clientCredentialsFlow.get("scope"), "something:create"); assertEquals(clientCredentialsFlow.get("description"), "create from client credentials flow"); - + final CodegenOperation getWithOauthAuth = getByOperationId(codegenOperations, "getWithOauthAuth"); assertEquals(getWithOauthAuth.authMethods.size(), 2); - + final Map passwordFlow = getWithOauthAuth.authMethods.get(0).scopes.get(0); assertEquals(passwordFlow.get("scope"), "something:create"); assertEquals(passwordFlow.get("description"), "create from password flow"); @@ -1236,11 +1269,11 @@ public void shouldGenerateBlockingAndNoBlockingOperationsForWebClient() { private CodegenOperation getByOperationId(List codegenOperations, String operationId) { return getByCriteria(codegenOperations, (co) -> co.operationId.equals(operationId)) - .orElseThrow( - () -> new IllegalStateException( - String.format(Locale.ROOT, "Operation with id [%s] does not exist", operationId) - ) - ); + .orElseThrow( + () -> new IllegalStateException( + String.format(Locale.ROOT, "Operation with id [%s] does not exist", operationId) + ) + ); } private Optional getByCriteria(List codegenOperations, Predicate filter) { @@ -1249,7 +1282,8 @@ private Optional getByCriteria(List codegenO .findFirst(); } - @Test public void testCustomMethodParamsAreCamelizedWhenUsingFeign() { + @Test + public void testCustomMethodParamsAreCamelizedWhenUsingFeign() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") @@ -1265,18 +1299,19 @@ private Optional getByCriteria(List codegenO var defaultApiFile = output.resolve("src/main/java/org/openapitools/client/api/DefaultApi.java"); assertThat(files).contains(defaultApiFile.toFile()); assertThat(defaultApiFile).content() - .doesNotContain("event_id") - .contains( - "@RequestLine(\"POST /events/{eventId}:undelete\")", - // baseName is kept for form parameters - "@Param(\"some_file\") File someFile" - ); + .doesNotContain("event_id") + .contains( + "@RequestLine(\"POST /events/{eventId}:undelete\")", + // baseName is kept for form parameters + "@Param(\"some_file\") File someFile" + ); } /** * see https://github.com/OpenAPITools/openapi-generator/issues/19895 */ - @Test public void testCharsetInContentTypeCorrectlyEncodedForFeignApi_issue19895() { + @Test + public void testCharsetInContentTypeCorrectlyEncodedForFeignApi_issue19895() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") @@ -1308,34 +1343,35 @@ private Optional getByCriteria(List codegenO * We will contact the contributor of the following test to see if the fix will break their use cases and * how we can fix it accordingly. */ - @Test(enabled = false) public void testWebClientWithUseAbstractionForFiles() { + @Test(enabled = false) + public void testWebClientWithUseAbstractionForFiles() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") - .addAdditionalProperty(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true) - .setLibrary(JavaClientCodegen.WEBCLIENT) - .setInputSpec("src/test/resources/3_0/form-multipart-binary-array.yaml") - .setOutputDir(output.toString().replace("\\", "/")); + .setGeneratorName("java") + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true) + .setLibrary(JavaClientCodegen.WEBCLIENT) + .setInputSpec("src/test/resources/3_0/form-multipart-binary-array.yaml") + .setOutputDir(output.toString().replace("\\", "/")); List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); assertThat(output.resolve("src/main/java/xyz/abcdef/api/MultipartApi.java")).content() - .contains( - // multiple files - "multipartArray(java.util.Collection files)", - "formParams.addAll(\"files\", files.stream().collect(Collectors.toList()));", - - // mixed - "multipartMixed(org.springframework.core.io.AbstractResource file, MultipartMixedMarker" - + " marker)", - "formParams.add(\"file\", file);", - - // single file - "multipartSingle(org.springframework.core.io.AbstractResource file)", - "formParams.add(\"file\", file);" - ); + .contains( + // multiple files + "multipartArray(java.util.Collection files)", + "formParams.addAll(\"files\", files.stream().collect(Collectors.toList()));", + + // mixed + "multipartMixed(org.springframework.core.io.AbstractResource file, MultipartMixedMarker" + + " marker)", + "formParams.add(\"file\", file);", + + // single file + "multipartSingle(org.springframework.core.io.AbstractResource file)", + "formParams.add(\"file\", file);" + ); } /** @@ -1353,13 +1389,14 @@ public void testRestTemplateWithFreeFormInQueryParameters() { new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); assertThat(output.resolve("src/main/java/xyz/abcdef/ApiClient.java")).content() - .contains("value instanceof Map"); + .contains("value instanceof Map"); } /** * See https://github.com/OpenAPITools/openapi-generator/issues/8352 */ - @Test public void testWebClientWithFreeFormInQueryParameters() { + @Test + public void testWebClientWithFreeFormInQueryParameters() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator().setGeneratorName("java") .setLibrary(JavaClientCodegen.WEBCLIENT) @@ -1371,13 +1408,14 @@ public void testRestTemplateWithFreeFormInQueryParameters() { validateJavaSourceFiles(files); assertThat(output.resolve("src/main/java/xyz/abcdef/ApiClient.java")).content() - .contains("value instanceof Map"); + .contains("value instanceof Map"); } /** * See https://github.com/OpenAPITools/openapi-generator/issues/11242 */ - @Test public void testNativeClientWhiteSpacePathParamEncoding() { + @Test + public void testNativeClientWhiteSpacePathParamEncoding() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") @@ -1391,15 +1429,16 @@ public void testRestTemplateWithFreeFormInQueryParameters() { validateJavaSourceFiles(files); assertThat(files).hasSize(35); TestUtils.assertFileContains(output.resolve("src/main/java/xyz/abcdef/ApiClient.java"), - "public static String urlEncode(String s) { return URLEncoder.encode(s," - + " UTF_8).replaceAll(\"\\\\+\", \"%20\"); }" + "public static String urlEncode(String s) { return URLEncoder.encode(s," + + " UTF_8).replaceAll(\"\\\\+\", \"%20\"); }" ); } /** * See https://github.com/OpenAPITools/openapi-generator/issues/4808 */ - @Test public void testNativeClientExplodedQueryParamObject() { + @Test + public void testNativeClientExplodedQueryParamObject() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") @@ -1413,15 +1452,16 @@ public void testRestTemplateWithFreeFormInQueryParameters() { validateJavaSourceFiles(files); assertThat(files).hasSize(38); assertThat(output.resolve("src/main/java/xyz/abcdef/api/DefaultApi.java")).content() - .contains( - "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"since\", queryObject.getSince()));", - "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"sinceBuild\", queryObject.getSinceBuild()));", - "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"maxBuilds\", queryObject.getMaxBuilds()));", - "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"maxWaitSecs\", queryObject.getMaxWaitSecs()));" - ); + .contains( + "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"since\", queryObject.getSince()));", + "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"sinceBuild\", queryObject.getSinceBuild()));", + "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"maxBuilds\", queryObject.getMaxBuilds()));", + "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"maxWaitSecs\", queryObject.getMaxWaitSecs()));" + ); } - @Test public void testDefaultMicroprofileRestClientVersion() { + @Test + public void testDefaultMicroprofileRestClientVersion() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") @@ -1434,16 +1474,17 @@ public void testRestTemplateWithFreeFormInQueryParameters() { validateJavaSourceFiles(files); assertThat(files).contains(output.resolve("pom.xml").toFile()); assertThat(output.resolve("src/main/java/org/openapitools/client/api/PetApi.java")).content() - .contains("import javax."); + .contains("import javax."); assertThat(output.resolve("pom.xml")).content() - .contains( - "2.0", - "1.2.1", - "1.8" - ); + .contains( + "2.0", + "1.2.1", + "1.8" + ); } - @Test public void testMicroprofileRestClientVersion_1_4_1() { + @Test + public void testMicroprofileRestClientVersion_1_4_1() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setAdditionalProperties(Map.of(JavaClientCodegen.MICROPROFILE_REST_CLIENT_VERSION, "1.4.1")) @@ -1457,20 +1498,20 @@ public void testRestTemplateWithFreeFormInQueryParameters() { validateJavaSourceFiles(files); assertThat(files).contains(output.resolve("pom.xml").toFile()); assertThat(output.resolve("src/main/java/org/openapitools/client/api/PetApi.java")).content() - .contains("import javax."); + .contains("import javax."); assertThat(output.resolve("pom.xml")).content() - .contains( - "1.4.1", - "1.2.1", - "1.8" - ); + .contains( + "1.4.1", + "1.2.1", + "1.8" + ); } @Test( - expectedExceptions = IllegalArgumentException.class, - expectedExceptionsMessageRegExp = - "Version incorrectVersion of MicroProfile Rest Client is not supported or incorrect." - + " Supported versions are 1.4.1, 2.0, 3.0" + expectedExceptions = IllegalArgumentException.class, + expectedExceptionsMessageRegExp = + "Version incorrectVersion of MicroProfile Rest Client is not supported or incorrect." + + " Supported versions are 1.4.1, 2.0, 3.0" ) public void testMicroprofileRestClientIncorrectVersion() { final Path output = newTempFolder(); @@ -1482,11 +1523,12 @@ public void testMicroprofileRestClientIncorrectVersion() { .setOutputDir(output.toString().replace("\\", "/")); new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); - + fail("Expected an exception that did not occur"); } - @Test public void testMicroprofileRestClientVersion_3_0() { + @Test + public void testMicroprofileRestClientVersion_3_0() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setAdditionalProperties(Map.of(JavaClientCodegen.MICROPROFILE_REST_CLIENT_VERSION, "3.0")) @@ -1500,26 +1542,27 @@ public void testMicroprofileRestClientIncorrectVersion() { validateJavaSourceFiles(files); assertThat(files).contains(output.resolve("pom.xml").toFile()); assertThat(output.resolve("src/main/java/org/openapitools/client/api/PetApi.java")).content() - .contains("import jakarta."); + .contains("import jakarta."); assertThat(output.resolve("pom.xml")).content() - .contains( - "3.0", - "3.0.4", - "11" - ); + .contains( + "3.0", + "3.0.4", + "11" + ); } - @Test public void testMicroprofileGenerateCorrectJsonbCreator_issue12622() { + @Test + public void testMicroprofileGenerateCorrectJsonbCreator_issue12622() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setAdditionalProperties(Map.of(JavaClientCodegen.MICROPROFILE_REST_CLIENT_VERSION, "3.0")) + .setAdditionalProperties(Map.of(JavaClientCodegen.MICROPROFILE_REST_CLIENT_VERSION, "3.0")) .setGeneratorName("java") .setLibrary(JavaClientCodegen.MICROPROFILE) .setInputSpec("src/test/resources/bugs/issue_12622.json") .setOutputDir(output.toString().replace("\\", "/")); Map files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate() - .stream().collect(Collectors.toMap(File::getName, Function.identity())); + .stream().collect(Collectors.toMap(File::getName, Function.identity())); JavaFileAssert.assertThat(files.get("Foo.java")) .assertConstructor("String", "Integer") @@ -1566,17 +1609,18 @@ public void testMicroprofileGenerateCorrectJacksonGenerator_issue18336() throws .containsWithNameAndAttributes("JsonProperty", ImmutableMap.of("value", "JSON_PROPERTY_NAME", "required", "true")); } - @Test public void testJavaClientDefaultValues_issueNoNumber() { + @Test + public void testJavaClientDefaultValues_issueNoNumber() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setAdditionalProperties(Map.of(JavaClientCodegen.MICROPROFILE_REST_CLIENT_VERSION, "3.0")) - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.WEBCLIENT) - .setOutputDir(output.toString().replace("\\", "/")) - .setInputSpec("src/test/resources/bugs/java-codegen-empty-array-as-default-value/issue_wrong-default.yaml"); + .setAdditionalProperties(Map.of(JavaClientCodegen.MICROPROFILE_REST_CLIENT_VERSION, "3.0")) + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.WEBCLIENT) + .setOutputDir(output.toString().replace("\\", "/")) + .setInputSpec("src/test/resources/bugs/java-codegen-empty-array-as-default-value/issue_wrong-default.yaml"); Map files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate() - .stream().collect(Collectors.toMap(File::getName, Function.identity())); + .stream().collect(Collectors.toMap(File::getName, Function.identity())); JavaFileAssert.assertThat(files.get("DefaultValuesType.java")) .assertProperty("stringDefault") @@ -1589,7 +1633,8 @@ public void testMicroprofileGenerateCorrectJacksonGenerator_issue18336() throws .asString().endsWith("= new ArrayList<>();"); } - @Test public void testWebClientJsonCreatorWithNullable_issue12790() { + @Test + public void testWebClientJsonCreatorWithNullable_issue12790() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setAdditionalProperties(Map.of(AbstractJavaCodegen.OPENAPI_NULLABLE, "true")) @@ -1610,29 +1655,31 @@ public void testMicroprofileGenerateCorrectJacksonGenerator_issue18336() throws "this.notNullableProperty = notNullableProperty;"); } - @Test public void testRestTemplateResponseTypeWithUseAbstractionForFiles() { + @Test + public void testRestTemplateResponseTypeWithUseAbstractionForFiles() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.RESTTEMPLATE) - .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") - .addAdditionalProperty(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true) - .setInputSpec("src/test/resources/3_0/issue13146_file_abstraction_response.yaml") - .setOutputDir(output.toString().replace("\\", "/")); + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.RESTTEMPLATE) + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true) + .setInputSpec("src/test/resources/3_0/issue13146_file_abstraction_response.yaml") + .setOutputDir(output.toString().replace("\\", "/")); List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); assertThat(output.resolve("src/main/java/xyz/abcdef/api/ResourceApi.java")).content() - .contains( - "org.springframework.core.io.Resource resourceInResponse()", - "ResponseEntity resourceInResponseWithHttpInfo()", - "ParameterizedTypeReference localReturnType = new" - + " ParameterizedTypeReference()" - ); + .contains( + "org.springframework.core.io.Resource resourceInResponse()", + "ResponseEntity resourceInResponseWithHttpInfo()", + "ParameterizedTypeReference localReturnType = new" + + " ParameterizedTypeReference()" + ); } - @Test(dataProvider = "supportedLibraries") void testExtraAnnotations(Library library) { + @Test(dataProvider = "supportedLibraries") + void testExtraAnnotations(Library library) { final Path output = newTempFolder(); final String outputPath = output.toString().replace('\\', '/'); final CodegenConfigurator configurator = new CodegenConfigurator() @@ -1654,7 +1701,8 @@ public void testMicroprofileGenerateCorrectJacksonGenerator_issue18336() throws /** * See https://github.com/OpenAPITools/openapi-generator/issues/11340 */ - @Test public void testReferencedHeader2() { + @Test + public void testReferencedHeader2() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator().setGeneratorName("java") .setAdditionalProperties(Map.of(BeanValidationFeatures.USE_BEANVALIDATION, "true")) @@ -1675,7 +1723,8 @@ public void testMicroprofileGenerateCorrectJacksonGenerator_issue18336() throws .containsWithName("NotNull"); } - @Test public void testReturnTypeMapping() { + @Test + public void testReturnTypeMapping() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") @@ -1687,7 +1736,7 @@ public void testMicroprofileGenerateCorrectJacksonGenerator_issue18336() throws new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); assertThat(output.resolve("src/main/java/org/openapitools/client/api/DefaultApi.java")).content() - .contains("import java.util.Stack;"); + .contains("import java.util.Stack;"); } @Test @@ -1708,17 +1757,18 @@ public void testNativeClientExplodedQueryParamWithArrayProperty() { + " queryObject.getValues()));"); } - @Test public void testJdkHttpClientWithAndWithoutParentExtension() { + @Test + public void testJdkHttpClientWithAndWithoutParentExtension() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - // use default `okhttp-gson` - //.setLibrary(JavaClientCodegen.NATIVE) - .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") - .addAdditionalProperty(CodegenConstants.MODEL_PACKAGE, "xyz.abcdef.model") - .addAdditionalProperty(CodegenConstants.INVOKER_PACKAGE, "xyz.abcdef.invoker") - .setInputSpec("src/test/resources/3_0/allOf_extension_parent.yaml") - .setOutputDir(output.toString().replace("\\", "/")); + .setGeneratorName("java") + // use default `okhttp-gson` + //.setLibrary(JavaClientCodegen.NATIVE) + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(CodegenConstants.MODEL_PACKAGE, "xyz.abcdef.model") + .addAdditionalProperty(CodegenConstants.INVOKER_PACKAGE, "xyz.abcdef.invoker") + .setInputSpec("src/test/resources/3_0/allOf_extension_parent.yaml") + .setOutputDir(output.toString().replace("\\", "/")); DefaultGenerator generator = new DefaultGenerator(); generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true"); @@ -1728,18 +1778,19 @@ public void testNativeClientExplodedQueryParamWithArrayProperty() { validateJavaSourceFiles(files); assertThat(files).hasSize(27); assertThat(output.resolve("src/main/java/xyz/abcdef/model/Child.java")) - .content().contains("public class Child extends Person {"); + .content().contains("public class Child extends Person {"); assertThat(output.resolve("src/main/java/xyz/abcdef/model/Adult.java")) - .content().contains("public class Adult extends Person {"); + .content().contains("public class Adult extends Person {"); assertThat(output.resolve("src/main/java/xyz/abcdef/model/AnotherChild.java")) - .content().contains("public class AnotherChild {"); + .content().contains("public class AnotherChild {"); } - @Test public void testDiscriminatorWithMappingIssue14731() { + @Test + public void testDiscriminatorWithMappingIssue14731() { final Path output = newTempFolder(); final OpenAPI openAPI = new OpenAPIParser() - .readLocation("src/test/resources/bugs/issue_14731.yaml", null, new ParseOptions()) - .getOpenAPI(); + .readLocation("src/test/resources/bugs/issue_14731.yaml", null, new ParseOptions()) + .getOpenAPI(); final JavaClientCodegen codegen = new JavaClientCodegen(); codegen.setOutputDir(output.toString()); @@ -1762,16 +1813,17 @@ public void testNativeClientExplodedQueryParamWithArrayProperty() { generator.opts(input).generate(); assertThat(output.resolve("src/main/java/org/openapitools/client/model/ChildWithMappingADTO.java")) - .content().doesNotContain("@JsonTypeName"); + .content().doesNotContain("@JsonTypeName"); assertThat(output.resolve("src/main/java/org/openapitools/client/model/ChildWithMappingBDTO.java")) - .content().doesNotContain("@JsonTypeName"); + .content().doesNotContain("@JsonTypeName"); } - @Test public void testDiscriminatorWithoutMappingIssue14731() { + @Test + public void testDiscriminatorWithoutMappingIssue14731() { final Path output = newTempFolder(); final OpenAPI openAPI = new OpenAPIParser() - .readLocation("src/test/resources/bugs/issue_14731.yaml", null, new ParseOptions()) - .getOpenAPI(); + .readLocation("src/test/resources/bugs/issue_14731.yaml", null, new ParseOptions()) + .getOpenAPI(); final JavaClientCodegen codegen = new JavaClientCodegen(); codegen.setOutputDir(output.toString()); codegen.additionalProperties().put(CXFServerFeatures.LOAD_TEST_DATA_FROM_FILE, "true"); @@ -1794,16 +1846,17 @@ public void testNativeClientExplodedQueryParamWithArrayProperty() { generator.opts(input).generate(); assertThat(output.resolve("src/main/java/org/openapitools/client/model/ChildWithoutMappingADTO.java")) - .content().contains("@JsonTypeName"); + .content().contains("@JsonTypeName"); assertThat(output.resolve("src/main/java/org/openapitools/client/model/ChildWithoutMappingBDTO.java")) - .content().contains("@JsonTypeName"); + .content().contains("@JsonTypeName"); } - @Test public void testForJavaNativeJsonSubtype() { + @Test + public void testForJavaNativeJsonSubtype() { final Path output = newTempFolder(); final OpenAPI openAPI = new OpenAPIParser() - .readLocation("src/test/resources/bugs/issue_14917.yaml", null, new ParseOptions()) - .getOpenAPI(); + .readLocation("src/test/resources/bugs/issue_14917.yaml", null, new ParseOptions()) + .getOpenAPI(); final JavaClientCodegen codegen = new JavaClientCodegen(); codegen.setLibrary(JavaClientCodegen.NATIVE); codegen.setOutputDir(output.toString()); @@ -1811,30 +1864,31 @@ public void testNativeClientExplodedQueryParamWithArrayProperty() { new DefaultGenerator().opts(new ClientOptInput().openAPI(openAPI).config(codegen)).generate(); assertThat(output.resolve("src/main/java/org/openapitools/client/model/Cat.java")).content() - .contains("mappings.put(\"Cat\", Cat.class)") - .doesNotContain( - "@JsonSubTypes", - "mappings.put(\"cat\", Cat.class);", - "mappings.put(\"dog\", Dog.class);", - "mappings.put(\"lizard\", Lizard.class);" - ); + .contains("mappings.put(\"Cat\", Cat.class)") + .doesNotContain( + "@JsonSubTypes", + "mappings.put(\"cat\", Cat.class);", + "mappings.put(\"dog\", Dog.class);", + "mappings.put(\"lizard\", Lizard.class);" + ); assertThat(output.resolve("src/main/java/org/openapitools/client/model/Pet.java")).content() - .contains( - "@JsonSubTypes.Type(value = Cat.class, name = \"cat\")", - "@JsonSubTypes.Type(value = Dog.class, name = \"dog\")", - "@JsonSubTypes.Type(value = Lizard.class, name = \"lizard\")", - "mappings.put(\"cat\", Cat.class)", - "mappings.put(\"dog\", Dog.class)", - "mappings.put(\"lizard\", Lizard.class)", - "mappings.put(\"Pet\", Pet.class)" - ).doesNotContain( - "@JsonSubTypes.Type(value = Cat.class, name = \"Cat\")", - "@JsonSubTypes.Type(value = Dog.class, name = \"Dog\")", - "@JsonSubTypes.Type(value = Lizard.class, name = \"Lizard\")" - ); - } - - @Test public void shouldProperlyExplodeRestTemplateQueryParameters_issue907() { + .contains( + "@JsonSubTypes.Type(value = Cat.class, name = \"cat\")", + "@JsonSubTypes.Type(value = Dog.class, name = \"dog\")", + "@JsonSubTypes.Type(value = Lizard.class, name = \"lizard\")", + "mappings.put(\"cat\", Cat.class)", + "mappings.put(\"dog\", Dog.class)", + "mappings.put(\"lizard\", Lizard.class)", + "mappings.put(\"Pet\", Pet.class)" + ).doesNotContain( + "@JsonSubTypes.Type(value = Cat.class, name = \"Cat\")", + "@JsonSubTypes.Type(value = Dog.class, name = \"Dog\")", + "@JsonSubTypes.Type(value = Lizard.class, name = \"Lizard\")" + ); + } + + @Test + public void shouldProperlyExplodeRestTemplateQueryParameters_issue907() { final Map files = generateFromContract( "src/test/resources/3_0/java/explode-query-parameter.yaml", @@ -1892,7 +1946,8 @@ private static Map generateFromContract( final String library, final Map properties ) { - return generateFromContract(pathToSpecification, library, properties, configurator -> {}); + return generateFromContract(pathToSpecification, library, properties, configurator -> { + }); } @SneakyThrows @@ -1905,21 +1960,22 @@ private static Map generateFromContract( final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(library) - .setAdditionalProperties(properties) - .setInputSpec(pathToSpecification) - .setOutputDir(output.toString()); + .setGeneratorName("java") + .setLibrary(library) + .setAdditionalProperties(properties) + .setInputSpec(pathToSpecification) + .setOutputDir(output.toString()); consumer.accept(configurator); return new DefaultGenerator().opts(configurator.toClientOptInput()).generate() - .stream().collect(Collectors.toMap(File::getName, Function.identity())); + .stream().collect(Collectors.toMap(File::getName, Function.identity())); } - @Test public void testForJavaApacheHttpClientJsonSubtype() { + @Test + public void testForJavaApacheHttpClientJsonSubtype() { final Path output = newTempFolder(); OpenAPI openAPI = new OpenAPIParser() - .readLocation("src/test/resources/bugs/issue_14917.yaml", null, new ParseOptions()) - .getOpenAPI(); + .readLocation("src/test/resources/bugs/issue_14917.yaml", null, new ParseOptions()) + .getOpenAPI(); JavaClientCodegen codegen = new JavaClientCodegen(); codegen.setLibrary(JavaClientCodegen.APACHE); @@ -1928,38 +1984,39 @@ private static Map generateFromContract( new DefaultGenerator().opts(new ClientOptInput().openAPI(openAPI).config(codegen)).generate(); assertThat(output.resolve("src/main/java/org/openapitools/client/model/Cat.java")).content() - .contains( - "@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property =" - + " \"petType\", visible = true)" - ).doesNotContain( - "mappings.put", - "@JsonSubTypes.Type(value = Cat.class, name = \"cat\")", - "@JsonSubTypes.Type(value = Dog.class, name = \"dog\")", - "@JsonSubTypes.Type(value = Lizard.class, name = \"lizard\")" - ); + .contains( + "@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property =" + + " \"petType\", visible = true)" + ).doesNotContain( + "mappings.put", + "@JsonSubTypes.Type(value = Cat.class, name = \"cat\")", + "@JsonSubTypes.Type(value = Dog.class, name = \"dog\")", + "@JsonSubTypes.Type(value = Lizard.class, name = \"lizard\")" + ); assertThat(output.resolve("src/main/java/org/openapitools/client/model/Pet.java")).content() - .contains( - "@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property =" - + " \"petType\", visible = true)", - "@JsonSubTypes.Type(value = Cat.class, name = \"cat\")", - "@JsonSubTypes.Type(value = Dog.class, name = \"dog\")", - "@JsonSubTypes.Type(value = Lizard.class, name = \"lizard\")" - ).doesNotContain( - "@JsonSubTypes.Type(value = Cat.class, name = \"Cat\")", - "@JsonSubTypes.Type(value = Dog.class, name = \"Dog\")", - "@JsonSubTypes.Type(value = Lizard.class, name = \"Lizard\")" - ); - } - - @Test public void testIsOverriddenProperty() { + .contains( + "@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property =" + + " \"petType\", visible = true)", + "@JsonSubTypes.Type(value = Cat.class, name = \"cat\")", + "@JsonSubTypes.Type(value = Dog.class, name = \"dog\")", + "@JsonSubTypes.Type(value = Lizard.class, name = \"lizard\")" + ).doesNotContain( + "@JsonSubTypes.Type(value = Cat.class, name = \"Cat\")", + "@JsonSubTypes.Type(value = Dog.class, name = \"Dog\")", + "@JsonSubTypes.Type(value = Lizard.class, name = \"Lizard\")" + ); + } + + @Test + public void testIsOverriddenProperty() { final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/allOf_composition_discriminator.yaml"); JavaClientCodegen codegen = new JavaClientCodegen(); codegen.setOpenAPI(openAPI); CodegenModel cm1 = codegen.fromModel("Cat", openAPI.getComponents().getSchemas().get("Cat")); - + CodegenProperty cp0 = cm1.getAllVars().get(0); Assertions.assertEquals(cp0.getName(), "petType"); Assertions.assertEquals(cp0.isOverridden, true); @@ -1969,11 +2026,12 @@ private static Map generateFromContract( Assertions.assertEquals(cp1.isOverridden, false); } - @Test public void testForJavaApacheHttpClientOverrideSetter() { + @Test + public void testForJavaApacheHttpClientOverrideSetter() { final Path output = newTempFolder(); OpenAPI openAPI = new OpenAPIParser() - .readLocation("src/test/resources/3_0/allOf_composition_discriminator.yaml", null, null) - .getOpenAPI(); + .readLocation("src/test/resources/3_0/allOf_composition_discriminator.yaml", null, null) + .getOpenAPI(); JavaClientCodegen codegen = new JavaClientCodegen(); codegen.setOutputDir(output.toString()); @@ -1982,16 +2040,17 @@ private static Map generateFromContract( new DefaultGenerator().opts(new ClientOptInput().openAPI(openAPI).config(codegen)).generate(); assertThat(output.resolve("src/main/java/org/openapitools/client/model/Cat.java")).content() - .contains(" @Override\n" + " public Cat petType(@javax.annotation.Nonnull String petType) {"); + .contains(" @Override\n" + " public Cat petType(@javax.annotation.Nonnull String petType) {"); assertThat(output.resolve("src/main/java/org/openapitools/client/model/Pet.java")).content() - .contains(" }\n" + "\n" + " public Pet petType(@javax.annotation.Nonnull String petType) {\n"); + .contains(" }\n" + "\n" + " public Pet petType(@javax.annotation.Nonnull String petType) {\n"); } - @Test public void testForJavaNativeClientOverrideSetter() { + @Test + public void testForJavaNativeClientOverrideSetter() { final Path output = newTempFolder(); final OpenAPI openAPI = new OpenAPIParser() - .readLocation("src/test/resources/3_0/allOf_composition_discriminator.yaml", null, null) - .getOpenAPI(); + .readLocation("src/test/resources/3_0/allOf_composition_discriminator.yaml", null, null) + .getOpenAPI(); final JavaClientCodegen codegen = new JavaClientCodegen(); codegen.setOutputDir(output.toString()); codegen.setLibrary(JavaClientCodegen.NATIVE); @@ -1999,12 +2058,13 @@ private static Map generateFromContract( new DefaultGenerator().opts(new ClientOptInput().openAPI(openAPI).config(codegen)).generate(); assertThat(output.resolve("src/main/java/org/openapitools/client/model/Cat.java")).content() - .contains(" @Override\n" + " public Cat petType(@javax.annotation.Nonnull String petType) {"); + .contains(" @Override\n" + " public Cat petType(@javax.annotation.Nonnull String petType) {"); assertThat(output.resolve("src/main/java/org/openapitools/client/model/Pet.java")).content() - .contains(" }\n" + "\n" + " public Pet petType(@javax.annotation.Nonnull String petType) {\n"); + .contains(" }\n" + "\n" + " public Pet petType(@javax.annotation.Nonnull String petType) {\n"); } - @Test public void testDeprecatedProperty() { + @Test + public void testDeprecatedProperty() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") @@ -2016,14 +2076,15 @@ private static Map generateFromContract( validateJavaSourceFiles(files); TestUtils.assertFileContains( - output.resolve("src/main/java/org/openapitools/client/model/BigDog.java"), - "@Deprecated\n public BigDog declawed(@javax.annotation.Nullable Boolean declawed) {", // deprecated builder method - "@Deprecated\n @javax.annotation.Nullable\n\n public Boolean getDeclawed() {", // deprecated getter - "@Deprecated\n" + " public void setDeclawed(@javax.annotation.Nullable Boolean declawed) {" // deprecated setter + output.resolve("src/main/java/org/openapitools/client/model/BigDog.java"), + "@Deprecated\n public BigDog declawed(@javax.annotation.Nullable Boolean declawed) {", // deprecated builder method + "@Deprecated\n @javax.annotation.Nullable\n\n public Boolean getDeclawed() {", // deprecated getter + "@Deprecated\n" + " public void setDeclawed(@javax.annotation.Nullable Boolean declawed) {" // deprecated setter ); } - @Test public void testDeprecatedPropertyJersey3() { + @Test + public void testDeprecatedPropertyJersey3() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") @@ -2035,14 +2096,14 @@ private static Map generateFromContract( validateJavaSourceFiles(files); TestUtils.assertFileContains( - output.resolve("src/main/java/org/openapitools/client/model/BigDog.java"), - "@Deprecated\n public BigDog declawed(@jakarta.annotation.Nullable Boolean declawed) {", // deprecated builder method - "@Deprecated\n @jakarta.annotation.Nullable\n @JsonProperty(JSON_PROPERTY_DECLAWED)\n" - + " @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n" - + " public Boolean getDeclawed() {", // deprecated getter - "@Deprecated\n @JsonProperty(JSON_PROPERTY_DECLAWED)\n" - + " @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n" - + " public void setDeclawed(@jakarta.annotation.Nullable Boolean declawed) {" // deprecated setter + output.resolve("src/main/java/org/openapitools/client/model/BigDog.java"), + "@Deprecated\n public BigDog declawed(@jakarta.annotation.Nullable Boolean declawed) {", // deprecated builder method + "@Deprecated\n @jakarta.annotation.Nullable\n @JsonProperty(JSON_PROPERTY_DECLAWED)\n" + + " @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n" + + " public Boolean getDeclawed() {", // deprecated getter + "@Deprecated\n @JsonProperty(JSON_PROPERTY_DECLAWED)\n" + + " @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n" + + " public void setDeclawed(@jakarta.annotation.Nullable Boolean declawed) {" // deprecated setter ); } @@ -2055,11 +2116,11 @@ public static Object[][] librariesToRegressionTestForIssue15684() { public void shouldNotAddAdditionalModelAnnotationsToAbstractOpenApiSchema_issue15684(String library) { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(library) - .addAdditionalProperty(AbstractJavaCodegen.ADDITIONAL_MODEL_TYPE_ANNOTATIONS, "@annotation1;@annotation2") - .setInputSpec("src/test/resources/3_0/deprecated-properties.yaml") - .setOutputDir(output.toString().replace("\\", "/")); + .setGeneratorName("java") + .setLibrary(library) + .addAdditionalProperty(AbstractJavaCodegen.ADDITIONAL_MODEL_TYPE_ANNOTATIONS, "@annotation1;@annotation2") + .setInputSpec("src/test/resources/3_0/deprecated-properties.yaml") + .setOutputDir(output.toString().replace("\\", "/")); Map files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate().stream() .collect(Collectors.toMap(File::getName, Function.identity())); @@ -2074,15 +2135,16 @@ public void shouldNotAddAdditionalModelAnnotationsToAbstractOpenApiSchema_issue1 .containsWithName("annotation2"); } - @Test public void testRestTemplateWithGeneratedClientAsBeanDisabled() { + @Test + public void testRestTemplateWithGeneratedClientAsBeanDisabled() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") - .addAdditionalProperty(JavaClientCodegen.GENERATE_CLIENT_AS_BEAN, false) - .setLibrary(JavaClientCodegen.RESTTEMPLATE) - .setInputSpec("src/test/resources/3_0/petstore.yaml") - .setOutputDir(output.toString().replace("\\", "/")); + .setGeneratorName("java") + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.GENERATE_CLIENT_AS_BEAN, false) + .setLibrary(JavaClientCodegen.RESTTEMPLATE) + .setInputSpec("src/test/resources/3_0/petstore.yaml") + .setOutputDir(output.toString().replace("\\", "/")); List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); @@ -2091,15 +2153,16 @@ public void shouldNotAddAdditionalModelAnnotationsToAbstractOpenApiSchema_issue1 TestUtils.assertFileNotContains(output.resolve("src/main/java/xyz/abcdef/api/PetApi.java"), "@Component"); } - @Test public void testRestTemplateWithGeneratedClientAsBeanEnabled() { + @Test + public void testRestTemplateWithGeneratedClientAsBeanEnabled() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") - .addAdditionalProperty(JavaClientCodegen.GENERATE_CLIENT_AS_BEAN, true) - .setLibrary(JavaClientCodegen.RESTTEMPLATE) - .setInputSpec("src/test/resources/3_0/petstore.yaml") - .setOutputDir(output.toString().replace("\\", "/")); + .setGeneratorName("java") + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.GENERATE_CLIENT_AS_BEAN, true) + .setLibrary(JavaClientCodegen.RESTTEMPLATE) + .setInputSpec("src/test/resources/3_0/petstore.yaml") + .setOutputDir(output.toString().replace("\\", "/")); List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); @@ -2108,15 +2171,16 @@ public void shouldNotAddAdditionalModelAnnotationsToAbstractOpenApiSchema_issue1 TestUtils.assertFileContains(output.resolve("src/main/java/xyz/abcdef/api/PetApi.java"), "@Component"); } - @Test public void testRestTemplateWithUseBeanValidationEnabled() { + @Test + public void testRestTemplateWithUseBeanValidationEnabled() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.RESTTEMPLATE) - .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") - .addAdditionalProperty(JavaClientCodegen.USE_BEANVALIDATION, true) - .setInputSpec("src/test/resources/3_0/petstore.yaml") - .setOutputDir(output.toString().replace("\\", "/")); + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.RESTTEMPLATE) + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.USE_BEANVALIDATION, true) + .setInputSpec("src/test/resources/3_0/petstore.yaml") + .setOutputDir(output.toString().replace("\\", "/")); List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); @@ -2125,15 +2189,16 @@ public void shouldNotAddAdditionalModelAnnotationsToAbstractOpenApiSchema_issue1 TestUtils.assertFileContains(output.resolve("src/main/java/org/openapitools/client/model/Pet.java"), "@Valid"); } - @Test public void testRestTemplateWithUseBeanValidationDisabled() { + @Test + public void testRestTemplateWithUseBeanValidationDisabled() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.RESTTEMPLATE) - .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") - .addAdditionalProperty(JavaClientCodegen.USE_BEANVALIDATION, false) - .setInputSpec("src/test/resources/3_0/petstore.yaml") - .setOutputDir(output.toString().replace("\\", "/")); + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.RESTTEMPLATE) + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.USE_BEANVALIDATION, false) + .setInputSpec("src/test/resources/3_0/petstore.yaml") + .setOutputDir(output.toString().replace("\\", "/")); List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); @@ -2142,15 +2207,16 @@ public void shouldNotAddAdditionalModelAnnotationsToAbstractOpenApiSchema_issue1 TestUtils.assertFileNotContains(output.resolve("src/main/java/org/openapitools/client/model/Pet.java"), "@Valid"); } - @Test public void testRestTemplateWithPerformBeanValidationEnabled() { + @Test + public void testRestTemplateWithPerformBeanValidationEnabled() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.RESTTEMPLATE) - .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") - .addAdditionalProperty(JavaClientCodegen.PERFORM_BEANVALIDATION, true) - .setInputSpec("src/test/resources/3_0/petstore.yaml") - .setOutputDir(output.toString().replace("\\", "/")); + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.RESTTEMPLATE) + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.PERFORM_BEANVALIDATION, true) + .setInputSpec("src/test/resources/3_0/petstore.yaml") + .setOutputDir(output.toString().replace("\\", "/")); List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); @@ -2159,15 +2225,16 @@ public void shouldNotAddAdditionalModelAnnotationsToAbstractOpenApiSchema_issue1 TestUtils.assertFileExists(output.resolve("src/main/java/xyz/abcdef/BeanValidationException.java")); } - @Test public void testRestTemplateWithPerformBeanValidationDisabled() { + @Test + public void testRestTemplateWithPerformBeanValidationDisabled() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") - .addAdditionalProperty(JavaClientCodegen.PERFORM_BEANVALIDATION, false) - .setLibrary(JavaClientCodegen.RESTTEMPLATE) - .setInputSpec("src/test/resources/3_0/petstore.yaml") - .setOutputDir(output.toString().replace("\\", "/")); + .setGeneratorName("java") + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.PERFORM_BEANVALIDATION, false) + .setLibrary(JavaClientCodegen.RESTTEMPLATE) + .setInputSpec("src/test/resources/3_0/petstore.yaml") + .setOutputDir(output.toString().replace("\\", "/")); List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); @@ -2176,47 +2243,50 @@ public void shouldNotAddAdditionalModelAnnotationsToAbstractOpenApiSchema_issue1 TestUtils.assertFileNotExists(output.resolve("src/main/java/org/openapitools/client/invoker/BeanValidationException.java")); } - @Test public void testLogicToAvoidStackOverflow() { + @Test + public void testLogicToAvoidStackOverflow() { final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") - .addAdditionalProperty(JavaClientCodegen.GENERATE_CLIENT_AS_BEAN, true) - .setLibrary(JavaClientCodegen.RESTTEMPLATE) - .setInputSpec("src/test/resources/3_0/issue_12929.yaml") - .setOutputDir(newTempFolder().toString().replace("\\", "/")); + .setGeneratorName("java") + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.GENERATE_CLIENT_AS_BEAN, true) + .setLibrary(JavaClientCodegen.RESTTEMPLATE) + .setInputSpec("src/test/resources/3_0/issue_12929.yaml") + .setOutputDir(newTempFolder().toString().replace("\\", "/")); new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); // shouldn't throw stackoverflow exception } - @Test public void testWebClientSupportListOfStringReturnType_issue7118() { + @Test + public void testWebClientSupportListOfStringReturnType_issue7118() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") - .addAdditionalProperty(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true) - .setLibrary(JavaClientCodegen.WEBCLIENT) - .setInputSpec("src/test/resources/bugs/issue_7118.yaml") - .setOutputDir(output.toString().replace("\\", "/")); + .setGeneratorName("java") + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true) + .setLibrary(JavaClientCodegen.WEBCLIENT) + .setInputSpec("src/test/resources/bugs/issue_7118.yaml") + .setOutputDir(output.toString().replace("\\", "/")); List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); assertThat(output.resolve("src/main/java/xyz/abcdef/api/UsersApi.java")).content() - .contains( - // set of string - "ParameterizedTypeReference> localVarReturnType = new" - + " ParameterizedTypeReference>() {};", - "getUserIdSetRequestCreation().toEntity(localVarReturnType)", - // list of string - "ParameterizedTypeReference> localVarReturnType = new" - + " ParameterizedTypeReference>() {};", - "getUserIdListRequestCreation().toEntity(localVarReturnType)" - ); + .contains( + // set of string + "ParameterizedTypeReference> localVarReturnType = new" + + " ParameterizedTypeReference>() {};", + "getUserIdSetRequestCreation().toEntity(localVarReturnType)", + // list of string + "ParameterizedTypeReference> localVarReturnType = new" + + " ParameterizedTypeReference>() {};", + "getUserIdListRequestCreation().toEntity(localVarReturnType)" + ); } - @Test public void testEnumCaseInsensitive_issue8084() { + @Test + public void testEnumCaseInsensitive_issue8084() { final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/2_0/issue8084.yaml"); final JavaClientCodegen codegen = new JavaClientCodegen(); codegen.setOpenAPI(openAPI); @@ -2224,14 +2294,15 @@ public void shouldNotAddAdditionalModelAnnotationsToAbstractOpenApiSchema_issue1 codegen.additionalProperties().put(USE_ENUM_CASE_INSENSITIVE, "true"); Map files = new DefaultGenerator().opts(new ClientOptInput().openAPI(openAPI).config(codegen)) - .generate().stream().collect(Collectors.toMap(File::getName, Function.identity())); + .generate().stream().collect(Collectors.toMap(File::getName, Function.identity())); JavaFileAssert.assertThat(files.get("EnumTest.java")) .assertMethod("fromValue") .bodyContainsLines("if (b.value.equalsIgnoreCase(value)) {"); } - @Test public void testEnumCaseSensitive_issue8084() { + @Test + public void testEnumCaseSensitive_issue8084() { final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/2_0/issue8084.yaml"); final JavaClientCodegen codegen = new JavaClientCodegen(); codegen.setOpenAPI(openAPI); @@ -2239,22 +2310,23 @@ public void shouldNotAddAdditionalModelAnnotationsToAbstractOpenApiSchema_issue1 codegen.additionalProperties().put(USE_ENUM_CASE_INSENSITIVE, "false"); Map files = new DefaultGenerator().opts(new ClientOptInput().openAPI(openAPI).config(codegen)) - .generate().stream().collect(Collectors.toMap(File::getName, Function.identity())); + .generate().stream().collect(Collectors.toMap(File::getName, Function.identity())); JavaFileAssert.assertThat(files.get("EnumTest.java")) - .assertMethod("fromValue") - .bodyContainsLines("if (b.value.equals(value)) {"); + .assertMethod("fromValue") + .bodyContainsLines("if (b.value.equals(value)) {"); } - @Test public void testWebClientResponseTypeWithUseAbstractionForFiles_issue16589() { + @Test + public void testWebClientResponseTypeWithUseAbstractionForFiles_issue16589() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") - .addAdditionalProperty(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true) - .setLibrary(JavaClientCodegen.WEBCLIENT) - .setInputSpec("src/test/resources/3_0/issue13146_file_abstraction_response.yaml") - .setOutputDir(output.toString().replace("\\", "/")); + .setGeneratorName("java") + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true) + .setLibrary(JavaClientCodegen.WEBCLIENT) + .setInputSpec("src/test/resources/3_0/issue13146_file_abstraction_response.yaml") + .setOutputDir(output.toString().replace("\\", "/")); List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); @@ -2266,7 +2338,8 @@ public void shouldNotAddAdditionalModelAnnotationsToAbstractOpenApiSchema_issue1 ); } - @Test public void testHandleConstantParams() { + @Test + public void testHandleConstantParams() { final Path output = newTempFolder(); final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/java/autoset_constant.yaml"); JavaClientCodegen codegen = new JavaClientCodegen(); @@ -2275,13 +2348,13 @@ public void shouldNotAddAdditionalModelAnnotationsToAbstractOpenApiSchema_issue1 codegen.setAutosetConstants(true); Map files = new DefaultGenerator().opts(new ClientOptInput().openAPI(openAPI).config(codegen)) - .generate().stream().collect(Collectors.toMap(File::getName, Function.identity())); + .generate().stream().collect(Collectors.toMap(File::getName, Function.identity())); File apiFile = files.get("HelloExampleApi.java"); Assertions.assertNotNull(apiFile); JavaFileAssert.assertThat(apiFile) - .assertMethod("helloCall", "String", "ApiCallback") - .bodyContainsLines("localVarHeaderParams.put(\"X-CUSTOM_CONSTANT_HEADER\", \"CONSTANT_VALUE\")"); + .assertMethod("helloCall", "String", "ApiCallback") + .bodyContainsLines("localVarHeaderParams.put(\"X-CUSTOM_CONSTANT_HEADER\", \"CONSTANT_VALUE\")"); } @Test @@ -2293,12 +2366,13 @@ public void testAllOfWithSinglePrimitiveTypeRef() { codegen.setAutosetConstants(true); Map files = new DefaultGenerator().opts(new ClientOptInput().openAPI(openAPI).config(codegen)) - .generate().stream().collect(Collectors.toMap(File::getName, Function.identity())); + .generate().stream().collect(Collectors.toMap(File::getName, Function.identity())); assertNull(files.get("AllOfDatetime.java")); } - @Test public void testOpenapiGeneratorIgnoreListOption() { + @Test + public void testOpenapiGeneratorIgnoreListOption() { final Path output = newTempFolder(); final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/allof_primitive.yaml"); JavaClientCodegen codegen = new JavaClientCodegen(); @@ -2306,9 +2380,9 @@ public void testAllOfWithSinglePrimitiveTypeRef() { codegen.setAutosetConstants(true); codegen.openapiGeneratorIgnoreList().add("README.md"); codegen.openapiGeneratorIgnoreList().add("pom.xml"); - + Map files = new DefaultGenerator().opts(new ClientOptInput().openAPI(openAPI).config(codegen)) - .generate().stream().collect(Collectors.toMap(File::getName, Function.identity())); + .generate().stream().collect(Collectors.toMap(File::getName, Function.identity())); // make sure README.md and pom.xml are not generated assertNull(files.get("README.md")); @@ -2317,14 +2391,14 @@ public void testAllOfWithSinglePrimitiveTypeRef() { @Test public void testRestTemplateHandleURIEnum() { - String[] expectedInnerEnumLines = new String[] { - "V1_SCHEMA_JSON(URI.create(\"https://example.com/v1/schema.json\"))", - "V2_SCHEMA_JSON(URI.create(\"https://example.com/v2/schema.json\"))" + String[] expectedInnerEnumLines = new String[]{ + "V1_SCHEMA_JSON(URI.create(\"https://example.com/v1/schema.json\"))", + "V2_SCHEMA_JSON(URI.create(\"https://example.com/v2/schema.json\"))" }; - String[] expectedEnumLines = new String[] { - "V1_METADATA_JSON(URI.create(\"https://example.com/v1/metadata.json\"))", - "V2_METADATA_JSON(URI.create(\"https://example.com/v2/metadata.json\"))" + String[] expectedEnumLines = new String[]{ + "V1_METADATA_JSON(URI.create(\"https://example.com/v1/metadata.json\"))", + "V2_METADATA_JSON(URI.create(\"https://example.com/v2/metadata.json\"))" }; testHandleURIEnum(JavaClientCodegen.RESTTEMPLATE, expectedInnerEnumLines, expectedEnumLines); @@ -2332,20 +2406,20 @@ public void testRestTemplateHandleURIEnum() { @Test public void testOkHttpGsonHandleURIEnum() { - String[] expectedInnerEnumLines = new String[] { - "V1_SCHEMA_JSON(URI.create(\"https://example.com/v1/schema.json\"))", - "V2_SCHEMA_JSON(URI.create(\"https://example.com/v2/schema.json\"))", - "jsonWriter.value(enumeration.getValue().toASCIIString())", - "URI value = URI.create(jsonReader.nextString())", - "URI value = URI.create(jsonElement.getAsString())" + String[] expectedInnerEnumLines = new String[]{ + "V1_SCHEMA_JSON(URI.create(\"https://example.com/v1/schema.json\"))", + "V2_SCHEMA_JSON(URI.create(\"https://example.com/v2/schema.json\"))", + "jsonWriter.value(enumeration.getValue().toASCIIString())", + "URI value = URI.create(jsonReader.nextString())", + "URI value = URI.create(jsonElement.getAsString())" }; - String[] expectedEnumLines = new String[] { - "V1_METADATA_JSON(URI.create(\"https://example.com/v1/metadata.json\"))", - "V2_METADATA_JSON(URI.create(\"https://example.com/v2/metadata.json\"))", - "jsonWriter.value(enumeration.getValue().toASCIIString())", - "URI value = URI.create(jsonReader.nextString())", - "URI value = URI.create(jsonElement.getAsString())" + String[] expectedEnumLines = new String[]{ + "V1_METADATA_JSON(URI.create(\"https://example.com/v1/metadata.json\"))", + "V2_METADATA_JSON(URI.create(\"https://example.com/v2/metadata.json\"))", + "jsonWriter.value(enumeration.getValue().toASCIIString())", + "URI value = URI.create(jsonReader.nextString())", + "URI value = URI.create(jsonElement.getAsString())" }; testHandleURIEnum(JavaClientCodegen.OKHTTP_GSON, expectedInnerEnumLines, expectedEnumLines); @@ -2353,15 +2427,15 @@ public void testOkHttpGsonHandleURIEnum() { @Test public void testMicroprofileHandleURIEnum() { - String[] expectedInnerEnumLines = new String[] { - "V1_SCHEMA_JSON(URI.create(\"https://example.com/v1/schema.json\"))", - "V2_SCHEMA_JSON(URI.create(\"https://example.com/v2/schema.json\"))", - "generator.write(obj.value.toASCIIString())" + String[] expectedInnerEnumLines = new String[]{ + "V1_SCHEMA_JSON(URI.create(\"https://example.com/v1/schema.json\"))", + "V2_SCHEMA_JSON(URI.create(\"https://example.com/v2/schema.json\"))", + "generator.write(obj.value.toASCIIString())" }; - String[] expectedEnumLines = new String[] { - "V1_METADATA_JSON(URI.create(\"https://example.com/v1/metadata.json\"))", - "V2_METADATA_JSON(URI.create(\"https://example.com/v2/metadata.json\"))" + String[] expectedEnumLines = new String[]{ + "V1_METADATA_JSON(URI.create(\"https://example.com/v1/metadata.json\"))", + "V2_METADATA_JSON(URI.create(\"https://example.com/v2/metadata.json\"))" }; testHandleURIEnum(JavaClientCodegen.MICROPROFILE, expectedInnerEnumLines, expectedEnumLines); @@ -2374,9 +2448,9 @@ private void testHandleURIEnum(String library, String[] expectedInnerEnumLines, .setLibrary(library) .setInputSpec("src/test/resources/3_0/enum-and-inner-enum-uri.yaml") .setOutputDir(output.toString().replace("\\", "/")); - + Map files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate() - .stream().collect(Collectors.toMap(File::getName, Function.identity())); + .stream().collect(Collectors.toMap(File::getName, Function.identity())); // enum File modelFile = files.get("Metadata.java"); @@ -2389,7 +2463,8 @@ private void testHandleURIEnum(String library, String[] expectedInnerEnumLines, JavaFileAssert.assertThat(apiFile).fileContains(expectedInnerEnumLines); } - @Test public void testQueryParamsExploded_whenQueryParamIsNull() { + @Test + public void testQueryParamsExploded_whenQueryParamIsNull() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") @@ -2404,7 +2479,8 @@ private void testHandleURIEnum(String library, String[] expectedInnerEnumLines, TestUtils.assertFileContains(output.resolve("src/main/java/xyz/abcdef/api/DepartmentApi.java"), "if (filter != null) {"); } - @Test public void generateAllArgsConstructor() { + @Test + public void generateAllArgsConstructor() { Map files = generateFromContract("src/test/resources/3_0/java/all_args_constructor.yaml", JavaClientCodegen.RESTTEMPLATE, Map.of(AbstractJavaCodegen.GENERATE_CONSTRUCTOR_WITH_ALL_ARGS, Boolean.TRUE), codegenConfigurator -> codegenConfigurator.addOpenapiNormalizer("REFACTOR_ALLOF_WITH_PROPERTIES_ONLY", "false")); @@ -2435,7 +2511,8 @@ private void testHandleURIEnum(String library, String[] expectedInnerEnumLines, .hasParameter("_list").toConstructor(); } - @Test public void generateAllArgsConstructor_REFACTOR_ALLOF_WITH_PROPERTIES_ONLY() { + @Test + public void generateAllArgsConstructor_REFACTOR_ALLOF_WITH_PROPERTIES_ONLY() { // try the generation with some additional OpenAPINormalizers Map files = generateFromContract("src/test/resources/3_0/java/all_args_constructor.yaml", JavaClientCodegen.RESTTEMPLATE, @@ -2463,7 +2540,8 @@ private void testHandleURIEnum(String library, String[] expectedInnerEnumLines, .assertConstructor("Integer", "String", "LocalDate", "String", "String"); } - @Test public void testRestClientFormMultipart() { + @Test + public void testRestClientFormMultipart() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") @@ -2471,57 +2549,59 @@ private void testHandleURIEnum(String library, String[] expectedInnerEnumLines, .setAdditionalProperties(Map.of(CodegenConstants.API_PACKAGE, "xyz.abcdef.api")) .setInputSpec("src/test/resources/3_0/form-multipart-binary-array.yaml") .setOutputDir(output.toString().replace("\\", "/")); - + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); TestUtils.assertFileContains( - output.resolve("src/main/java/xyz/abcdef/api/MultipartApi.java"), - // multiple files - "multipartArray(List files)", - "formParams.addAll(\"files\"," - + " files.stream().map(FileSystemResource::new).collect(Collectors.toList()));", - - // mixed - "multipartMixed(MultipartMixedStatus status, File _file, MultipartMixedRequestMarker marker, List statusArray)", - "formParams.add(\"file\", new FileSystemResource(_file));", - - // single file - "multipartSingle(File _file)", - "formParams.add(\"file\", new FileSystemResource(_file));" + output.resolve("src/main/java/xyz/abcdef/api/MultipartApi.java"), + // multiple files + "multipartArray(List files)", + "formParams.addAll(\"files\"," + + " files.stream().map(FileSystemResource::new).collect(Collectors.toList()));", + + // mixed + "multipartMixed(MultipartMixedStatus status, File _file, MultipartMixedRequestMarker marker, List statusArray)", + "formParams.add(\"file\", new FileSystemResource(_file));", + + // single file + "multipartSingle(File _file)", + "formParams.add(\"file\", new FileSystemResource(_file));" ); } - @Test public void testRestClientWithUseAbstractionForFiles() { + @Test + public void testRestClientWithUseAbstractionForFiles() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") - .addAdditionalProperty(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true) - .setLibrary(JavaClientCodegen.RESTCLIENT) - .setInputSpec("src/test/resources/3_0/form-multipart-binary-array.yaml") - .setOutputDir(output.toString().replace("\\", "/")); + .setGeneratorName("java") + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true) + .setLibrary(JavaClientCodegen.RESTCLIENT) + .setInputSpec("src/test/resources/3_0/form-multipart-binary-array.yaml") + .setOutputDir(output.toString().replace("\\", "/")); List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); TestUtils.assertFileContains( - output.resolve("src/main/java/xyz/abcdef/api/MultipartApi.java"), - // multiple files - "multipartArray(java.util.Collection files)", - "formParams.addAll(\"files\", files.stream().collect(Collectors.toList()));", - - // mixed - "multipartMixed(MultipartMixedStatus status, org.springframework.core.io.AbstractResource _file, MultipartMixedRequestMarker marker, List statusArray)", - "formParams.add(\"file\", _file);", - - // single file - "multipartSingle(org.springframework.core.io.AbstractResource _file)", - "formParams.add(\"file\", _file);" + output.resolve("src/main/java/xyz/abcdef/api/MultipartApi.java"), + // multiple files + "multipartArray(java.util.Collection files)", + "formParams.addAll(\"files\", files.stream().collect(Collectors.toList()));", + + // mixed + "multipartMixed(MultipartMixedStatus status, org.springframework.core.io.AbstractResource _file, MultipartMixedRequestMarker marker, List statusArray)", + "formParams.add(\"file\", _file);", + + // single file + "multipartSingle(org.springframework.core.io.AbstractResource _file)", + "formParams.add(\"file\", _file);" ); } - @Test public void testRestClientWithFreeFormInQueryParameters() { + @Test + public void testRestClientWithFreeFormInQueryParameters() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator().setGeneratorName("java") .setLibrary(JavaClientCodegen.RESTCLIENT) @@ -2535,189 +2615,198 @@ private void testHandleURIEnum(String library, String[] expectedInnerEnumLines, TestUtils.assertFileContains(output.resolve("src/main/java/xyz/abcdef/ApiClient.java"), "value instanceof Map"); } - @Test public void testRestClientJsonCreatorWithNullable_issue12790() { + @Test + public void testRestClientJsonCreatorWithNullable_issue12790() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .addAdditionalProperty(AbstractJavaCodegen.OPENAPI_NULLABLE, "true") - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.RESTCLIENT) - .setInputSpec("src/test/resources/bugs/issue_12790.yaml") - .setOutputDir(output.toString().replace("\\", "/")); + .addAdditionalProperty(AbstractJavaCodegen.OPENAPI_NULLABLE, "true") + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.RESTCLIENT) + .setInputSpec("src/test/resources/bugs/issue_12790.yaml") + .setOutputDir(output.toString().replace("\\", "/")); Map files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate().stream() .collect(Collectors.toMap(File::getName, Function.identity())); JavaFileAssert.assertThat(files.get("TestObject.java")) - .printFileContent() - .assertConstructor("String", "String") - .bodyContainsLines( - "this.nullableProperty = nullableProperty == null ? JsonNullable.undefined() :" - + " JsonNullable.of(nullableProperty);", - "this.notNullableProperty = notNullableProperty;" - ); + .printFileContent() + .assertConstructor("String", "String") + .bodyContainsLines( + "this.nullableProperty = nullableProperty == null ? JsonNullable.undefined() :" + + " JsonNullable.of(nullableProperty);", + "this.notNullableProperty = notNullableProperty;" + ); } - @Test public void testRestClientSupportListOfStringReturnType_issue7118() { + @Test + public void testRestClientSupportListOfStringReturnType_issue7118() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") - .addAdditionalProperty(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true) - .setLibrary(JavaClientCodegen.RESTCLIENT) - .setInputSpec("src/test/resources/bugs/issue_7118.yaml") - .setOutputDir(output.toString().replace("\\", "/")); + .setGeneratorName("java") + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true) + .setLibrary(JavaClientCodegen.RESTCLIENT) + .setInputSpec("src/test/resources/bugs/issue_7118.yaml") + .setOutputDir(output.toString().replace("\\", "/")); List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); TestUtils.assertFileContains( - output.resolve("src/main/java/xyz/abcdef/api/UsersApi.java"), - // set of string - "ParameterizedTypeReference> localVarReturnType = new" - + " ParameterizedTypeReference<>() {};", - "getUserIdSetRequestCreation().toEntity(localVarReturnType)", - // list of string - "ParameterizedTypeReference> localVarReturnType = new" - + " ParameterizedTypeReference<>() {};", - "getUserIdListRequestCreation().toEntity(localVarReturnType)" + output.resolve("src/main/java/xyz/abcdef/api/UsersApi.java"), + // set of string + "ParameterizedTypeReference> localVarReturnType = new" + + " ParameterizedTypeReference<>() {};", + "getUserIdSetRequestCreation().toEntity(localVarReturnType)", + // list of string + "ParameterizedTypeReference> localVarReturnType = new" + + " ParameterizedTypeReference<>() {};", + "getUserIdListRequestCreation().toEntity(localVarReturnType)" ); } - @Test public void testRestClientResponseTypeWithUseAbstractionForFiles_issue16589() { + @Test + public void testRestClientResponseTypeWithUseAbstractionForFiles_issue16589() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") - .addAdditionalProperty(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true) - .setLibrary(JavaClientCodegen.RESTCLIENT) - .setInputSpec("src/test/resources/3_0/issue13146_file_abstraction_response.yaml") - .setOutputDir(output.toString().replace("\\", "/")); + .setGeneratorName("java") + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true) + .setLibrary(JavaClientCodegen.RESTCLIENT) + .setInputSpec("src/test/resources/3_0/issue13146_file_abstraction_response.yaml") + .setOutputDir(output.toString().replace("\\", "/")); List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); TestUtils.assertFileContains( - output.resolve("src/main/java/xyz/abcdef/api/ResourceApi.java"), - "org.springframework.core.io.Resource resourceInResponse()", - "ResponseEntity resourceInResponseWithHttpInfo()", - "ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>()" + output.resolve("src/main/java/xyz/abcdef/api/ResourceApi.java"), + "org.springframework.core.io.Resource resourceInResponse()", + "ResponseEntity resourceInResponseWithHttpInfo()", + "ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>()" ); } - @Test void testBuilderJavaClient() { + @Test + void testBuilderJavaClient() { Map files = generateFromContract( - "src/test/resources/3_0/java/builder.yaml", - JavaClientCodegen.RESTTEMPLATE, - Map.of(AbstractJavaCodegen.GENERATE_BUILDERS, Boolean.TRUE) + "src/test/resources/3_0/java/builder.yaml", + JavaClientCodegen.RESTTEMPLATE, + Map.of(AbstractJavaCodegen.GENERATE_BUILDERS, Boolean.TRUE) ); - + JavaFileAssert.assertThat(files.get("Pet.java")) - .fileContains( - "protected String petReadonlyProperty", "toBuilder()", "builder()", "public static class Builder {" - ); + .fileContains( + "protected String petReadonlyProperty", "toBuilder()", "builder()", "public static class Builder {" + ); JavaFileAssert.assertThat(files.get("Snake.java")) - .fileContains( - "toBuilder()", - "builder()", - "public static class Builder extends Reptile.Builder {", - ".petType(getPetType())", - ".name(getName())", - "hasLegs(getHasLegs())" - ); + .fileContains( + "toBuilder()", + "builder()", + "public static class Builder extends Reptile.Builder {", + ".petType(getPetType())", + ".name(getName())", + "hasLegs(getHasLegs())" + ); } - @DataProvider Iterator serializationLibraries() { + @DataProvider + Iterator serializationLibraries() { return new JavaClientCodegen().supportedLibraries().keySet().iterator(); } - - @Test(dataProvider = "serializationLibraries") void setsDefaultSerializationLibrary(String library) { + + @Test(dataProvider = "serializationLibraries") + void setsDefaultSerializationLibrary(String library) { var codegen = new JavaClientCodegen(); codegen.setLibrary(library); codegen.processOpts(); - + assertThat(codegen.additionalProperties()) - .containsAnyOf( - entry(SERIALIZATION_LIBRARY_GSON, "true"), - entry(SERIALIZATION_LIBRARY_JACKSON, "true"), - entry(SERIALIZATION_LIBRARY_JSONB, "true") - ); + .containsAnyOf( + entry(SERIALIZATION_LIBRARY_GSON, "true"), + entry(SERIALIZATION_LIBRARY_JACKSON, "true"), + entry(SERIALIZATION_LIBRARY_JSONB, "true") + ); } - + /** * Regression test for #18515: * When GSON is selected as serializer, there should not be any jackson references * (except jackson-databind-nullable that is, which is only added when openApiNullable=true) */ - @Test(dataProvider = "librariesSupportingGson") void gsonCodeDoesNotContainJacksonReferences(Library library) { + @Test(dataProvider = "librariesSupportingGson") + void gsonCodeDoesNotContainJacksonReferences(Library library) { final CodegenConfigurator configurator = new CodegenConfigurator() - .addAdditionalProperty(SERIALIZATION_LIBRARY, Serializer.GSON) - .addAdditionalProperty(OPENAPI_NULLABLE, "false") - .setGeneratorName("java") - .setLibrary(library.getValue()) - .setInputSpec("src/test/resources/3_0/java/autoset_constant.yaml") - .setOutputDir(newTempFolder().toString()); + .addAdditionalProperty(SERIALIZATION_LIBRARY, Serializer.GSON) + .addAdditionalProperty(OPENAPI_NULLABLE, "false") + .setGeneratorName("java") + .setLibrary(library.getValue()) + .setInputSpec("src/test/resources/3_0/java/autoset_constant.yaml") + .setOutputDir(newTempFolder().toString()); var generator = new DefaultGenerator(); generator.setGenerateMetadata(false); - + List files = generator.opts(configurator.toClientOptInput()).generate(); - + assertThat(files).allSatisfy( - file -> assertThat(file).content().doesNotContainIgnoringCase("jackson") + file -> assertThat(file).content().doesNotContainIgnoringCase("jackson") ); } - + /** * Regression test for #6496 */ - @Test void doesNotGenerateJacksonJsonFormatAnnotation_whenLibraryIsGson_andSerializeBigDecimalAsStringIsTrue() { + @Test + void doesNotGenerateJacksonJsonFormatAnnotation_whenLibraryIsGson_andSerializeBigDecimalAsStringIsTrue() { final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.OKHTTP_GSON) - .addAdditionalProperty(CodegenConstants.SERIALIZATION_LIBRARY, SERIALIZATION_LIBRARY_GSON) - .addAdditionalProperty(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, true) - .addGlobalProperty(CodegenConstants.MODELS, "FormatTest") - .addGlobalProperty(CodegenConstants.MODEL_DOCS, "false") - .addGlobalProperty(CodegenConstants.MODEL_TESTS, "false") - .setInputSpec("src/test/resources/2_0/java/issue-6496.yaml") - .setOutputDir(newTempFolder().toString().replace("\\", "/")); + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.OKHTTP_GSON) + .addAdditionalProperty(CodegenConstants.SERIALIZATION_LIBRARY, SERIALIZATION_LIBRARY_GSON) + .addAdditionalProperty(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, true) + .addGlobalProperty(CodegenConstants.MODELS, "FormatTest") + .addGlobalProperty(CodegenConstants.MODEL_DOCS, "false") + .addGlobalProperty(CodegenConstants.MODEL_TESTS, "false") + .setInputSpec("src/test/resources/2_0/java/issue-6496.yaml") + .setOutputDir(newTempFolder().toString().replace("\\", "/")); List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); assertThat(files).hasSize(1).first(FILE).content() - .doesNotContain( - "@JsonDeserialize(as = LinkedHashSet.class)", - "@JsonFormat(shape = JsonFormat.Shape.STRING)", - "com.fasterxml.jackson.databind.annotation.JsonDeserialize" - ); + .doesNotContain( + "@JsonDeserialize(as = LinkedHashSet.class)", + "@JsonFormat(shape = JsonFormat.Shape.STRING)", + "com.fasterxml.jackson.databind.annotation.JsonDeserialize" + ); } - + /** * Test that fix for #6496 has * no unwanted side effects on the existing feature (Jackson + bigDecimalAsString) */ - @Test void generatesJacksonJsonFormatAnnotation_whenLibraryIsJackson_andSerializeBigDecimalAsStringIsTrue() { + @Test + void generatesJacksonJsonFormatAnnotation_whenLibraryIsJackson_andSerializeBigDecimalAsStringIsTrue() { final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.NATIVE) - .addAdditionalProperty(CodegenConstants.SERIALIZATION_LIBRARY, SERIALIZATION_LIBRARY_JACKSON) - .addAdditionalProperty(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, true) - .addAdditionalProperty(OPENAPI_NULLABLE, false) - .addGlobalProperty(CodegenConstants.MODELS, "FormatTest") - .addGlobalProperty(CodegenConstants.MODEL_DOCS, "false") - .addGlobalProperty(CodegenConstants.MODEL_TESTS, "false") - .setInputSpec("src/test/resources/2_0/java/issue-6496.yaml") - .setOutputDir(newTempFolder().toString().replace("\\", "/")); - + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.NATIVE) + .addAdditionalProperty(CodegenConstants.SERIALIZATION_LIBRARY, SERIALIZATION_LIBRARY_JACKSON) + .addAdditionalProperty(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, true) + .addAdditionalProperty(OPENAPI_NULLABLE, false) + .addGlobalProperty(CodegenConstants.MODELS, "FormatTest") + .addGlobalProperty(CodegenConstants.MODEL_DOCS, "false") + .addGlobalProperty(CodegenConstants.MODEL_TESTS, "false") + .setInputSpec("src/test/resources/2_0/java/issue-6496.yaml") + .setOutputDir(newTempFolder().toString().replace("\\", "/")); + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); assertThat(files).hasSize(1).first(FILE).content() - .contains( - "@JsonDeserialize(as = LinkedHashSet.class)", - "@JsonFormat(shape = JsonFormat.Shape.STRING)", - "com.fasterxml.jackson.databind.annotation.JsonDeserialize" - ); + .contains( + "@JsonDeserialize(as = LinkedHashSet.class)", + "@JsonFormat(shape = JsonFormat.Shape.STRING)", + "com.fasterxml.jackson.databind.annotation.JsonDeserialize" + ); } - + /** * General XML annotations test (both JAXB and Jackson) *
@@ -2725,240 +2814,240 @@ private void testHandleURIEnum(String library, String[] expectedInnerEnumLines, * - Correct Jackson annotation when `wrapped: false` * - Microprofile generator missing Jackson annotations and namespaces */ - @Test(dataProvider = "librariesSupportingJackson") + @Test(dataProvider = "librariesSupportingJackson") void shouldGenerateCorrectXmlAnnotations(Library library) { // Arrange final CodegenConfigurator config = new CodegenConfigurator() - .addAdditionalProperty(CodegenConstants.WITH_XML, true) - .addAdditionalProperty(SERIALIZATION_LIBRARY, "jackson") - .addGlobalProperty(CodegenConstants.MODELS, "Pet") - .addGlobalProperty(CodegenConstants.MODEL_DOCS, null) - .addGlobalProperty(CodegenConstants.MODEL_TESTS, null) - .setGeneratorName("java") - .setInputSpec("src/test/resources/3_0/java/xml-annotations-test.yaml") - .setLibrary(library.value) - .setOutputDir(newTempFolder().toString()); + .addAdditionalProperty(CodegenConstants.WITH_XML, true) + .addAdditionalProperty(SERIALIZATION_LIBRARY, "jackson") + .addGlobalProperty(CodegenConstants.MODELS, "Pet") + .addGlobalProperty(CodegenConstants.MODEL_DOCS, null) + .addGlobalProperty(CodegenConstants.MODEL_TESTS, null) + .setGeneratorName("java") + .setInputSpec("src/test/resources/3_0/java/xml-annotations-test.yaml") + .setLibrary(library.value) + .setOutputDir(newTempFolder().toString()); // Act final List files = new DefaultGenerator().opts(config.toClientOptInput()).generate(); // Assert JavaFileAssert.assertThat(files.get(0)) - .assertTypeAnnotations() - .containsWithNameAndAttributes("XmlAccessorType", Map.of("value", "XmlAccessType.FIELD")) - .containsWithNameAndAttributes("XmlRootElement", Map.of("name", "\"Pet\"", "namespace", "\"urn:jacksonxml\"")) - .containsWithNameAndAttributes("JacksonXmlRootElement", Map.of("localName", "\"Pet\"", "namespace", "\"urn:jacksonxml\"")) - .toType() - - // ↓ test custom-name on wrapper element (https://swagger.io/docs/specification/data-models/representing-xml/#:~:text=Use%20xml/name%20to%20give%20different%20names) - .assertProperty("tags").assertPropertyAnnotations() - .doesNotContainWithName("XmlAttribute") - .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"Tag\"")) - .containsWithNameAndAttributes("XmlElementWrapper", Map.of("name", "\"TagList\"")) - .toProperty().toType() - .assertMethod("getTags") - .hasAnnotation("JacksonXmlProperty", Map.of("localName", "\"Tag\"")) - .hasAnnotation("JacksonXmlElementWrapper", Map.of("localName", "\"TagList\"", "useWrapping", "true")) - .toFileAssert() - - // ↓ custom internal xml-array element name, non-wrapped (1st example in https://spec.openapis.org/oas/v3.0.0#xml-arrays) - .assertProperty("friends").assertPropertyAnnotations() - .doesNotContainWithName("XmlAttribute") - .doesNotContainWithName("XmlElementWrapper") - .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"friend-pet\"")) - .toProperty().toType() - .assertMethod("getFriends") - .hasAnnotation("JacksonXmlProperty", Map.of("localName", "\"friend-pet\"")) - .hasAnnotation("JacksonXmlElementWrapper", Map.of("useWrapping", "false")) - .toFileAssert() - - // ↓ test custom element name (https://swagger.io/docs/specification/data-models/representing-xml/#:~:text=Change%20Element%20Names) - .assertProperty("status").assertPropertyAnnotations() - .doesNotContainWithName("XmlAttribute") - .doesNotContainWithName("XmlElementWrapper") - .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"PetStatus\"")) - .toProperty().toType() - .assertMethod("getStatus") - .doesNotHaveAnnotation("JacksonXmlElementWrapper") - .hasAnnotation("JacksonXmlProperty", Map.of("localName", "\"PetStatus\"")) - .toFileAssert() - - // ↓ test same-name wrapping element (https://swagger.io/docs/specification/data-models/representing-xml/#:~:text=Wrapping%20Arrays) - // maps to 3rd example in https://spec.openapis.org/oas/v3.0.0#xml-arrays - .assertProperty("photoUrls").assertPropertyAnnotations() - .doesNotContainWithName("XmlAttribute") - .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"photoUrls\"")) - .containsWithNameAndAttributes("XmlElementWrapper", Map.of("name", "\"photoUrls\"")) - .toProperty().toType() - .assertMethod("getPhotoUrls") - .hasAnnotation("JacksonXmlProperty", Map.of("localName", "\"photoUrls\"")) - .hasAnnotation("JacksonXmlElementWrapper", Map.of("localName", "\"photoUrls\"", "useWrapping", "true")) - .toFileAssert() - - // ↓ test attribute generation (https://swagger.io/docs/specification/data-models/representing-xml/#:~:text=Convert%20Property%20to%20an%20Attribute) - .assertProperty("name").assertPropertyAnnotations() - .doesNotContainWithName("XmlElement") - .doesNotContainWithName("XmlElementWrapper") - .containsWithNameAndAttributes("XmlAttribute", Map.of("name", "\"name\"")) - .toProperty().toType() - .assertMethod("getName") - .doesNotHaveAnnotation("JacksonXmlElementWrapper") - .hasAnnotation("JacksonXmlProperty", Map.of("isAttribute", "true", "localName", "\"name\"")) - .toFileAssert() - - // ↓ test XML namespace and prefix (https://swagger.io/docs/specification/data-models/representing-xml/#:~:text=Prefixes%20and%20Namespaces) - .assertProperty("id").assertPropertyAnnotations() - .doesNotContainWithName("XmlAttribute") - .doesNotContainWithName("XmlElementWrapper") - .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"id\"", "namespace", "\"http://example.com/schema\"")) - .toProperty().toType() - .assertMethod("getId") - .doesNotHaveAnnotation("JacksonXmlElementWrapper") - .hasAnnotation("JacksonXmlProperty", Map.of("localName", "\"id\"", "namespace", "\"http://example.com/schema\"")) - .toFileAssert() - - // ↓ external xml-array element name only (last example in https://spec.openapis.org/oas/v3.0.0#xml-arrays) - .assertProperty("foods").assertPropertyAnnotations() - .doesNotContainWithName("XmlAttribute") - .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"yummy-yummy\"")) - .containsWithNameAndAttributes("XmlElementWrapper", Map.of("name", "\"yummy-yummy\"")) - .toProperty().toType() - .assertMethod("getFoods") - .hasAnnotation("JacksonXmlProperty", Map.of("localName", "\"yummy-yummy\"")) - .hasAnnotation("JacksonXmlElementWrapper", Map.of("localName", "\"yummy-yummy\"")) - .toFileAssert() - - // ↓ internal xml-array element name (4th example in https://spec.openapis.org/oas/v3.0.0#xml-arrays) - .assertProperty("colors").assertPropertyAnnotations() - .doesNotContainWithName("XmlAttribute") - .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"color\"")) - .containsWithNameAndAttributes("XmlElementWrapper", Map.of("name", "\"colors\"")) - .toProperty().toType() - .assertMethod("getColors") - .hasAnnotation("JacksonXmlProperty", Map.of("localName", "\"color\"")) - .hasAnnotation("JacksonXmlElementWrapper", Map.of("localName", "\"colors\"")) - .toFileAssert() - - // ↓ ignored external xml-array element name, non-wrapped (2nd example in https://spec.openapis.org/oas/v3.0.0#xml-arrays) - .assertProperty("categories").assertPropertyAnnotations() - .doesNotContainWithName("XmlAttribute") - .doesNotContainWithName("XmlElementWrapper") - .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"Category\"")) - .toProperty().toType() - .assertMethod("getCategories") - .hasAnnotation("JacksonXmlProperty", Map.of("localName", "\"Category\"")) - // ↓ specific regression test for #2417: (useWrapping=false) needs to be present - .hasAnnotation("JacksonXmlElementWrapper", Map.of("useWrapping", "false")) - .toFileAssert() - - // ↓ test custom-name on wrapper AND children (https://swagger.io/docs/specification/data-models/representing-xml/#:~:text=Use%20xml/name%20to%20give%20different%20names) - // maps to 5th example in https://spec.openapis.org/oas/v3.0.0#xml-arrays - .assertProperty("activities").assertPropertyAnnotations() - .doesNotContainWithName("XmlAttribute") - .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"item\"")) - .containsWithNameAndAttributes("XmlElementWrapper", Map.of("name", "\"activities-array\"")) - .toProperty().toType() - .assertMethod("getActivities") - .hasAnnotation("JacksonXmlProperty", Map.of("localName", "\"item\"")) - .hasAnnotation("JacksonXmlElementWrapper", Map.of("localName", "\"activities-array\"")); + .assertTypeAnnotations() + .containsWithNameAndAttributes("XmlAccessorType", Map.of("value", "XmlAccessType.FIELD")) + .containsWithNameAndAttributes("XmlRootElement", Map.of("name", "\"Pet\"", "namespace", "\"urn:jacksonxml\"")) + .containsWithNameAndAttributes("JacksonXmlRootElement", Map.of("localName", "\"Pet\"", "namespace", "\"urn:jacksonxml\"")) + .toType() + + // ↓ test custom-name on wrapper element (https://swagger.io/docs/specification/data-models/representing-xml/#:~:text=Use%20xml/name%20to%20give%20different%20names) + .assertProperty("tags").assertPropertyAnnotations() + .doesNotContainWithName("XmlAttribute") + .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"Tag\"")) + .containsWithNameAndAttributes("XmlElementWrapper", Map.of("name", "\"TagList\"")) + .toProperty().toType() + .assertMethod("getTags") + .hasAnnotation("JacksonXmlProperty", Map.of("localName", "\"Tag\"")) + .hasAnnotation("JacksonXmlElementWrapper", Map.of("localName", "\"TagList\"", "useWrapping", "true")) + .toFileAssert() + + // ↓ custom internal xml-array element name, non-wrapped (1st example in https://spec.openapis.org/oas/v3.0.0#xml-arrays) + .assertProperty("friends").assertPropertyAnnotations() + .doesNotContainWithName("XmlAttribute") + .doesNotContainWithName("XmlElementWrapper") + .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"friend-pet\"")) + .toProperty().toType() + .assertMethod("getFriends") + .hasAnnotation("JacksonXmlProperty", Map.of("localName", "\"friend-pet\"")) + .hasAnnotation("JacksonXmlElementWrapper", Map.of("useWrapping", "false")) + .toFileAssert() + + // ↓ test custom element name (https://swagger.io/docs/specification/data-models/representing-xml/#:~:text=Change%20Element%20Names) + .assertProperty("status").assertPropertyAnnotations() + .doesNotContainWithName("XmlAttribute") + .doesNotContainWithName("XmlElementWrapper") + .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"PetStatus\"")) + .toProperty().toType() + .assertMethod("getStatus") + .doesNotHaveAnnotation("JacksonXmlElementWrapper") + .hasAnnotation("JacksonXmlProperty", Map.of("localName", "\"PetStatus\"")) + .toFileAssert() + + // ↓ test same-name wrapping element (https://swagger.io/docs/specification/data-models/representing-xml/#:~:text=Wrapping%20Arrays) + // maps to 3rd example in https://spec.openapis.org/oas/v3.0.0#xml-arrays + .assertProperty("photoUrls").assertPropertyAnnotations() + .doesNotContainWithName("XmlAttribute") + .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"photoUrls\"")) + .containsWithNameAndAttributes("XmlElementWrapper", Map.of("name", "\"photoUrls\"")) + .toProperty().toType() + .assertMethod("getPhotoUrls") + .hasAnnotation("JacksonXmlProperty", Map.of("localName", "\"photoUrls\"")) + .hasAnnotation("JacksonXmlElementWrapper", Map.of("localName", "\"photoUrls\"", "useWrapping", "true")) + .toFileAssert() + + // ↓ test attribute generation (https://swagger.io/docs/specification/data-models/representing-xml/#:~:text=Convert%20Property%20to%20an%20Attribute) + .assertProperty("name").assertPropertyAnnotations() + .doesNotContainWithName("XmlElement") + .doesNotContainWithName("XmlElementWrapper") + .containsWithNameAndAttributes("XmlAttribute", Map.of("name", "\"name\"")) + .toProperty().toType() + .assertMethod("getName") + .doesNotHaveAnnotation("JacksonXmlElementWrapper") + .hasAnnotation("JacksonXmlProperty", Map.of("isAttribute", "true", "localName", "\"name\"")) + .toFileAssert() + + // ↓ test XML namespace and prefix (https://swagger.io/docs/specification/data-models/representing-xml/#:~:text=Prefixes%20and%20Namespaces) + .assertProperty("id").assertPropertyAnnotations() + .doesNotContainWithName("XmlAttribute") + .doesNotContainWithName("XmlElementWrapper") + .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"id\"", "namespace", "\"http://example.com/schema\"")) + .toProperty().toType() + .assertMethod("getId") + .doesNotHaveAnnotation("JacksonXmlElementWrapper") + .hasAnnotation("JacksonXmlProperty", Map.of("localName", "\"id\"", "namespace", "\"http://example.com/schema\"")) + .toFileAssert() + + // ↓ external xml-array element name only (last example in https://spec.openapis.org/oas/v3.0.0#xml-arrays) + .assertProperty("foods").assertPropertyAnnotations() + .doesNotContainWithName("XmlAttribute") + .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"yummy-yummy\"")) + .containsWithNameAndAttributes("XmlElementWrapper", Map.of("name", "\"yummy-yummy\"")) + .toProperty().toType() + .assertMethod("getFoods") + .hasAnnotation("JacksonXmlProperty", Map.of("localName", "\"yummy-yummy\"")) + .hasAnnotation("JacksonXmlElementWrapper", Map.of("localName", "\"yummy-yummy\"")) + .toFileAssert() + + // ↓ internal xml-array element name (4th example in https://spec.openapis.org/oas/v3.0.0#xml-arrays) + .assertProperty("colors").assertPropertyAnnotations() + .doesNotContainWithName("XmlAttribute") + .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"color\"")) + .containsWithNameAndAttributes("XmlElementWrapper", Map.of("name", "\"colors\"")) + .toProperty().toType() + .assertMethod("getColors") + .hasAnnotation("JacksonXmlProperty", Map.of("localName", "\"color\"")) + .hasAnnotation("JacksonXmlElementWrapper", Map.of("localName", "\"colors\"")) + .toFileAssert() + + // ↓ ignored external xml-array element name, non-wrapped (2nd example in https://spec.openapis.org/oas/v3.0.0#xml-arrays) + .assertProperty("categories").assertPropertyAnnotations() + .doesNotContainWithName("XmlAttribute") + .doesNotContainWithName("XmlElementWrapper") + .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"Category\"")) + .toProperty().toType() + .assertMethod("getCategories") + .hasAnnotation("JacksonXmlProperty", Map.of("localName", "\"Category\"")) + // ↓ specific regression test for #2417: (useWrapping=false) needs to be present + .hasAnnotation("JacksonXmlElementWrapper", Map.of("useWrapping", "false")) + .toFileAssert() + + // ↓ test custom-name on wrapper AND children (https://swagger.io/docs/specification/data-models/representing-xml/#:~:text=Use%20xml/name%20to%20give%20different%20names) + // maps to 5th example in https://spec.openapis.org/oas/v3.0.0#xml-arrays + .assertProperty("activities").assertPropertyAnnotations() + .doesNotContainWithName("XmlAttribute") + .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"item\"")) + .containsWithNameAndAttributes("XmlElementWrapper", Map.of("name", "\"activities-array\"")) + .toProperty().toType() + .assertMethod("getActivities") + .hasAnnotation("JacksonXmlProperty", Map.of("localName", "\"item\"")) + .hasAnnotation("JacksonXmlElementWrapper", Map.of("localName", "\"activities-array\"")); } /** * General XML annotations test (only JAXB) */ - @Test(dataProvider = "librariesNotSupportingJackson") + @Test(dataProvider = "librariesNotSupportingJackson") void shouldGenerateCorrectJaxbAnnotations(Library library) { // Arrange final CodegenConfigurator config = new CodegenConfigurator() - .addAdditionalProperty(CodegenConstants.WITH_XML, true) - .addGlobalProperty(CodegenConstants.MODELS, "Pet") - .addGlobalProperty(CodegenConstants.MODEL_DOCS, null) - .addGlobalProperty(CodegenConstants.MODEL_TESTS, null) - .setGeneratorName("java") - .setLibrary(library.value) - .setInputSpec("src/test/resources/3_0/java/xml-annotations-test.yaml") - .setOutputDir(newTempFolder().toString()); + .addAdditionalProperty(CodegenConstants.WITH_XML, true) + .addGlobalProperty(CodegenConstants.MODELS, "Pet") + .addGlobalProperty(CodegenConstants.MODEL_DOCS, null) + .addGlobalProperty(CodegenConstants.MODEL_TESTS, null) + .setGeneratorName("java") + .setLibrary(library.value) + .setInputSpec("src/test/resources/3_0/java/xml-annotations-test.yaml") + .setOutputDir(newTempFolder().toString()); // Act final List files = new DefaultGenerator().opts(config.toClientOptInput()).generate(); // Assert JavaFileAssert.assertThat(files.get(0)) - .assertTypeAnnotations() - .containsWithNameAndAttributes("XmlRootElement", Map.of("name", "\"Pet\"", "namespace", "\"urn:jacksonxml\"")) - .containsWithNameAndAttributes("XmlAccessorType", Map.of("value", "XmlAccessType.FIELD")) - .toType() - - // ↓ test custom-name on wrapper element (https://swagger.io/docs/specification/data-models/representing-xml/#:~:text=Use%20xml/name%20to%20give%20different%20names) - .assertProperty("tags").assertPropertyAnnotations() - .doesNotContainWithName("XmlAttribute") - .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"Tag\"")) - .containsWithNameAndAttributes("XmlElementWrapper", Map.of("name", "\"TagList\"")) - .toProperty().toType() - - // ↓ custom internal xml-array element name, non-wrapped (1st example in https://spec.openapis.org/oas/v3.0.0#xml-arrays) - .assertProperty("friends").assertPropertyAnnotations() - .doesNotContainWithName("XmlAttribute") - .doesNotContainWithName("XmlElementWrapper") - .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"friend-pet\"")) - .toProperty().toType() - - // ↓ test custom element name (https://swagger.io/docs/specification/data-models/representing-xml/#:~:text=Change%20Element%20Names) - .assertProperty("status").assertPropertyAnnotations() - .doesNotContainWithName("XmlAttribute") - .doesNotContainWithName("XmlElementWrapper") - .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"PetStatus\"")) - .toProperty().toType() - - // ↓ test same-name wrapping element (https://swagger.io/docs/specification/data-models/representing-xml/#:~:text=Wrapping%20Arrays) - // maps to 3rd example in https://spec.openapis.org/oas/v3.0.0#xml-arrays - .assertProperty("photoUrls").assertPropertyAnnotations() - .doesNotContainWithName("XmlAttribute") - .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"photoUrls\"")) - .containsWithNameAndAttributes("XmlElementWrapper", Map.of("name", "\"photoUrls\"")) - .toProperty().toType() - - // ↓ test attribute generation (https://swagger.io/docs/specification/data-models/representing-xml/#:~:text=Convert%20Property%20to%20an%20Attribute) - .assertProperty("name").assertPropertyAnnotations() - .doesNotContainWithName("XmlElement") - .doesNotContainWithName("XmlElementWrapper") - .containsWithNameAndAttributes("XmlAttribute", Map.of("name", "\"name\"")) - .toProperty().toType() - - // ↓ test XML namespace and prefix (https://swagger.io/docs/specification/data-models/representing-xml/#:~:text=Prefixes%20and%20Namespaces) - .assertProperty("id").assertPropertyAnnotations() - .doesNotContainWithName("XmlAttribute") - .doesNotContainWithName("XmlElementWrapper") - .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"id\"", "namespace", "\"http://example.com/schema\"")) - .toProperty().toType() - - // ↓ external xml-array element name only (last example in https://spec.openapis.org/oas/v3.0.0#xml-arrays) - .assertProperty("foods").assertPropertyAnnotations() - .doesNotContainWithName("XmlAttribute") - .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"yummy-yummy\"")) - .containsWithNameAndAttributes("XmlElementWrapper", Map.of("name", "\"yummy-yummy\"")) - .toProperty().toType() - - // ↓ internal xml-array element name (4th example in https://spec.openapis.org/oas/v3.0.0#xml-arrays) - .assertProperty("colors").assertPropertyAnnotations() - .doesNotContainWithName("XmlAttribute") - .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"color\"")) - .containsWithNameAndAttributes("XmlElementWrapper", Map.of("name", "\"colors\"")) - .toProperty().toType() - - // ↓ ignored external xml-array element name, non-wrapped (2nd example in https://spec.openapis.org/oas/v3.0.0#xml-arrays) - .assertProperty("categories").assertPropertyAnnotations() - .doesNotContainWithName("XmlAttribute") - .doesNotContainWithName("XmlElementWrapper") - .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"Category\"")) - .toProperty().toType() - - // ↓ test custom-name on wrapper AND children (https://swagger.io/docs/specification/data-models/representing-xml/#:~:text=Use%20xml/name%20to%20give%20different%20names) - // maps to 5th example in https://spec.openapis.org/oas/v3.0.0#xml-arrays - .assertProperty("activities").assertPropertyAnnotations() - .doesNotContainWithName("XmlAttribute") - .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"item\"")) - .containsWithNameAndAttributes("XmlElementWrapper", Map.of("name", "\"activities-array\"")); + .assertTypeAnnotations() + .containsWithNameAndAttributes("XmlRootElement", Map.of("name", "\"Pet\"", "namespace", "\"urn:jacksonxml\"")) + .containsWithNameAndAttributes("XmlAccessorType", Map.of("value", "XmlAccessType.FIELD")) + .toType() + + // ↓ test custom-name on wrapper element (https://swagger.io/docs/specification/data-models/representing-xml/#:~:text=Use%20xml/name%20to%20give%20different%20names) + .assertProperty("tags").assertPropertyAnnotations() + .doesNotContainWithName("XmlAttribute") + .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"Tag\"")) + .containsWithNameAndAttributes("XmlElementWrapper", Map.of("name", "\"TagList\"")) + .toProperty().toType() + + // ↓ custom internal xml-array element name, non-wrapped (1st example in https://spec.openapis.org/oas/v3.0.0#xml-arrays) + .assertProperty("friends").assertPropertyAnnotations() + .doesNotContainWithName("XmlAttribute") + .doesNotContainWithName("XmlElementWrapper") + .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"friend-pet\"")) + .toProperty().toType() + + // ↓ test custom element name (https://swagger.io/docs/specification/data-models/representing-xml/#:~:text=Change%20Element%20Names) + .assertProperty("status").assertPropertyAnnotations() + .doesNotContainWithName("XmlAttribute") + .doesNotContainWithName("XmlElementWrapper") + .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"PetStatus\"")) + .toProperty().toType() + + // ↓ test same-name wrapping element (https://swagger.io/docs/specification/data-models/representing-xml/#:~:text=Wrapping%20Arrays) + // maps to 3rd example in https://spec.openapis.org/oas/v3.0.0#xml-arrays + .assertProperty("photoUrls").assertPropertyAnnotations() + .doesNotContainWithName("XmlAttribute") + .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"photoUrls\"")) + .containsWithNameAndAttributes("XmlElementWrapper", Map.of("name", "\"photoUrls\"")) + .toProperty().toType() + + // ↓ test attribute generation (https://swagger.io/docs/specification/data-models/representing-xml/#:~:text=Convert%20Property%20to%20an%20Attribute) + .assertProperty("name").assertPropertyAnnotations() + .doesNotContainWithName("XmlElement") + .doesNotContainWithName("XmlElementWrapper") + .containsWithNameAndAttributes("XmlAttribute", Map.of("name", "\"name\"")) + .toProperty().toType() + + // ↓ test XML namespace and prefix (https://swagger.io/docs/specification/data-models/representing-xml/#:~:text=Prefixes%20and%20Namespaces) + .assertProperty("id").assertPropertyAnnotations() + .doesNotContainWithName("XmlAttribute") + .doesNotContainWithName("XmlElementWrapper") + .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"id\"", "namespace", "\"http://example.com/schema\"")) + .toProperty().toType() + + // ↓ external xml-array element name only (last example in https://spec.openapis.org/oas/v3.0.0#xml-arrays) + .assertProperty("foods").assertPropertyAnnotations() + .doesNotContainWithName("XmlAttribute") + .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"yummy-yummy\"")) + .containsWithNameAndAttributes("XmlElementWrapper", Map.of("name", "\"yummy-yummy\"")) + .toProperty().toType() + + // ↓ internal xml-array element name (4th example in https://spec.openapis.org/oas/v3.0.0#xml-arrays) + .assertProperty("colors").assertPropertyAnnotations() + .doesNotContainWithName("XmlAttribute") + .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"color\"")) + .containsWithNameAndAttributes("XmlElementWrapper", Map.of("name", "\"colors\"")) + .toProperty().toType() + + // ↓ ignored external xml-array element name, non-wrapped (2nd example in https://spec.openapis.org/oas/v3.0.0#xml-arrays) + .assertProperty("categories").assertPropertyAnnotations() + .doesNotContainWithName("XmlAttribute") + .doesNotContainWithName("XmlElementWrapper") + .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"Category\"")) + .toProperty().toType() + + // ↓ test custom-name on wrapper AND children (https://swagger.io/docs/specification/data-models/representing-xml/#:~:text=Use%20xml/name%20to%20give%20different%20names) + // maps to 5th example in https://spec.openapis.org/oas/v3.0.0#xml-arrays + .assertProperty("activities").assertPropertyAnnotations() + .doesNotContainWithName("XmlAttribute") + .containsWithNameAndAttributes("XmlElement", Map.of("name", "\"item\"")) + .containsWithNameAndAttributes("XmlElementWrapper", Map.of("name", "\"activities-array\"")); } @@ -2966,56 +3055,57 @@ void shouldGenerateCorrectJaxbAnnotations(Library library) { public void testRestTemplateWithGeneratedOAuthTokenSuppliers() { final Map files = generateFromContract( - "src/test/resources/3_0/java/oauth.yaml", - JavaClientCodegen.RESTTEMPLATE + "src/test/resources/3_0/java/oauth.yaml", + JavaClientCodegen.RESTTEMPLATE ); final JavaFileAssert apiClient = JavaFileAssert.assertThat(files.get("ApiClient.java")) - .printFileContent(); + .printFileContent(); apiClient - .assertMethod("setAccessToken", "String") - .bodyContainsLines("setAccessToken(() -> accessToken);"); + .assertMethod("setAccessToken", "String") + .bodyContainsLines("setAccessToken(() -> accessToken);"); apiClient - .assertMethod("setAccessToken", "Supplier") - .bodyContainsLines("((OAuth) auth).setAccessToken(tokenSupplier);"); + .assertMethod("setAccessToken", "Supplier") + .bodyContainsLines("((OAuth) auth).setAccessToken(tokenSupplier);"); final JavaFileAssert oAuth = JavaFileAssert.assertThat(files.get("OAuth.java")) - .printFileContent(); + .printFileContent(); oAuth - .assertMethod("setAccessToken", "String") - .bodyContainsLines("setAccessToken(() -> accessToken);"); + .assertMethod("setAccessToken", "String") + .bodyContainsLines("setAccessToken(() -> accessToken);"); oAuth - .assertMethod("setAccessToken", "Supplier") - .bodyContainsLines("this.tokenSupplier = tokenSupplier;"); + .assertMethod("setAccessToken", "Supplier") + .bodyContainsLines("this.tokenSupplier = tokenSupplier;"); oAuth - .assertMethod("applyToParams") - .bodyContainsLines("Optional.ofNullable(tokenSupplier).map(Supplier::get).ifPresent(accessToken ->") - .bodyContainsLines("headerParams.add(HttpHeaders.AUTHORIZATION, \"Bearer \" + accessToken)"); + .assertMethod("applyToParams") + .bodyContainsLines("Optional.ofNullable(tokenSupplier).map(Supplier::get).ifPresent(accessToken ->") + .bodyContainsLines("headerParams.add(HttpHeaders.AUTHORIZATION, \"Bearer \" + accessToken)"); } @Test public void testRestClientWithGeneratedOAuthTokenSuppliers() { final Map files = generateFromContract( - "src/test/resources/3_0/java/oauth.yaml", - JavaClientCodegen.RESTCLIENT + "src/test/resources/3_0/java/oauth.yaml", + JavaClientCodegen.RESTCLIENT ); final JavaFileAssert oAuth = JavaFileAssert.assertThat(files.get("OAuth.java")) - .printFileContent(); + .printFileContent(); oAuth - .assertMethod("setAccessToken", "String") - .bodyContainsLines("setAccessToken(() -> accessToken);"); + .assertMethod("setAccessToken", "String") + .bodyContainsLines("setAccessToken(() -> accessToken);"); oAuth - .assertMethod("setAccessToken", "Supplier") - .bodyContainsLines("this.tokenSupplier = tokenSupplier;"); + .assertMethod("setAccessToken", "Supplier") + .bodyContainsLines("this.tokenSupplier = tokenSupplier;"); oAuth - .assertMethod("applyToParams") - .bodyContainsLines("Optional.ofNullable(tokenSupplier).map(Supplier::get).ifPresent(accessToken ->") - .bodyContainsLines("headerParams.add(HttpHeaders.AUTHORIZATION, \"Bearer \" + accessToken)"); + .assertMethod("applyToParams") + .bodyContainsLines("Optional.ofNullable(tokenSupplier).map(Supplier::get).ifPresent(accessToken ->") + .bodyContainsLines("headerParams.add(HttpHeaders.AUTHORIZATION, \"Bearer \" + accessToken)"); } - - @Test public void testRestClientWithXML_issue_19137() { + + @Test + public void testRestClientWithXML_issue_19137() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") @@ -3037,7 +3127,8 @@ public void testRestClientWithGeneratedOAuthTokenSuppliers() { ); } - @Test public void testRestClientWithUseSingleRequestParameter_issue_19406() { + @Test + public void testRestClientWithUseSingleRequestParameter_issue_19406() { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") @@ -3063,4 +3154,41 @@ public void testRestClientWithGeneratedOAuthTokenSuppliers() { ); } + @Test + public void testDuplicatedOperationId() { + final Path output = newTempFolder(); + final CodegenConfigurator configurator = new CodegenConfigurator() + .setValidateSpec(false) + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.RESTCLIENT) + .setAdditionalProperties(Map.of( + CodegenConstants.API_PACKAGE, "xyz.abcdef.api", + CodegenConstants.USE_SINGLE_REQUEST_PARAMETER, true + )) + .setInputSpec("src/test/resources/3_0/duplicated_operationid.yaml") + .setOutputDir(output.toString().replace("\\", "/")); + + new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); + + TestUtils.assertFileContains( + output.resolve("src/main/java/xyz/abcdef/api/PetApi.java"), + " void getObject(" + ); + + TestUtils.assertFileContains( + output.resolve("src/main/java/xyz/abcdef/api/UserApi.java"), + " void getObject(" + ); + + TestUtils.assertFileNotContains( + output.resolve("src/main/java/xyz/abcdef/api/UserApi.java"), + " void getObject_0(" + ); + + TestUtils.assertFileNotContains( + output.resolve("src/main/java/xyz/abcdef/api/UserApi.java"), + " void getObject0(" + ); + } + } diff --git a/modules/openapi-generator/src/test/resources/3_0/duplicated_operationid.yaml b/modules/openapi-generator/src/test/resources/3_0/duplicated_operationid.yaml new file mode 100644 index 000000000000..9cc43534779c --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/duplicated_operationid.yaml @@ -0,0 +1,58 @@ +openapi: 3.0.0 +servers: + - url: 'http://petstore.swagger.io/v2' +info: + description: A sample spec to test duplicated operationId + version: 1.0.0 + title: OpenAPI Petstore + license: + name: Apache-2.0 + url: 'https://www.apache.org/licenses/LICENSE-2.0.html' +paths: + '/pet/{petId}': + get: + tags: + - pet + summary: Find pet by ID + description: Returns a single pet + operationId: getObject + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + '400': + description: Invalid ID supplied + '404': + description: Pet not found + '/user/{username}': + get: + tags: + - user + summary: Get user by user name + description: '' + operationId: getObject + parameters: + - name: username + in: path + description: The name that needs to be fetched. Use user1 for testing. + required: true + schema: + type: string + responses: + '200': + description: successful operation + '400': + description: Invalid username supplied + '404': + description: User not found +externalDocs: + description: Find out more about Swagger + url: 'http://swagger.io' +