diff --git a/gradle-plugin/buildSrc/src/main/java/com/yelp/codegen/gradle/PublishingVersions.kt b/gradle-plugin/buildSrc/src/main/java/com/yelp/codegen/gradle/PublishingVersions.kt index ca73398d..c6ffe0b3 100644 --- a/gradle-plugin/buildSrc/src/main/java/com/yelp/codegen/gradle/PublishingVersions.kt +++ b/gradle-plugin/buildSrc/src/main/java/com/yelp/codegen/gradle/PublishingVersions.kt @@ -1,6 +1,6 @@ object PublishingVersions { - const val PLUGIN_VERSION = "1.4.1" - const val PLUGIN_GROUP = "com.yelp.codegen" - @Suppress("UNUSED") - const val PLUGIN_ARTIFACT = "plugin" + const val PLUGIN_VERSION = "1.4.1" + const val PLUGIN_GROUP = "com.yelp.codegen" + @Suppress("UNUSED") + const val PLUGIN_ARTIFACT = "plugin" } diff --git a/gradle-plugin/plugin/src/main/java/com/yelp/codegen/KotlinCoroutineGenerator.kt b/gradle-plugin/plugin/src/main/java/com/yelp/codegen/KotlinCoroutineGenerator.kt index 4b59a273..1d97829a 100644 --- a/gradle-plugin/plugin/src/main/java/com/yelp/codegen/KotlinCoroutineGenerator.kt +++ b/gradle-plugin/plugin/src/main/java/com/yelp/codegen/KotlinCoroutineGenerator.kt @@ -7,29 +7,29 @@ import io.swagger.models.Swagger open class KotlinCoroutineGenerator : KotlinGenerator() { - init { - templateDir = "kotlin" - } + init { + templateDir = "kotlin" + } - override fun getName() = "kotlin-coroutines" + override fun getName() = "kotlin-coroutines" - override fun wrapResponseType(imports: MutableSet, responsePrimitiveType: String) = responsePrimitiveType + override fun wrapResponseType(imports: MutableSet, responsePrimitiveType: String) = responsePrimitiveType - override fun getNoResponseType(imports: MutableSet) = "Unit" + override fun getNoResponseType(imports: MutableSet) = "Unit" - /** - * Overriding the behavior of [KotlinGenerator] to make sure operations are rendered as `suspend fun` rather - * than just plain `fun`. - */ - override fun fromOperation( - path: String?, - httpMethod: String?, - operation: Operation?, - definitions: MutableMap?, - swagger: Swagger? - ): CodegenOperation { - val codegenOperation = super.fromOperation(path, httpMethod, operation, definitions, swagger) - codegenOperation.vendorExtensions[X_FUNCTION_QUALIFIERS] = "suspend" - return codegenOperation - } + /** + * Overriding the behavior of [KotlinGenerator] to make sure operations are rendered as `suspend fun` rather + * than just plain `fun`. + */ + override fun fromOperation( + path: String?, + httpMethod: String?, + operation: Operation?, + definitions: MutableMap?, + swagger: Swagger? + ): CodegenOperation { + val codegenOperation = super.fromOperation(path, httpMethod, operation, definitions, swagger) + codegenOperation.vendorExtensions[X_FUNCTION_QUALIFIERS] = "suspend" + return codegenOperation + } } diff --git a/gradle-plugin/plugin/src/main/java/com/yelp/codegen/KotlinGenerator.kt b/gradle-plugin/plugin/src/main/java/com/yelp/codegen/KotlinGenerator.kt index 0e3e7901..6605679e 100644 --- a/gradle-plugin/plugin/src/main/java/com/yelp/codegen/KotlinGenerator.kt +++ b/gradle-plugin/plugin/src/main/java/com/yelp/codegen/KotlinGenerator.kt @@ -22,518 +22,519 @@ import java.io.File @Suppress("TooManyFunctions") open class KotlinGenerator : SharedCodegen() { - companion object { - /** - * This number represents the version of the kotlin template - * Please note that is independent from the Plugin version - */ - @JvmStatic val VERSION = 12 - - // Vendor Extension use to generate the list of top level headers - const val HAS_OPERATION_HEADERS = "hasOperationHeaders" - const val OPERATION_HEADERS = "operationHeaders" - } - - private val apiDocPath = "docs/" - private val modelDocPath = "docs/" - internal var basePath: String? = null - - private val retrofitImport = mapOf( - "GET" to "retrofit2.http.GET", - "DELETE" to "retrofit2.http.DELETE", - "PATCH" to "retrofit2.http.PATCH", - "POST" to "retrofit2.http.POST", - "PUT" to "retrofit2.http.PUT" - ) - + companion object { /** - * Constructs an instance of `KotlinAndroidGenerator`. + * This number represents the version of the kotlin template + * Please note that is independent from the Plugin version */ - init { - languageSpecificPrimitives = KotlinLangUtils.kotlinLanguageSpecificPrimitives - reservedWords = KotlinLangUtils.kotlinReservedWords - defaultIncludes = KotlinLangUtils.kotlinDefaultIncludes - typeMapping = KotlinLangUtils.kotlinTypeMapping - instantiationTypes = KotlinLangUtils.kotlinInstantiationTypes - importMapping = KotlinLangUtils.kotlinImportMapping - - templateDir = "kotlin" - outputFolder = "generated-code${File.separator}android-kotlin-client" - modelTemplateFiles["model.mustache"] = ".kt" - apiTemplateFiles["retrofit2/api.mustache"] = ".kt" - } + @JvmStatic val VERSION = 12 + + // Vendor Extension use to generate the list of top level headers + const val HAS_OPERATION_HEADERS = "hasOperationHeaders" + const val OPERATION_HEADERS = "operationHeaders" + } + + private val apiDocPath = "docs/" + private val modelDocPath = "docs/" + internal var basePath: String? = null + + private val retrofitImport = mapOf( + "GET" to "retrofit2.http.GET", + "DELETE" to "retrofit2.http.DELETE", + "PATCH" to "retrofit2.http.PATCH", + "POST" to "retrofit2.http.POST", + "PUT" to "retrofit2.http.PUT" + ) + + /** + * Constructs an instance of `KotlinAndroidGenerator`. + */ + init { + languageSpecificPrimitives = KotlinLangUtils.kotlinLanguageSpecificPrimitives + reservedWords = KotlinLangUtils.kotlinReservedWords + defaultIncludes = KotlinLangUtils.kotlinDefaultIncludes + typeMapping = KotlinLangUtils.kotlinTypeMapping + instantiationTypes = KotlinLangUtils.kotlinInstantiationTypes + importMapping = KotlinLangUtils.kotlinImportMapping + + templateDir = "kotlin" + outputFolder = "generated-code${File.separator}android-kotlin-client" + modelTemplateFiles["model.mustache"] = ".kt" + apiTemplateFiles["retrofit2/api.mustache"] = ".kt" + } /* * ABSTRACT FIELDS AND CONFIG FUNCTIONS ==================================================== */ - @VisibleForTesting - public override val platform = "android" + @VisibleForTesting + public override val platform = "android" - override fun getName() = "kotlin" + override fun getName() = "kotlin" - override fun getHelp() = "Generates code for a Kotlin Android client." + override fun getHelp() = "Generates code for a Kotlin Android client." - override fun modelPackage() = "$packageName.models" + override fun modelPackage() = "$packageName.models" - override fun apiPackage() = "$packageName.apis" + override fun apiPackage() = "$packageName.apis" - private val groupId: String - get() = additionalProperties[GROUP_ID] as String? ?: "" + private val groupId: String + get() = additionalProperties[GROUP_ID] as String? ?: "" - private val artifactId: String - get() = additionalProperties[ARTIFACT_ID] as String? ?: "" + private val artifactId: String + get() = additionalProperties[ARTIFACT_ID] as String? ?: "" - private val packageName: String - get() = "$groupId.$artifactId" + private val packageName: String + get() = "$groupId.$artifactId" - private val toolsPackage: String - get() = "$packageName.tools" + private val toolsPackage: String + get() = "$packageName.tools" /* * FOLDERS SETUP ==================================================== */ - override fun apiDocFileFolder() = "$outputFolder${File.separator}$apiDocPath" + override fun apiDocFileFolder() = "$outputFolder${File.separator}$apiDocPath" - override fun apiFileFolder() = - "$outputFolder${File.separator}" + apiPackage() - .replace('.', File.separatorChar) + override fun apiFileFolder() = + "$outputFolder${File.separator}" + apiPackage() + .replace('.', File.separatorChar) /* * SHARED CODEGEN SETUP ==================================================== */ - override val mustacheTags - get() = hashMapOf( - CodegenConstants.GROUP_ID to groupId, - CodegenConstants.ARTIFACT_ID to artifactId, - CodegenConstants.PACKAGE_NAME to packageName, - CodegenConstants.API_PACKAGE to apiPackage(), - CodegenConstants.MODEL_PACKAGE to modelPackage(), - "apiDocPath" to apiDocPath, - "modelDocPath" to modelDocPath, - "service" to serviceName, - "newline" to "\n" - ) - - override val supportFiles: Collection - get() { - val toolsFolder = toolsPackage.replace(".", File.separator).plus(File.separator) - val toolsFiles = listOf( - "CollectionFormatConverterFactory.kt", - "CollectionFormats.kt", - "EnumToValueConverterFactory.kt", - "GeneratedCodeConverters.kt", - "TypesAdapters.kt", - "WrapperConverterFactory.kt", - "XNullable.kt", - "XNullableAdapterFactory.kt" - ) - supportingFiles.addAll(toolsFiles.map { SupportingFile("tools/$it.mustache", toolsFolder, it) }) - return supportingFiles - } + override val mustacheTags + get() = hashMapOf( + CodegenConstants.GROUP_ID to groupId, + CodegenConstants.ARTIFACT_ID to artifactId, + CodegenConstants.PACKAGE_NAME to packageName, + CodegenConstants.API_PACKAGE to apiPackage(), + CodegenConstants.MODEL_PACKAGE to modelPackage(), + "apiDocPath" to apiDocPath, + "modelDocPath" to modelDocPath, + "service" to serviceName, + "newline" to "\n" + ) - /** No testing files are needed on Kotlin Generator */ - override val testingSupportFiles = listOf() + override val supportFiles: Collection + get() { + val toolsFolder = toolsPackage.replace(".", File.separator).plus(File.separator) + val toolsFiles = listOf( + "CollectionFormatConverterFactory.kt", + "CollectionFormats.kt", + "EnumToValueConverterFactory.kt", + "GeneratedCodeConverters.kt", + "TypesAdapters.kt", + "WrapperConverterFactory.kt", + "XNullable.kt", + "XNullableAdapterFactory.kt" + ) + supportingFiles.addAll(toolsFiles.map { SupportingFile("tools/$it.mustache", toolsFolder, it) }) + return supportingFiles + } - @VisibleForTesting - public override fun listTypeWrapper(listType: String, innerType: String) = - "$listType<$innerType>" + /** No testing files are needed on Kotlin Generator */ + override val testingSupportFiles = listOf() - public override fun listTypeUnwrapper(baseType: String) = baseType - .replace(" ", "") - .removeSuffix(">") - .removePrefix("${typeMapping["list"]}<") + @VisibleForTesting + public override fun listTypeWrapper(listType: String, innerType: String) = + "$listType<$innerType>" - public override fun isListTypeWrapped(baseType: String) = - baseType.endsWith('>') && baseType.startsWith("${typeMapping["list"]}<") + public override fun listTypeUnwrapper(baseType: String) = baseType + .replace(" ", "") + .removeSuffix(">") + .removePrefix("${typeMapping["list"]}<") - @VisibleForTesting - public override fun mapTypeWrapper(mapType: String, innerType: String) = - "$mapType<${typeMapping["string"]}, $innerType>" + public override fun isListTypeWrapped(baseType: String) = + baseType.endsWith('>') && baseType.startsWith("${typeMapping["list"]}<") - public override fun mapTypeUnwrapper(baseType: String) = baseType - .replace(" ", "") - .removeSuffix(">") - .removePrefix("${typeMapping["map"]}<${typeMapping["string"]},") + @VisibleForTesting + public override fun mapTypeWrapper(mapType: String, innerType: String) = + "$mapType<${typeMapping["string"]}, $innerType>" - public override fun isMapTypeWrapped(baseType: String) = - baseType.endsWith('>') && baseType.startsWith("${typeMapping["map"]}<${typeMapping["string"]},") + public override fun mapTypeUnwrapper(baseType: String) = baseType + .replace(" ", "") + .removeSuffix(">") + .removePrefix("${typeMapping["map"]}<${typeMapping["string"]},") - @VisibleForTesting - public override fun nullableTypeWrapper(baseType: String) = - baseType.safeSuffix("?") + public override fun isMapTypeWrapped(baseType: String) = + baseType.endsWith('>') && baseType.startsWith("${typeMapping["map"]}<${typeMapping["string"]},") + + @VisibleForTesting + public override fun nullableTypeWrapper(baseType: String) = + baseType.safeSuffix("?") /* * ESCAPING ==================================================== */ - override fun initalizeSpecialCharacterMapping() { - super.initalizeSpecialCharacterMapping() - // Kotlin specific. - specialCharReplacements[";"] = "Semicolon" - specialCharReplacements.remove("_") - } + override fun initalizeSpecialCharacterMapping() { + super.initalizeSpecialCharacterMapping() + // Kotlin specific. + specialCharReplacements[";"] = "Semicolon" + specialCharReplacements.remove("_") + } - @VisibleForTesting - public override fun isReservedWord(word: String?) = word in reservedWords + @VisibleForTesting + public override fun isReservedWord(word: String?) = word in reservedWords - // remove " to avoid code injection - override fun escapeQuotationMark(input: String) = input.replace("\"", "") + // remove " to avoid code injection + override fun escapeQuotationMark(input: String) = input.replace("\"", "") - override fun escapeReservedWord(name: String) = - if (name in reservedWords) { - "`$name`" - } else { - name - } + override fun escapeReservedWord(name: String) = + if (name in reservedWords) { + "`$name`" + } else { + name + } - override fun escapeUnsafeCharacters(input: String) = - input.replace("*/", "*_/").replace("/*", "/_*") + override fun escapeUnsafeCharacters(input: String) = + input.replace("*/", "*_/").replace("/*", "/_*") /* * CODEGEN FUNCTIONS ==================================================== */ - override fun fromModel(name: String, model: Model, allDefinitions: MutableMap?): CodegenModel { - val codegenModel = super.fromModel(name, model, allDefinitions) - addRequiredImports(codegenModel) - return codegenModel + override fun fromModel(name: String, model: Model, allDefinitions: MutableMap?): CodegenModel { + val codegenModel = super.fromModel(name, model, allDefinitions) + addRequiredImports(codegenModel) + return codegenModel + } + + @VisibleForTesting + internal fun addRequiredImports(codegenModel: CodegenModel) { + // If there are any vars, we will mark them with the @Json annotation so we have to make sure to import it + if (codegenModel.allVars.isNotEmpty() || codegenModel.isEnum) { + codegenModel.imports.add("kotlinx.serialization.Serializable") + codegenModel.imports.add("kotlinx.serialization.SerialName") } - @VisibleForTesting - internal fun addRequiredImports(codegenModel: CodegenModel) { - // If there are any vars, we will mark them with the @Json annotation so we have to make sure to import it - if (codegenModel.allVars.isNotEmpty() || codegenModel.isEnum) { - codegenModel.imports.add("com.squareup.moshi.Json") - } - - if (!codegenModel.isAlias) { - // If we are rendering a model (or enum) we are annotating it with @JsonClass, - // so we need to make sure that we're importing it - codegenModel.imports.add("com.squareup.moshi.JsonClass") - } - - // Add import for @XNullable annotation if there are any XNullable properties - for (property in codegenModel.allVars) { - if (X_NULLABLE in property.vendorExtensions) { - codegenModel.imports.add("$toolsPackage.XNullable") - break - } - } + if (!codegenModel.isAlias) { + // If we are rendering a model (or enum) we are annotating it with @JsonClass, + // so we need to make sure that we're importing it + codegenModel.imports.add("kotlinx.serialization.Serializable") } - override fun postProcessModelProperty(model: CodegenModel, property: CodegenProperty) { - super.postProcessModelProperty(model, property) - - if (property.isEnum) { - property.datatypeWithEnum = postProcessDataTypeWithEnum(model.classname, property) - } + // Add import for @XNullable annotation if there are any XNullable properties + for (property in codegenModel.allVars) { + if (X_NULLABLE in property.vendorExtensions) { + codegenModel.imports.add("$toolsPackage.XNullable") + break + } } + } - /** - * When handling inner enums, we want to prefix their class name, when using them, with their containing class, - * to avoid name conflicts. - */ - private fun postProcessDataTypeWithEnum(modelClassName: String, codegenProperty: CodegenProperty): String { - val name = "$modelClassName.${codegenProperty.enumName}" - - val baseType = if (codegenProperty.isContainer) { - val type = checkNotNull(typeMapping[codegenProperty.containerType]) - "$type<$name>" - } else { - name - } + override fun postProcessModelProperty(model: CodegenModel, property: CodegenProperty) { + super.postProcessModelProperty(model, property) - return if (codegenProperty.isNullable()) { - nullableTypeWrapper(baseType) - } else { - baseType - } + if (property.isEnum) { + property.datatypeWithEnum = postProcessDataTypeWithEnum(model.classname, property) } - - /** - * Returns the swagger type for the property - * - * @param property Swagger property object - * @return string presentation of the type - */ - override fun getSwaggerType(property: Property): String? { - val swaggerType = super.getSwaggerType(property) - val type: String - // This maps, for example, long -> kotlin.Long based on hashes in this type's constructor - if (swaggerType in typeMapping) { - type = checkNotNull(typeMapping[swaggerType]) - if (type in languageSpecificPrimitives) { - return toModelName(type) - } - } else { - type = swaggerType - } - return toModelName(type) + } + + /** + * When handling inner enums, we want to prefix their class name, when using them, with their containing class, + * to avoid name conflicts. + */ + private fun postProcessDataTypeWithEnum(modelClassName: String, codegenProperty: CodegenProperty): String { + val name = "$modelClassName.${codegenProperty.enumName}" + + val baseType = if (codegenProperty.isContainer) { + val type = checkNotNull(typeMapping[codegenProperty.containerType]) + "$type<$name>" + } else { + name } - /** - * Output the type declaration of the property. - * - * @param property Swagger Property object - * @return a string presentation of the property type - */ - override fun getTypeDeclaration(property: Property): String { - val resolvedType = resolvePropertyType(property) - - return if (property.isNullable()) { - nullableTypeWrapper(resolvedType) - } else { - resolvedType - } + return if (codegenProperty.isNullable()) { + nullableTypeWrapper(baseType) + } else { + baseType } - - override fun modelDocFileFolder(): String { - return "$outputFolder${File.separator}$modelDocPath" + } + + /** + * Returns the swagger type for the property + * + * @param property Swagger property object + * @return string presentation of the type + */ + override fun getSwaggerType(property: Property): String? { + val swaggerType = super.getSwaggerType(property) + val type: String + // This maps, for example, long -> kotlin.Long based on hashes in this type's constructor + if (swaggerType in typeMapping) { + type = checkNotNull(typeMapping[swaggerType]) + if (type in languageSpecificPrimitives) { + return toModelName(type) + } + } else { + type = swaggerType } - - override fun modelFileFolder(): String { - return outputFolder + File.separator + modelPackage().replace('.', File.separatorChar) + return toModelName(type) + } + + /** + * Output the type declaration of the property. + * + * @param property Swagger Property object + * @return a string presentation of the property type + */ + override fun getTypeDeclaration(property: Property): String { + val resolvedType = resolvePropertyType(property) + + return if (property.isNullable()) { + nullableTypeWrapper(resolvedType) + } else { + resolvedType } - - /** - * Return the sanitized variable name for enum - * - * @param value enum variable name - * @param datatype data type - * @return the sanitized variable name for enum - */ - override fun toEnumVarName(value: String, datatype: String): String { - (if (value.isEmpty()) "EMPTY" else value) - .sanitizeKotlinSpecificNames(specialCharReplacements) - .toUpperCase() - .let { - return escapeReservedWord(it) - } + } + + override fun modelDocFileFolder(): String { + return "$outputFolder${File.separator}$modelDocPath" + } + + override fun modelFileFolder(): String { + return outputFolder + File.separator + modelPackage().replace('.', File.separatorChar) + } + + /** + * Return the sanitized variable name for enum + * + * @param value enum variable name + * @param datatype data type + * @return the sanitized variable name for enum + */ + override fun toEnumVarName(value: String, datatype: String): String { + (if (value.isEmpty()) "EMPTY" else value) + .sanitizeKotlinSpecificNames(specialCharReplacements) + .toUpperCase() + .let { + return escapeReservedWord(it) + } + } + + override fun toVarName(name: String): String { + return escapeReservedWord(name.toCamelCase()) + } + + /** + * Return the fully-qualified "Model" name for import + * + * @param name the name of the "Model" + * @return the fully-qualified "Model" name for import + */ + override fun toModelImport(name: String): String { + // toModelImport is called while processing operations, but DefaultCodegen doesn't + // define imports correctly with fully qualified primitives and models as defined in this generator. + return when { + name.isFullyQualifiedImportName() -> name + needToImport(name) -> super.toModelImport(name) + else -> name } + } - override fun toVarName(name: String): String { - return escapeReservedWord(name.toCamelCase()) + @VisibleForTesting + public override fun addImport(model: CodegenModel, type: String?) { + if (type != null && needToImport(type) && type in importMapping) { + model.imports.add(type) } - - /** - * Return the fully-qualified "Model" name for import - * - * @param name the name of the "Model" - * @return the fully-qualified "Model" name for import - */ - override fun toModelImport(name: String): String { - // toModelImport is called while processing operations, but DefaultCodegen doesn't - // define imports correctly with fully qualified primitives and models as defined in this generator. - return when { - name.isFullyQualifiedImportName() -> name - needToImport(name) -> super.toModelImport(name) - else -> name - } + } + + /** + * Output the proper model name (capitalized). + * In case the name belongs to the TypeSystem it won't be renamed. + * + * @param name the name of the model + * @return capitalized model name + */ + override fun toModelName(name: String): String { + return if (name in importMapping) { + name + } else { + matchXModel(name) + .replace(Regex("(\\.|\\s)"), "_") + .toPascalCase() + .sanitizeKotlinSpecificNames(specialCharReplacements) + .apply { escapeReservedWord(this) } } - - @VisibleForTesting - public override fun addImport(model: CodegenModel, type: String?) { - if (type != null && needToImport(type) && type in importMapping) { - model.imports.add(type) + } + + /** + * Output the proper enum name (capitalized). We append a 'Enum' at the end of the name to avoid + * name clashes when enums are inner classes. + * + * Please note that this method is providing the same behavior as [DefaultCodegen.toEnumName] + * and might eventually be refactored. + * + * @param property the name of the model + * @return capitalized enum name (with appended 'Enum'). + */ + override fun toEnumName(property: CodegenProperty): String { + return toModelName(property.name) + "Enum" + } + + override fun toModelFilename(name: String): String = toModelName(name) + + /** + * Check if a name is of the type `com.x.name`, which means it has a fully qualified package. + */ + @Suppress("NOTHING_TO_INLINE") + private inline fun String.isFullyQualifiedImportName() = "." in this + + override fun postProcessModels(objs: Map): Map { + val processedModels = postProcessModelsEnum(super.postProcessModels(objs)) + + // Sort imports. Not strictly needed, neater. + @Suppress("UNCHECKED_CAST") + val imports = processedModels["imports"] as MutableList> + imports.sortBy { it["import"] } + + return processedModels + } + + override fun fromOperation( + path: String?, + httpMethod: String?, + operation: Operation?, + definitions: MutableMap?, + swagger: Swagger? + ): CodegenOperation { + val codegenOperation = super.fromOperation(path, httpMethod, operation, definitions, swagger) + + retrofitImport[codegenOperation.httpMethod]?.let { codegenOperation.imports.add(it) } + codegenOperation.allParams.forEach { codegenParameter: CodegenParameter -> + codegenParameter.collectionFormat?.let { + val importName = "$toolsPackage.${it.toUpperCase()}" + if (importName !in codegenOperation.imports) { + codegenOperation.imports.add(importName) } - } + } - /** - * Output the proper model name (capitalized). - * In case the name belongs to the TypeSystem it won't be renamed. - * - * @param name the name of the model - * @return capitalized model name - */ - override fun toModelName(name: String): String { - return if (name in importMapping) { - name - } else { - matchXModel(name) - .replace(Regex("(\\.|\\s)"), "_") - .toPascalCase() - .sanitizeKotlinSpecificNames(specialCharReplacements) - .apply { escapeReservedWord(this) } - } + if (codegenParameter.isFile) { + codegenOperation.imports.add("okhttp3.RequestBody") + // The generated Retrofit APIs use RequestBody and not File objects + codegenOperation.imports.remove("File") + } } - /** - * Output the proper enum name (capitalized). We append a 'Enum' at the end of the name to avoid - * name clashes when enums are inner classes. - * - * Please note that this method is providing the same behavior as [DefaultCodegen.toEnumName] - * and might eventually be refactored. - * - * @param property the name of the model - * @return capitalized enum name (with appended 'Enum'). - */ - override fun toEnumName(property: CodegenProperty): String { - return toModelName(property.name) + "Enum" + codegenOperation.returnType = when { + codegenOperation.isResponseFile -> { + codegenOperation.imports.add("okhttp3.ResponseBody") + wrapResponseType(codegenOperation.imports, "ResponseBody") + } + codegenOperation.returnType == null -> { + getNoResponseType(codegenOperation.imports) + } + else -> { + wrapResponseType(codegenOperation.imports, codegenOperation.returnType) + } } - override fun toModelFilename(name: String): String = toModelName(name) - - /** - * Check if a name is of the type `com.x.name`, which means it has a fully qualified package. - */ - @Suppress("NOTHING_TO_INLINE") - private inline fun String.isFullyQualifiedImportName() = "." in this - - override fun postProcessModels(objs: Map): Map { - val processedModels = postProcessModelsEnum(super.postProcessModels(objs)) - - // Sort imports. Not strictly needed, neater. - @Suppress("UNCHECKED_CAST") - val imports = processedModels["imports"] as MutableList> - imports.sortBy { it["import"] } - - return processedModels + // Let's remove the leading + if (!basePath.isNullOrBlank()) { + codegenOperation.path = codegenOperation.path.removePrefix("/") } - override fun fromOperation( - path: String?, - httpMethod: String?, - operation: Operation?, - definitions: MutableMap?, - swagger: Swagger? - ): CodegenOperation { - val codegenOperation = super.fromOperation(path, httpMethod, operation, definitions, swagger) - - retrofitImport[codegenOperation.httpMethod]?.let { codegenOperation.imports.add(it) } - codegenOperation.allParams.forEach { codegenParameter: CodegenParameter -> - codegenParameter.collectionFormat?.let { - val importName = "$toolsPackage.${it.toUpperCase()}" - if (importName !in codegenOperation.imports) { - codegenOperation.imports.add(importName) - } - } - - if (codegenParameter.isFile) { - codegenOperation.imports.add("okhttp3.RequestBody") - // The generated Retrofit APIs use RequestBody and not File objects - codegenOperation.imports.remove("File") - } - } - - codegenOperation.returnType = when { - codegenOperation.isResponseFile -> { - codegenOperation.imports.add("okhttp3.ResponseBody") - wrapResponseType(codegenOperation.imports, "ResponseBody") - } - codegenOperation.returnType == null -> { - getNoResponseType(codegenOperation.imports) - } - else -> { - wrapResponseType(codegenOperation.imports, codegenOperation.returnType) - } - } - - // Let's remove the leading - if (!basePath.isNullOrBlank()) { - codegenOperation.path = codegenOperation.path.removePrefix("/") - } - - // Let's process the top level Headers and eventually add the retrofit annotations. - processTopLevelHeaders(codegenOperation) - if (codegenOperation.vendorExtensions[HAS_OPERATION_HEADERS] == true) { - codegenOperation.imports.add("retrofit2.http.Headers") - } - - // Let's make sure we import all the types, also the inner ones (see #76). - codegenOperation.responses.forEach { - if (it.dataType != null) { - val innerType = resolveInnerType(it.dataType) - if (innerType !in codegenOperation.imports) { - codegenOperation.imports.add(innerType) - } - } - } - - return codegenOperation + // Let's process the top level Headers and eventually add the retrofit annotations. + processTopLevelHeaders(codegenOperation) + if (codegenOperation.vendorExtensions[HAS_OPERATION_HEADERS] == true) { + codegenOperation.imports.add("retrofit2.http.Headers") } - override fun postProcessOperations(objs: Map): Map { - // Cleanup imports, by removing the default includes, and sorting them by alphabetical order. - @Suppress("UNCHECKED_CAST") - val allImports = objs["imports"] as MutableList>? - allImports?.also { imports -> - val iterator = imports.iterator() - while (iterator.hasNext()) { - val import = iterator.next()["import"] - if (import in defaultIncludes) { - iterator.remove() - } - } - imports.sortBy { it["import"] } + // Let's make sure we import all the types, also the inner ones (see #76). + codegenOperation.responses.forEach { + if (it.dataType != null) { + val innerType = resolveInnerType(it.dataType) + if (innerType !in codegenOperation.imports) { + codegenOperation.imports.add(innerType) } - return objs - } - - override fun preprocessSwagger(swagger: Swagger) { - super.preprocessSwagger(swagger) - - this.basePath = swagger.basePath + } } - /** - * Function used to sanitize the name for operation generations. - * The superclass is not providing the correct string pattern (See #31). - * - * Here we override the provided pattern to include also square brackets in during the - * parameter name generation. - */ - override fun removeNonNameElementToCamelCase(name: String?): String { - return super.removeNonNameElementToCamelCase(name, "[-_:;.#\\[\\]]") - } - - /** - * Function to check if there are Headers that should be applied at the Top level on Retrofit - * with the @Headers annotation. This method will populate the `hasOperationHeaders` and `operationHeaders` - * vendor extensions to support the mustache template. - */ - internal fun processTopLevelHeaders(operation: CodegenOperation) { - val topLevelHeaders = mutableListOf>() - - // Send the X-Operation-Id header only if a custom operation ID was set. - val operationId = operation.vendorExtensions[X_OPERATION_ID] as String? - if (!operationId.isNullOrBlank()) { - topLevelHeaders.add(HEADER_X_OPERATION_ID to operationId) + return codegenOperation + } + + override fun postProcessOperations(objs: Map): Map { + // Cleanup imports, by removing the default includes, and sorting them by alphabetical order. + @Suppress("UNCHECKED_CAST") + val allImports = objs["imports"] as MutableList>? + allImports?.also { imports -> + val iterator = imports.iterator() + while (iterator.hasNext()) { + val import = iterator.next()["import"] + if (import in defaultIncludes) { + iterator.remove() } - - // Send the Content-Type header for the first `consume` mediaType specified. - val firstContentType = operation.consumes?.firstOrNull() - if (operation.formParams.isNullOrEmpty() && firstContentType != null) { - firstContentType["mediaType"]?.let { - topLevelHeaders.add(HEADER_CONTENT_TYPE to it) - } - } - - // Process the headers from the `headersToIgnore` config feature. - val headersToIgnore = getHeadersToIgnore() - topLevelHeaders.removeIf { it.first in headersToIgnore } - - operation.vendorExtensions[HAS_OPERATION_HEADERS] = topLevelHeaders.isNotEmpty() - operation.vendorExtensions[OPERATION_HEADERS] = topLevelHeaders + } + imports.sortBy { it["import"] } } - - /** - * Wraps the return type of an operation with the proper type (e.g. Single, Observable, Future, etc.) - * Use this method to eventually add imports if needed in the [imports] param. - */ - protected open fun wrapResponseType(imports: MutableSet, responsePrimitiveType: String): String { - imports.add("io.reactivex.Single") - return "Single<$responsePrimitiveType>" + return objs + } + + override fun preprocessSwagger(swagger: Swagger) { + super.preprocessSwagger(swagger) + + this.basePath = swagger.basePath + } + + /** + * Function used to sanitize the name for operation generations. + * The superclass is not providing the correct string pattern (See #31). + * + * Here we override the provided pattern to include also square brackets in during the + * parameter name generation. + */ + override fun removeNonNameElementToCamelCase(name: String?): String { + return super.removeNonNameElementToCamelCase(name, "[-_:;.#\\[\\]]") + } + + /** + * Function to check if there are Headers that should be applied at the Top level on Retrofit + * with the @Headers annotation. This method will populate the `hasOperationHeaders` and `operationHeaders` + * vendor extensions to support the mustache template. + */ + internal fun processTopLevelHeaders(operation: CodegenOperation) { + val topLevelHeaders = mutableListOf>() + + // Send the X-Operation-Id header only if a custom operation ID was set. + val operationId = operation.vendorExtensions[X_OPERATION_ID] as String? + if (!operationId.isNullOrBlank()) { + topLevelHeaders.add(HEADER_X_OPERATION_ID to operationId) } - /** - * Get the return type of operations with no ResponseType set (void, Unit, Completables). - * Use this method to eventually add imports if needed in the [imports] param. - */ - protected open fun getNoResponseType(imports: MutableSet): String { - imports.add("io.reactivex.Completable") - return "Completable" + // Send the Content-Type header for the first `consume` mediaType specified. + val firstContentType = operation.consumes?.firstOrNull() + if (operation.formParams.isNullOrEmpty() && firstContentType != null) { + firstContentType["mediaType"]?.let { + topLevelHeaders.add(HEADER_CONTENT_TYPE to it) + } } + + // Process the headers from the `headersToIgnore` config feature. + val headersToIgnore = getHeadersToIgnore() + topLevelHeaders.removeIf { it.first in headersToIgnore } + + operation.vendorExtensions[HAS_OPERATION_HEADERS] = topLevelHeaders.isNotEmpty() + operation.vendorExtensions[OPERATION_HEADERS] = topLevelHeaders + } + + /** + * Wraps the return type of an operation with the proper type (e.g. Single, Observable, Future, etc.) + * Use this method to eventually add imports if needed in the [imports] param. + */ + protected open fun wrapResponseType(imports: MutableSet, responsePrimitiveType: String): String { + imports.add("io.reactivex.Single") + return "Single<$responsePrimitiveType>" + } + + /** + * Get the return type of operations with no ResponseType set (void, Unit, Completables). + * Use this method to eventually add imports if needed in the [imports] param. + */ + protected open fun getNoResponseType(imports: MutableSet): String { + imports.add("io.reactivex.Completable") + return "Completable" + } } diff --git a/gradle-plugin/plugin/src/main/java/com/yelp/codegen/Main.kt b/gradle-plugin/plugin/src/main/java/com/yelp/codegen/Main.kt index 4de957f6..fb9d165e 100644 --- a/gradle-plugin/plugin/src/main/java/com/yelp/codegen/Main.kt +++ b/gradle-plugin/plugin/src/main/java/com/yelp/codegen/Main.kt @@ -15,87 +15,87 @@ import org.apache.commons.cli.Options import java.io.File fun main(args: Array) { - val options = Options() - options.addRequiredOption( - "p", - "platform", - true, - "The platform to generate" - ) - options.addRequiredOption( - "i", - "input", - true, - "Path to the input spec" - ) - options.addRequiredOption( - "o", - "output", - true, - "Path to the output directory" - ) - options.addRequiredOption( - "s", - "service", - true, - "Name of the service to build" - ) - options.addRequiredOption( - "v", - "version", - true, - "Version to use when generating the code." - ) - options.addRequiredOption( - "g", - "groupid", - true, - "The fully qualified domain name of company/organization." - ) - options.addRequiredOption( - "a", - "artifactid", - true, - "The artifact id to be used when generating the code." - ) - options.addOption( - Option.builder("ignoreheaders") - .hasArg().argName("Comma separated list of headers to ingore") - .desc("A comma separated list of headers that will be ignored by the generator") - .build() - ) + val options = Options() + options.addRequiredOption( + "p", + "platform", + true, + "The platform to generate" + ) + options.addRequiredOption( + "i", + "input", + true, + "Path to the input spec" + ) + options.addRequiredOption( + "o", + "output", + true, + "Path to the output directory" + ) + options.addRequiredOption( + "s", + "service", + true, + "Name of the service to build" + ) + options.addRequiredOption( + "v", + "version", + true, + "Version to use when generating the code." + ) + options.addRequiredOption( + "g", + "groupid", + true, + "The fully qualified domain name of company/organization." + ) + options.addRequiredOption( + "a", + "artifactid", + true, + "The artifact id to be used when generating the code." + ) + options.addOption( + Option.builder("ignoreheaders") + .hasArg().argName("Comma separated list of headers to ingore") + .desc("A comma separated list of headers that will be ignored by the generator") + .build() + ) - val parser: CommandLineParser = DefaultParser() - val parsed: CommandLine = parser.parse(options, args) + val parser: CommandLineParser = DefaultParser() + val parsed: CommandLine = parser.parse(options, args) - val specVersion = parsed['v'] + val specVersion = parsed['v'] - val configurator = CodegenConfigurator() - configurator.lang = parsed['p'] - configurator.inputSpec = parsed['i'] - configurator.outputDir = parsed['o'] + val configurator = CodegenConfigurator() + configurator.lang = parsed['p'] + configurator.inputSpec = parsed['i'] + configurator.outputDir = parsed['o'] - configurator.addAdditionalProperty(LANGUAGE, parsed['p']) + configurator.addAdditionalProperty(LANGUAGE, parsed['p']) - configurator.addAdditionalProperty(SPEC_VERSION, specVersion) - configurator.addAdditionalProperty(SERVICE_NAME, parsed['s']) - configurator.addAdditionalProperty(GROUP_ID, parsed['g']) - configurator.addAdditionalProperty(ARTIFACT_ID, parsed['a']) - configurator.addAdditionalProperty(HEADERS_TO_IGNORE, parsed["ignoreheaders"]) + configurator.addAdditionalProperty(SPEC_VERSION, specVersion) + configurator.addAdditionalProperty(SERVICE_NAME, parsed['s']) + configurator.addAdditionalProperty(GROUP_ID, parsed['g']) + configurator.addAdditionalProperty(ARTIFACT_ID, parsed['a']) + configurator.addAdditionalProperty(HEADERS_TO_IGNORE, parsed["ignoreheaders"]) - DefaultGenerator().opts(configurator.toClientOptInput()).generate() - copySpec(checkNotNull(configurator.inputSpec), checkNotNull(configurator.outputDir)) + DefaultGenerator().opts(configurator.toClientOptInput()).generate() + copySpec(checkNotNull(configurator.inputSpec), checkNotNull(configurator.outputDir)) } fun copySpec(inputSpec: String, outputDirectory: String) { - val swagger = SwaggerParser().read(inputSpec) - Json.mapper().writer(null as PrettyPrinter?).writeValue(File("$outputDirectory/swagger.json"), swagger) + val swagger = SwaggerParser().read(inputSpec) + Json.mapper().writer(null as PrettyPrinter?).writeValue(File("$outputDirectory/swagger.json"), swagger) } private operator fun CommandLine.get(opt: Char): String? { - return getOptionValue(opt, null) + return getOptionValue(opt, null) } private operator fun CommandLine.get(opt: String): String? { - return getOptionValue(opt, null) + return getOptionValue(opt, null) } diff --git a/gradle-plugin/plugin/src/main/java/com/yelp/codegen/SharedCodegen.kt b/gradle-plugin/plugin/src/main/java/com/yelp/codegen/SharedCodegen.kt index d717ad23..00bcf40b 100644 --- a/gradle-plugin/plugin/src/main/java/com/yelp/codegen/SharedCodegen.kt +++ b/gradle-plugin/plugin/src/main/java/com/yelp/codegen/SharedCodegen.kt @@ -44,544 +44,544 @@ internal const val HEADER_CONTENT_TYPE = "Content-Type" @Suppress("TooManyFunctions") abstract class SharedCodegen : DefaultCodegen(), CodegenConfig { - // Reference to the Swagger Specs - protected var swagger: Swagger? = null - private val xModelMatches = mutableMapOf() - private val unsafeOperations: MutableList = mutableListOf() - - override fun getTag() = CodegenType.CLIENT - - /** - * Return the platform for which the concrete codegen instance is generating code for - */ - protected abstract val platform: String - - /** - * Add all the mustache tags needed for the rendering that are dependent - * on the specific language - */ - protected abstract val mustacheTags: Map - - /** - * Add generator support files. NOTE: testing files should not be in here - */ - protected abstract val supportFiles: Collection - - /** - * Add generator support files for testing the final generated code. - */ - protected abstract val testingSupportFiles: Collection - - /** - * Returns the provided service name from the command line invocation - */ - protected val serviceName: String get() = this.additionalProperties[SERVICE_NAME] as String - - /** - * Returns the /main/resources directory to access the .mustache files - */ - protected val resourcesDirectory: File - get() = File(this.javaClass.classLoader.getResource(templateDir).path.safeSuffix(File.separator)) - - override fun processOpts() { - super.processOpts() - this.additionalProperties.putAll(mustacheTags) - this.supportingFiles.addAll(supportFiles) - this.supportingFiles.addAll(testingSupportFiles) + // Reference to the Swagger Specs + protected var swagger: Swagger? = null + private val xModelMatches = mutableMapOf() + private val unsafeOperations: MutableList = mutableListOf() + + override fun getTag() = CodegenType.CLIENT + + /** + * Return the platform for which the concrete codegen instance is generating code for + */ + protected abstract val platform: String + + /** + * Add all the mustache tags needed for the rendering that are dependent + * on the specific language + */ + protected abstract val mustacheTags: Map + + /** + * Add generator support files. NOTE: testing files should not be in here + */ + protected abstract val supportFiles: Collection + + /** + * Add generator support files for testing the final generated code. + */ + protected abstract val testingSupportFiles: Collection + + /** + * Returns the provided service name from the command line invocation + */ + protected val serviceName: String get() = this.additionalProperties[SERVICE_NAME] as String + + /** + * Returns the /main/resources directory to access the .mustache files + */ + protected val resourcesDirectory: File + get() = File(this.javaClass.classLoader.getResource(templateDir).path.safeSuffix(File.separator)) + + override fun processOpts() { + super.processOpts() + this.additionalProperties.putAll(mustacheTags) + this.supportingFiles.addAll(supportFiles) + this.supportingFiles.addAll(testingSupportFiles) + } + + override fun preprocessSwagger(swagger: Swagger) { + super.preprocessSwagger(swagger) + + // Swagger-Codegen does invoke InlineModelResolver.flatten before starting the API and Models generation + // It is a bit too late to ensure that inline models (with x-model) have the model name honored + // according to the following ordering preference: x-model, title, + // So we're triggering the process early on as the process is not super slow and more importantly is idempotent + InlineModelResolver().flatten(swagger) + + unsafeOperations.addAll( + when (val it = swagger.info.vendorExtensions["x-operation-ids-unsafe-to-use"]) { + is List<*> -> it.filterIsInstance() + else -> listOf() + } + ) + + mapXModel(swagger) + + // Override the swagger version with the one provided from command line. + swagger.info.version = additionalProperties[SPEC_VERSION] as String + + swagger.definitions?.forEach { (name, model) -> + // Ensure that all the models have a title + // The title should give priority to x-model, then title and finally + // to the name that codegen thought to use + model.title = xModelMatches[name] ?: name } - override fun preprocessSwagger(swagger: Swagger) { - super.preprocessSwagger(swagger) + this.swagger = swagger + } - // Swagger-Codegen does invoke InlineModelResolver.flatten before starting the API and Models generation - // It is a bit too late to ensure that inline models (with x-model) have the model name honored - // according to the following ordering preference: x-model, title, - // So we're triggering the process early on as the process is not super slow and more importantly is idempotent - InlineModelResolver().flatten(swagger) + override fun addAdditionPropertiesToCodeGenModel(codegenModel: CodegenModel?, swaggerModel: ModelImpl?) { + val additionalProperties = swaggerModel?.additionalProperties + if (additionalProperties != null) { + codegenModel?.additionalPropertiesType = this.getSwaggerType(additionalProperties) - unsafeOperations.addAll( - when (val it = swagger.info.vendorExtensions["x-operation-ids-unsafe-to-use"]) { - is List<*> -> it.filterIsInstance() - else -> listOf() - } - ) - - mapXModel(swagger) - - // Override the swagger version with the one provided from command line. - swagger.info.version = additionalProperties[SPEC_VERSION] as String - - swagger.definitions?.forEach { (name, model) -> - // Ensure that all the models have a title - // The title should give priority to x-model, then title and finally - // to the name that codegen thought to use - model.title = xModelMatches[name] ?: name - } - - this.swagger = swagger + // If the model has additional properties at the top level, we want to create a typealias. + // Please note that definitions with properties and additionalProperties at the top level will be + // generated as typealias as well (`properties` will be lost). + codegenModel?.isAlias = true } - - override fun addAdditionPropertiesToCodeGenModel(codegenModel: CodegenModel?, swaggerModel: ModelImpl?) { - val additionalProperties = swaggerModel?.additionalProperties - if (additionalProperties != null) { - codegenModel?.additionalPropertiesType = this.getSwaggerType(additionalProperties) - - // If the model has additional properties at the top level, we want to create a typealias. - // Please note that definitions with properties and additionalProperties at the top level will be - // generated as typealias as well (`properties` will be lost). - codegenModel?.isAlias = true - } + } + + /** + * Creates a map of all x-model declarations (or title as a fallback), so that they can be used later when + * computing models names. + */ + private fun mapXModel(swagger: Swagger) { + swagger.definitions?.forEach { (name, model) -> + (model.vendorExtensions?.get(X_MODEL) as? String?)?.let { x_model -> + xModelMatches[name] = x_model + } + xModelMatches[name] ?: model.title?.let { title -> + xModelMatches[name] = title + } } - - /** - * Creates a map of all x-model declarations (or title as a fallback), so that they can be used later when - * computing models names. - */ - private fun mapXModel(swagger: Swagger) { - swagger.definitions?.forEach { (name, model) -> - (model.vendorExtensions?.get(X_MODEL) as? String?)?.let { x_model -> - xModelMatches[name] = x_model - } - xModelMatches[name] ?: model.title?.let { title -> - xModelMatches[name] = title - } - } + } + + /** + * Returns the x-model alternative name if it was defined. + * If the x-model alternative name is not found then the call will + * use the defined title, if any, or returns the input name + */ + fun matchXModel(name: String): String { + return xModelMatches[name] ?: ( + this.swagger?.definitions?.get(name)?.title ?: name + ) + } + + /** + * Method to propagate all the X-Nullable annotations from the referenced definition to the place where that + * reference is used. + * + * We need to investigate all the [RefProperty] of the current [Model] parameter, and check if their definition + * in the `allDefinitions` object is marked as x-nullable. + * + * This method is covering those cases: + * - Property that are using refs + * - AdditionalProperties at the top level that are using refs + * - Arrays at the top level that are using refs + * + * This is making sure that types are annotated properly when they're used. E.g. when used in Retrofit Apis. + */ + protected fun propagateXNullable(model: Model, allDefinitions: MutableMap?) { + if (allDefinitions == null) { + return } - - /** - * Returns the x-model alternative name if it was defined. - * If the x-model alternative name is not found then the call will - * use the defined title, if any, or returns the input name - */ - fun matchXModel(name: String): String { - return xModelMatches[name] ?: ( - this.swagger?.definitions?.get(name)?.title ?: name - ) + // If the model has properties, we need to investigate all of them. + if (model.properties != null) { + propagateXNullableToProperties(model, allDefinitions) } - - /** - * Method to propagate all the X-Nullable annotations from the referenced definition to the place where that - * reference is used. - * - * We need to investigate all the [RefProperty] of the current [Model] parameter, and check if their definition - * in the `allDefinitions` object is marked as x-nullable. - * - * This method is covering those cases: - * - Property that are using refs - * - AdditionalProperties at the top level that are using refs - * - Arrays at the top level that are using refs - * - * This is making sure that types are annotated properly when they're used. E.g. when used in Retrofit Apis. - */ - protected fun propagateXNullable(model: Model, allDefinitions: MutableMap?) { - if (allDefinitions == null) { - return - } - // If the model has properties, we need to investigate all of them. - if (model.properties != null) { - propagateXNullableToProperties(model, allDefinitions) - } - // If the model has additionalProperties at the top level, investigate it. - if (model is ModelImpl && model.additionalProperties != null && model.additionalProperties is RefProperty) { - propagateXNullableVendorExtension(model.additionalProperties as RefProperty, allDefinitions) - } - // If the model has `items` (is an array) at the top level, investigate it. - if (model is ArrayModel && model.items != null && model.items is RefProperty) { - propagateXNullableVendorExtension(model.items as RefProperty, allDefinitions) - } + // If the model has additionalProperties at the top level, investigate it. + if (model is ModelImpl && model.additionalProperties != null && model.additionalProperties is RefProperty) { + propagateXNullableVendorExtension(model.additionalProperties as RefProperty, allDefinitions) } - - /** - * Given a model determine what is the underlying data type ensuring. - * The method takes care of: - * * references to references - * * composed models where only one of the allOf items is responsible for type definition - */ - private fun getModelDataType(model: Model?): String? { - return when (model) { - is ModelImpl -> { - if (model.type != null) { - model.type - } else { - if (false == model.properties?.isEmpty() || - model.additionalProperties != null - ) { - "object" - } else { - null - } - } - } - is RefModel -> toModelName(model.simpleRef) - is ComposedModel -> { - val allOfModelDefinitions = model.allOf.mapNotNull { allOfItem -> - when (allOfItem) { - is Model, is RefModel -> getModelDataType(allOfItem) - else -> null - } - } - if (allOfModelDefinitions.size == 1) { - allOfModelDefinitions[0] - } else { - null - } - } - else -> null - } + // If the model has `items` (is an array) at the top level, investigate it. + if (model is ArrayModel && model.items != null && model.items is RefProperty) { + propagateXNullableVendorExtension(model.items as RefProperty, allDefinitions) } - - override fun fromModel(name: String, model: Model, allDefinitions: MutableMap?): CodegenModel { - propagateXNullable(model, allDefinitions) - val codegenModel = super.fromModel(name, model, allDefinitions) - - // Deal with composed models (models with allOf) that are meant to override descriptions and - // with references to references - if (model is ComposedModel || model is RefModel) { - getModelDataType(model)?.let { - codegenModel.isAlias = true - codegenModel.dataType = it - // This workaround is done to prevent regeneration of enums that would not be used anyway as - // the current codegenModel is a pure type alias - codegenModel.hasEnums = false - } + } + + /** + * Given a model determine what is the underlying data type ensuring. + * The method takes care of: + * * references to references + * * composed models where only one of the allOf items is responsible for type definition + */ + private fun getModelDataType(model: Model?): String? { + return when (model) { + is ModelImpl -> { + if (model.type != null) { + model.type + } else { + if (false == model.properties?.isEmpty() || + model.additionalProperties != null + ) { + "object" + } else { + null + } } - - // Top level array Models should generate a typealias. - if (codegenModel.isArrayModel) { - codegenModel.isAlias = true + } + is RefModel -> toModelName(model.simpleRef) + is ComposedModel -> { + val allOfModelDefinitions = model.allOf.mapNotNull { allOfItem -> + when (allOfItem) { + is Model, is RefModel -> getModelDataType(allOfItem) + else -> null + } } - - // If model is an Alias will generate a typealias. We need to check if the type is aliasing - // to any 'x-nullable' annotated model. - if (codegenModel.isAlias) { - codegenModel.dataType = getAliasTypeDeclaration(codegenModel) - checkForEnumsInTopLevel(codegenModel, model) + if (allOfModelDefinitions.size == 1) { + allOfModelDefinitions[0] + } else { + null } - - handleXNullable(codegenModel) - return codegenModel + } + else -> null } - - /** - * Find variables in the model that contain the x-nullable vendorExtensions, - * and mark them as optional instead of required. - */ - internal open fun handleXNullable(codegenModel: CodegenModel) { - val requiredIterator = codegenModel.requiredVars.iterator() - while (requiredIterator.hasNext()) { - val property = requiredIterator.next() - if (property.vendorExtensions[X_NULLABLE] == true) { - requiredIterator.remove() - property.required = false - codegenModel.optionalVars.add(property) - codegenModel.hasOptional = true - } - } - // If we moved all required vars to optional because they are all x-nullable, hasRequired must be false. - if (codegenModel.requiredVars.isEmpty()) { - codegenModel.hasRequired = false - } + } + + override fun fromModel(name: String, model: Model, allDefinitions: MutableMap?): CodegenModel { + propagateXNullable(model, allDefinitions) + val codegenModel = super.fromModel(name, model, allDefinitions) + + // Deal with composed models (models with allOf) that are meant to override descriptions and + // with references to references + if (model is ComposedModel || model is RefModel) { + getModelDataType(model)?.let { + codegenModel.isAlias = true + codegenModel.dataType = it + // This workaround is done to prevent regeneration of enums that would not be used anyway as + // the current codegenModel is a pure type alias + codegenModel.hasEnums = false + } } - /** - * Private method to investigate all the properties of a models, filter only the [RefProperty] and eventually - * propagate the `x-nullable` vendor extension. - */ - private fun propagateXNullableToProperties(model: Model, allDefinitions: MutableMap) { - model.properties - .values - .filterIsInstance(RefProperty::class.java) - .forEach { propagateXNullableVendorExtension(it, allDefinitions) } + // Top level array Models should generate a typealias. + if (codegenModel.isArrayModel) { + codegenModel.isAlias = true } - /** - * Private method to propagate the `x-nullable` vendor extension form the global definitions to the usage. - */ - private fun propagateXNullableVendorExtension( - refProperty: RefProperty, - allDefinitions: MutableMap - ) { - if (allDefinitions[refProperty.simpleRef]?.vendorExtensions?.get(X_NULLABLE) == true) { - refProperty.vendorExtensions[X_NULLABLE] = true - } + // If model is an Alias will generate a typealias. We need to check if the type is aliasing + // to any 'x-nullable' annotated model. + if (codegenModel.isAlias) { + codegenModel.dataType = getAliasTypeDeclaration(codegenModel) + checkForEnumsInTopLevel(codegenModel, model) } - /** - * Method to check if a top level definition (array or map) contains an enum that needs to be defined. - * By default those top level definitions will create objects like `List` and `Map`. - * - * This method will check if the [StringProperty] has an enum and attach it as a variable to the [CodegenModel]. - * This will allow us to generate the proper definitions for the enum. - * Furthermore the dataType will be updated to use the Enum type (rather than string) - */ - protected fun checkForEnumsInTopLevel(codegenModel: CodegenModel, model: Model) { - var innerEnum: CodegenProperty? = null - - // Checking if the top level definition is an array with a string property and enum. - if (model is ArrayModel && model.items is StringProperty) { - val items = model.items as StringProperty - if (items.enum != null) { - innerEnum = fromProperty(codegenModel.name, model.items) - } - } - // Checking if the top level definition is a map with a string property and enum. - if (model is ModelImpl && model.additionalProperties is StringProperty) { - val items = model.additionalProperties as StringProperty - if (items.enum != null) { - innerEnum = fromProperty(codegenModel.name, model.additionalProperties) - } - } - if (innerEnum == null) { - // No inner enum found, then you have nothing to do. - return - } - codegenModel.hasEnums = true - codegenModel.vars.add(innerEnum) - codegenModel.dataType = - codegenModel.dataType.replace(defaultStringType(), innerEnum.datatypeWithEnum) + handleXNullable(codegenModel) + return codegenModel + } + + /** + * Find variables in the model that contain the x-nullable vendorExtensions, + * and mark them as optional instead of required. + */ + internal open fun handleXNullable(codegenModel: CodegenModel) { + val requiredIterator = codegenModel.requiredVars.iterator() + while (requiredIterator.hasNext()) { + val property = requiredIterator.next() + if (property.vendorExtensions[X_NULLABLE] == true) { + requiredIterator.remove() + property.required = false + codegenModel.optionalVars.add(property) + codegenModel.hasOptional = true + } } - - /** - * Method to return the list of Header parameters that we want to suppress from the generated code. - * - * Client code might have a centralized way to handle the headers (Android is attaching them with an OkHttp - * Header Interceptor) and is helpful to remove the header from the endpoints to avoid confusion. - */ - protected fun getHeadersToIgnore(): List { - val headerList = mutableListOf() - val headerParam = additionalProperties[HEADERS_TO_IGNORE] as? String - if (headerParam != null) { - headerList.addAll(headerParam.split(',')) - } - return headerList.toList() + // If we moved all required vars to optional because they are all x-nullable, hasRequired must be false. + if (codegenModel.requiredVars.isEmpty()) { + codegenModel.hasRequired = false } - - /** - * Method to remove the a header parameter from a [CodegenOperation]. - */ - protected fun ignoreHeaderParameter(headerName: String, codegenOperation: CodegenOperation) { - codegenOperation.headerParams.removeAll { - it.baseName!!.contentEquals(headerName) - } - codegenOperation.allParams.removeAll { - it.baseName!!.contentEquals(headerName) - } - - // If we removed the last parameter of the Operation, we should update the `hasMore` flag. - codegenOperation.allParams.lastOrNull()?.hasMore = false + } + + /** + * Private method to investigate all the properties of a models, filter only the [RefProperty] and eventually + * propagate the `x-nullable` vendor extension. + */ + private fun propagateXNullableToProperties(model: Model, allDefinitions: MutableMap) { + model.properties + .values + .filterIsInstance(RefProperty::class.java) + .forEach { propagateXNullableVendorExtension(it, allDefinitions) } + } + + /** + * Private method to propagate the `x-nullable` vendor extension form the global definitions to the usage. + */ + private fun propagateXNullableVendorExtension( + refProperty: RefProperty, + allDefinitions: MutableMap + ) { + if (allDefinitions[refProperty.simpleRef]?.vendorExtensions?.get(X_NULLABLE) == true) { + refProperty.vendorExtensions[X_NULLABLE] = true } - - /** - * Resolve the type declaration of a [Property]. - * Please note that this method will recursively resolve all the types. - * For ArrayProperties this will generate a `List of ` - * For MapProperties this will generate a `Map from String to ` - * For other Properties this will resolve the type and evaluate the `X-Nullability` - */ - internal fun resolvePropertyType( - property: Property, - listTypeWrapper: (String, String) -> String = ::listTypeWrapper, - mapTypeWrapper: (String, String) -> String = ::mapTypeWrapper - ): String { - return when (property) { - is ArrayProperty -> { - // Will generate a type like List - listTypeWrapper(getSwaggerType(property), resolvePropertyType(property.items)) - } - is MapProperty -> { - // Will generate a type like Map - mapTypeWrapper(getSwaggerType(property), resolvePropertyType(property.additionalProperties)) - } - // Please note that calling super.getTypeDeclaration() will block the recursion - // and will pick a type from the typeMapping. - // Here we want to evaluate the X-Nullability and eventually annotate the type. - else -> { - val baseType = super.getTypeDeclaration(property) - return if (property.isXNullable()) { - baseType.safeSuffix("?") - } else { - baseType - } - } - } + } + + /** + * Method to check if a top level definition (array or map) contains an enum that needs to be defined. + * By default those top level definitions will create objects like `List` and `Map`. + * + * This method will check if the [StringProperty] has an enum and attach it as a variable to the [CodegenModel]. + * This will allow us to generate the proper definitions for the enum. + * Furthermore the dataType will be updated to use the Enum type (rather than string) + */ + protected fun checkForEnumsInTopLevel(codegenModel: CodegenModel, model: Model) { + var innerEnum: CodegenProperty? = null + + // Checking if the top level definition is an array with a string property and enum. + if (model is ArrayModel && model.items is StringProperty) { + val items = model.items as StringProperty + if (items.enum != null) { + innerEnum = fromProperty(codegenModel.name, model.items) + } } - - /** - * Private method to return a dataType for a [CodegenModel] that is an Alias. - * This is useful for populating type for model with 'additionalProperties' at the top level (Maps) - * or `items` at the top level (Arrays). - * Their returned type would be a `Map` or `List`, where `Any?` will be the aliased type. - * - * The method will call [KotlinAndroidGenerator.resolvePropertyType] that will perform a check if the model - * is aliasing to a 'x-nullable' annotated model and compute the proper type (adding a `?` if needed). - * - * ``` - * // e.g. for a not 'x-nullable' additionalProperty type - * typealias myModel = Map - * - * // or this fon a 'x-nullable' additionalProperty type - * typealias myModel = Map - * ``` - */ - internal fun getAliasTypeDeclaration( - codegenModel: CodegenModel, - listTypeWrapper: (String, String) -> String = ::listTypeWrapper, - mapTypeWrapper: (String, String) -> String = ::mapTypeWrapper - ): String? { - - // If the codegenModel has arrayModelType properties here (top level) must alias to a list. - if (codegenModel.isArrayModel) { - val innerProperty = (this.swagger?.definitions?.get(codegenModel.name) as ArrayModel).items - return listTypeWrapper(defaultListType(), resolvePropertyType(innerProperty)) - } - - // If the codegenModel has additional properties here (top level) must alias to a map. - // This method will generate the proper type of the alias. - if (codegenModel.additionalPropertiesType != null) { - val innerProperty = (this.swagger?.definitions?.get(codegenModel.name) as ModelImpl).additionalProperties - return mapTypeWrapper(defaultMapType(), resolvePropertyType(innerProperty)) - } - - return codegenModel.dataType + // Checking if the top level definition is a map with a string property and enum. + if (model is ModelImpl && model.additionalProperties is StringProperty) { + val items = model.additionalProperties as StringProperty + if (items.enum != null) { + innerEnum = fromProperty(codegenModel.name, model.additionalProperties) + } + } + if (innerEnum == null) { + // No inner enum found, then you have nothing to do. + return + } + codegenModel.hasEnums = true + codegenModel.vars.add(innerEnum) + codegenModel.dataType = + codegenModel.dataType.replace(defaultStringType(), innerEnum.datatypeWithEnum) + } + + /** + * Method to return the list of Header parameters that we want to suppress from the generated code. + * + * Client code might have a centralized way to handle the headers (Android is attaching them with an OkHttp + * Header Interceptor) and is helpful to remove the header from the endpoints to avoid confusion. + */ + protected fun getHeadersToIgnore(): List { + val headerList = mutableListOf() + val headerParam = additionalProperties[HEADERS_TO_IGNORE] as? String + if (headerParam != null) { + headerList.addAll(headerParam.split(',')) + } + return headerList.toList() + } + + /** + * Method to remove the a header parameter from a [CodegenOperation]. + */ + protected fun ignoreHeaderParameter(headerName: String, codegenOperation: CodegenOperation) { + codegenOperation.headerParams.removeAll { + it.baseName!!.contentEquals(headerName) + } + codegenOperation.allParams.removeAll { + it.baseName!!.contentEquals(headerName) } - /** - * Resolve the inner type from a complex type. E.g: - * List> ---> Int - * Map>> ---> Object - */ - internal tailrec fun resolveInnerType( - baseType: String - ): String { - if (isListTypeWrapped(baseType)) { - return resolveInnerType(listTypeUnwrapper(baseType)) + // If we removed the last parameter of the Operation, we should update the `hasMore` flag. + codegenOperation.allParams.lastOrNull()?.hasMore = false + } + + /** + * Resolve the type declaration of a [Property]. + * Please note that this method will recursively resolve all the types. + * For ArrayProperties this will generate a `List of ` + * For MapProperties this will generate a `Map from String to ` + * For other Properties this will resolve the type and evaluate the `X-Nullability` + */ + internal fun resolvePropertyType( + property: Property, + listTypeWrapper: (String, String) -> String = ::listTypeWrapper, + mapTypeWrapper: (String, String) -> String = ::mapTypeWrapper + ): String { + return when (property) { + is ArrayProperty -> { + // Will generate a type like List + listTypeWrapper(getSwaggerType(property), resolvePropertyType(property.items)) + } + is MapProperty -> { + // Will generate a type like Map + mapTypeWrapper(getSwaggerType(property), resolvePropertyType(property.additionalProperties)) + } + // Please note that calling super.getTypeDeclaration() will block the recursion + // and will pick a type from the typeMapping. + // Here we want to evaluate the X-Nullability and eventually annotate the type. + else -> { + val baseType = super.getTypeDeclaration(property) + return if (property.isXNullable()) { + baseType.safeSuffix("?") + } else { + baseType } - if (isMapTypeWrapped(baseType)) { - return resolveInnerType(mapTypeUnwrapper(baseType)) - } - - return baseType + } + } + } + + /** + * Private method to return a dataType for a [CodegenModel] that is an Alias. + * This is useful for populating type for model with 'additionalProperties' at the top level (Maps) + * or `items` at the top level (Arrays). + * Their returned type would be a `Map` or `List`, where `Any?` will be the aliased type. + * + * The method will call [KotlinAndroidGenerator.resolvePropertyType] that will perform a check if the model + * is aliasing to a 'x-nullable' annotated model and compute the proper type (adding a `?` if needed). + * + * ``` + * // e.g. for a not 'x-nullable' additionalProperty type + * typealias myModel = Map + * + * // or this fon a 'x-nullable' additionalProperty type + * typealias myModel = Map + * ``` + */ + internal fun getAliasTypeDeclaration( + codegenModel: CodegenModel, + listTypeWrapper: (String, String) -> String = ::listTypeWrapper, + mapTypeWrapper: (String, String) -> String = ::mapTypeWrapper + ): String? { + + // If the codegenModel has arrayModelType properties here (top level) must alias to a list. + if (codegenModel.isArrayModel) { + val innerProperty = (this.swagger?.definitions?.get(codegenModel.name) as ArrayModel).items + return listTypeWrapper(defaultListType(), resolvePropertyType(innerProperty)) } - /** - * Determine if the swagger operation consumes mutipart content. - */ - private fun isMultipartOperation(operation: Operation?): Boolean { - return operation?.consumes?.any { it == "multipart/form-data" } ?: false + // If the codegenModel has additional properties here (top level) must alias to a map. + // This method will generate the proper type of the alias. + if (codegenModel.additionalPropertiesType != null) { + val innerProperty = (this.swagger?.definitions?.get(codegenModel.name) as ModelImpl).additionalProperties + return mapTypeWrapper(defaultMapType(), resolvePropertyType(innerProperty)) } - /** - * Convert Swagger Operation object to Codegen Operation object - * - * The function takes care of adding additional vendor extensions on the Codegen Operation - * to better support the swagger-gradle-codegen use-case - * 1) X_OPERATION_ID : added as we want to render operation ids on the final API artifacts - * 2) X_UNSAFE_OPERATION : added as we want to mark as deprecated APIs for which we're not sure - * that will work exactly as expected in the generated code - * - * @return the converted codegen operation - */ - override fun fromOperation( - path: String?, - httpMethod: String?, - operation: Operation?, - definitions: MutableMap?, - swagger: Swagger? - ): CodegenOperation { - val codegenOperation = super.fromOperation(path, httpMethod, operation, definitions, swagger) - codegenOperation.vendorExtensions[X_OPERATION_ID] = operation?.operationId - getHeadersToIgnore().forEach { headerName -> - ignoreHeaderParameter(headerName, codegenOperation) - } - if (unsafeOperations.contains(operation?.operationId)) { - codegenOperation.vendorExtensions[X_UNSAFE_OPERATION] = true - } - codegenOperation.isMultipart = isMultipartOperation(operation) + return codegenModel.dataType + } + + /** + * Resolve the inner type from a complex type. E.g: + * List> ---> Int + * Map>> ---> Object + */ + internal tailrec fun resolveInnerType( + baseType: String + ): String { + if (isListTypeWrapped(baseType)) { + return resolveInnerType(listTypeUnwrapper(baseType)) + } + if (isMapTypeWrapped(baseType)) { + return resolveInnerType(mapTypeUnwrapper(baseType)) + } - if (!codegenOperation.isMultipart && codegenOperation.allParams.any { it.isFile }) { - // According to the swagger specifications in order to send files the operation must - // consume multipart/form-data (https://swagger.io/docs/specification/2-0/file-upload/) - codegenOperation.vendorExtensions[X_UNSAFE_OPERATION] = true - } + return baseType + } + + /** + * Determine if the swagger operation consumes mutipart content. + */ + private fun isMultipartOperation(operation: Operation?): Boolean { + return operation?.consumes?.any { it == "multipart/form-data" } ?: false + } + + /** + * Convert Swagger Operation object to Codegen Operation object + * + * The function takes care of adding additional vendor extensions on the Codegen Operation + * to better support the swagger-gradle-codegen use-case + * 1) X_OPERATION_ID : added as we want to render operation ids on the final API artifacts + * 2) X_UNSAFE_OPERATION : added as we want to mark as deprecated APIs for which we're not sure + * that will work exactly as expected in the generated code + * + * @return the converted codegen operation + */ + override fun fromOperation( + path: String?, + httpMethod: String?, + operation: Operation?, + definitions: MutableMap?, + swagger: Swagger? + ): CodegenOperation { + val codegenOperation = super.fromOperation(path, httpMethod, operation, definitions, swagger) + codegenOperation.vendorExtensions[X_OPERATION_ID] = operation?.operationId + getHeadersToIgnore().forEach { headerName -> + ignoreHeaderParameter(headerName, codegenOperation) + } + if (unsafeOperations.contains(operation?.operationId)) { + codegenOperation.vendorExtensions[X_UNSAFE_OPERATION] = true + } + codegenOperation.isMultipart = isMultipartOperation(operation) - return codegenOperation + if (!codegenOperation.isMultipart && codegenOperation.allParams.any { it.isFile }) { + // According to the swagger specifications in order to send files the operation must + // consume multipart/form-data (https://swagger.io/docs/specification/2-0/file-upload/) + codegenOperation.vendorExtensions[X_UNSAFE_OPERATION] = true } - /** - * Abstract function to create a type for a JSON Array. - * @param listType A List Type (e.g. `List`, `ArrayList`, etc) - * @param innerType The List value Type (e.g. `String`, `Integer`, `Any?`, etc.) - * @return The composed list type (e.g. `List`, `[ String ]`, etc. - */ - protected abstract fun listTypeWrapper(listType: String, innerType: String): String - - /** - * Abstract function to unwrap a JSON Array type. - * @param baseType A JSON list type (e.g. `List`) - * @return The unwrapped inner type (e.g. `String`). - * @see isListTypeWrapped - */ - protected abstract fun listTypeUnwrapper(baseType: String): String - - /** - * Abstract function to check if a type is a JSON Array type. - * @param baseType A JSON type - * @return True if the type is a JSON Array type and can be safely unwrapped with [listTypeUnwrapper] - */ - protected abstract fun isListTypeWrapped(baseType: String): Boolean - - /** - * Abstract function to create a type for a JSON Object (A Map from String to values). - * Please note that in JSON Maps have only Strings as keys. - * - * @param mapType A Map Type (e.g. `Map`, `HashMap`, `Dictionary`, etc.) - * @param innerType The Value Type (e.g. `String`, `Integer`, `Any?`, etc.) - * @return The composed map type (e.g. `Map`, `[String: Integer]`, etc. - */ - protected abstract fun mapTypeWrapper(mapType: String, innerType: String): String - - /** - * Abstract function to unwrap a JSON Map type. - * @param baseType A JSON map type (e.g. `Map`) - * @return The unwrapped inner type (e.g. `Item`). - * @see isMapTypeWrapped - */ - protected abstract fun mapTypeUnwrapper(baseType: String): String - - /** - * Abstract function to check if a type is a JSON Map type. - * @param baseType A JSON type - * @return True if the type is a JSON Map type and can be safely unwrapped with [mapTypeUnwrapper] - */ - protected abstract fun isMapTypeWrapped(baseType: String): Boolean - - /** - * Abstract function to create a type from a Nullable type. - * @param baseType A type (e.g. `Integer`). - * @return The nullable version of the [baseType] (e.g. `Integer?` for Kotlin) - */ - protected abstract fun nullableTypeWrapper(baseType: String): String - - private fun defaultListType() = typeMapping["list"] ?: "" - - private fun defaultMapType() = typeMapping["map"] ?: "" - - private fun defaultStringType() = typeMapping["string"] ?: "" - - /** - * Checking if the type is marked as XNullable. - */ - internal fun Property.isXNullable() = this.vendorExtensions[X_NULLABLE] == true - - /** - * Checking if the type should be nullable. - * Nullable type are either not required or x-nullable annotated properties. - */ - internal fun Property.isNullable() = !this.required || this.vendorExtensions[X_NULLABLE] == true - - /** - * Checking if the type should be nullable. - * Nullable type are either not required or x-nullable annotated properties. - */ - internal fun CodegenProperty.isNullable() = !this.required || this.vendorExtensions[X_NULLABLE] == true + return codegenOperation + } + + /** + * Abstract function to create a type for a JSON Array. + * @param listType A List Type (e.g. `List`, `ArrayList`, etc) + * @param innerType The List value Type (e.g. `String`, `Integer`, `Any?`, etc.) + * @return The composed list type (e.g. `List`, `[ String ]`, etc. + */ + protected abstract fun listTypeWrapper(listType: String, innerType: String): String + + /** + * Abstract function to unwrap a JSON Array type. + * @param baseType A JSON list type (e.g. `List`) + * @return The unwrapped inner type (e.g. `String`). + * @see isListTypeWrapped + */ + protected abstract fun listTypeUnwrapper(baseType: String): String + + /** + * Abstract function to check if a type is a JSON Array type. + * @param baseType A JSON type + * @return True if the type is a JSON Array type and can be safely unwrapped with [listTypeUnwrapper] + */ + protected abstract fun isListTypeWrapped(baseType: String): Boolean + + /** + * Abstract function to create a type for a JSON Object (A Map from String to values). + * Please note that in JSON Maps have only Strings as keys. + * + * @param mapType A Map Type (e.g. `Map`, `HashMap`, `Dictionary`, etc.) + * @param innerType The Value Type (e.g. `String`, `Integer`, `Any?`, etc.) + * @return The composed map type (e.g. `Map`, `[String: Integer]`, etc. + */ + protected abstract fun mapTypeWrapper(mapType: String, innerType: String): String + + /** + * Abstract function to unwrap a JSON Map type. + * @param baseType A JSON map type (e.g. `Map`) + * @return The unwrapped inner type (e.g. `Item`). + * @see isMapTypeWrapped + */ + protected abstract fun mapTypeUnwrapper(baseType: String): String + + /** + * Abstract function to check if a type is a JSON Map type. + * @param baseType A JSON type + * @return True if the type is a JSON Map type and can be safely unwrapped with [mapTypeUnwrapper] + */ + protected abstract fun isMapTypeWrapped(baseType: String): Boolean + + /** + * Abstract function to create a type from a Nullable type. + * @param baseType A type (e.g. `Integer`). + * @return The nullable version of the [baseType] (e.g. `Integer?` for Kotlin) + */ + protected abstract fun nullableTypeWrapper(baseType: String): String + + private fun defaultListType() = typeMapping["list"] ?: "" + + private fun defaultMapType() = typeMapping["map"] ?: "" + + private fun defaultStringType() = typeMapping["string"] ?: "" + + /** + * Checking if the type is marked as XNullable. + */ + internal fun Property.isXNullable() = this.vendorExtensions[X_NULLABLE] == true + + /** + * Checking if the type should be nullable. + * Nullable type are either not required or x-nullable annotated properties. + */ + internal fun Property.isNullable() = !this.required || this.vendorExtensions[X_NULLABLE] == true + + /** + * Checking if the type should be nullable. + * Nullable type are either not required or x-nullable annotated properties. + */ + internal fun CodegenProperty.isNullable() = !this.required || this.vendorExtensions[X_NULLABLE] == true } diff --git a/gradle-plugin/plugin/src/main/java/com/yelp/codegen/plugin/CodegenPlugin.kt b/gradle-plugin/plugin/src/main/java/com/yelp/codegen/plugin/CodegenPlugin.kt index 1bda800f..7d3d529a 100644 --- a/gradle-plugin/plugin/src/main/java/com/yelp/codegen/plugin/CodegenPlugin.kt +++ b/gradle-plugin/plugin/src/main/java/com/yelp/codegen/plugin/CodegenPlugin.kt @@ -5,23 +5,23 @@ import org.gradle.api.Project import org.gradle.util.GradleVersion class CodegenPlugin : Plugin { - override fun apply(project: Project) { - require(GradleVersion.current() >= GradleVersion.version("5.4.1")) { - "com.yelp.codegen.plugin requires Gradle version 5.4.1 or greater" - } + override fun apply(project: Project) { + require(GradleVersion.current() >= GradleVersion.version("5.4.1")) { + "com.yelp.codegen.plugin requires Gradle version 5.4.1 or greater" + } - val config = project.extensions.create("generateSwagger", GenerateTaskConfiguration::class.java, project) + val config = project.extensions.create("generateSwagger", GenerateTaskConfiguration::class.java, project) - project.tasks.register("generateSwagger", GenerateTask::class.java) { - it.platform.set(config.platform) - it.packageName.set(config.packageName) - it.specName.set(config.specName) - it.specVersion.set(config.specVersion) - it.inputFile.set(config.inputFile) - it.outputDir.set(config.outputDir) + project.tasks.register("generateSwagger", GenerateTask::class.java) { + it.platform.set(config.platform) + it.packageName.set(config.packageName) + it.specName.set(config.specName) + it.specVersion.set(config.specVersion) + it.inputFile.set(config.inputFile) + it.outputDir.set(config.outputDir) - it.extraFiles.set(config.extraFiles) - it.features = config.features - } + it.extraFiles.set(config.extraFiles) + it.features = config.features } + } } diff --git a/gradle-plugin/plugin/src/main/java/com/yelp/codegen/plugin/FeatureConfiguration.kt b/gradle-plugin/plugin/src/main/java/com/yelp/codegen/plugin/FeatureConfiguration.kt index 39c15e61..ee5e387c 100644 --- a/gradle-plugin/plugin/src/main/java/com/yelp/codegen/plugin/FeatureConfiguration.kt +++ b/gradle-plugin/plugin/src/main/java/com/yelp/codegen/plugin/FeatureConfiguration.kt @@ -5,7 +5,7 @@ import org.gradle.api.tasks.Input import org.gradle.api.tasks.Optional class FeatureConfiguration(objectFactory: ObjectFactory) { - @get:Input - @get:Optional - val headersToRemove = objectFactory.listProperty(String::class.java) + @get:Input + @get:Optional + val headersToRemove = objectFactory.listProperty(String::class.java) } diff --git a/gradle-plugin/plugin/src/main/java/com/yelp/codegen/plugin/GenerateTask.kt b/gradle-plugin/plugin/src/main/java/com/yelp/codegen/plugin/GenerateTask.kt index 445f487c..65c107b9 100644 --- a/gradle-plugin/plugin/src/main/java/com/yelp/codegen/plugin/GenerateTask.kt +++ b/gradle-plugin/plugin/src/main/java/com/yelp/codegen/plugin/GenerateTask.kt @@ -17,60 +17,60 @@ import org.gradle.api.tasks.options.Option abstract class GenerateTask : DefaultTask() { - init { - description = "Run the Swagger Code Generation tool" - group = BasePlugin.BUILD_GROUP - } - - @get:Input - @get:Option(option = "platform", description = "Configures the platform that is used for generating the code.") - abstract val platform: Property - - @get:Input - @get:Option(option = "packageName", description = "Configures the package name of the resulting code.") - abstract val packageName: Property - - @get:Input - @get:Option(option = "specName", description = "Configures the name of the service for the Swagger Spec.") - abstract val specName: Property - - @get:Input - @get:Option(option = "specVersion", description = "Configures the version of the Swagger Spec.") - abstract val specVersion: Property - - @get:InputFile - @get:Option(option = "inputFile", description = "Configures path of the Swagger Spec.") - abstract val inputFile: RegularFileProperty - - @get:OutputDirectory - @get:Option(option = "outputDir", description = "Configures path of the Generated code directory.") - abstract val outputDir: DirectoryProperty - - @get:InputFiles - @get:Optional - @get:Option( - option = "extraFiles", - description = "Configures path of the extra files directory to be added to the Generated code." - ) - abstract val extraFiles: DirectoryProperty - - @get:Nested - @get:Option(option = "featureHeaderToRemove", description = "") - var features: FeatureConfiguration? = null - - @TaskAction - fun swaggerGenerate() { - val platform = platform.get() - val specName = specName.get() - val packageName = packageName.get() - val outputDir = outputDir.get().asFile - val inputFile = inputFile.get().asFile - val specVersion = specVersion.get() - - val headersToRemove = features?.headersToRemove?.get() ?: emptyList() - - println( - """ + init { + description = "Run the Swagger Code Generation tool" + group = BasePlugin.BUILD_GROUP + } + + @get:Input + @get:Option(option = "platform", description = "Configures the platform that is used for generating the code.") + abstract val platform: Property + + @get:Input + @get:Option(option = "packageName", description = "Configures the package name of the resulting code.") + abstract val packageName: Property + + @get:Input + @get:Option(option = "specName", description = "Configures the name of the service for the Swagger Spec.") + abstract val specName: Property + + @get:Input + @get:Option(option = "specVersion", description = "Configures the version of the Swagger Spec.") + abstract val specVersion: Property + + @get:InputFile + @get:Option(option = "inputFile", description = "Configures path of the Swagger Spec.") + abstract val inputFile: RegularFileProperty + + @get:OutputDirectory + @get:Option(option = "outputDir", description = "Configures path of the Generated code directory.") + abstract val outputDir: DirectoryProperty + + @get:InputFiles + @get:Optional + @get:Option( + option = "extraFiles", + description = "Configures path of the extra files directory to be added to the Generated code." + ) + abstract val extraFiles: DirectoryProperty + + @get:Nested + @get:Option(option = "featureHeaderToRemove", description = "") + var features: FeatureConfiguration? = null + + @TaskAction + fun swaggerGenerate() { + val platform = platform.get() + val specName = specName.get() + val packageName = packageName.get() + val outputDir = outputDir.get().asFile + val inputFile = inputFile.get().asFile + val specVersion = specVersion.get() + + val headersToRemove = features?.headersToRemove?.get() ?: emptyList() + + println( + """ #################### Yelp Swagger Codegen #################### @@ -83,35 +83,35 @@ abstract class GenerateTask : DefaultTask() { groupId ${'\t'} $packageName artifactId ${'\t'} $packageName features ${'\t'} ${headersToRemove.joinToString(separator = ",", prefix = "[", postfix = "]")} - """.trimIndent() - ) - - val params = mutableListOf() - params.add("-p") - params.add(platform) - params.add("-s") - params.add(specName) - params.add("-v") - params.add(specVersion) - params.add("-g") - params.add(packageName.substringBeforeLast('.')) - params.add("-a") - params.add(packageName.substringAfterLast('.')) - params.add("-i") - params.add(inputFile.toString()) - params.add("-o") - params.add(outputDir.toString()) - - if (headersToRemove.isNotEmpty()) { - params.add("-ignoreheaders") - params.add(headersToRemove.joinToString(",")) - } - - // Running the Codegen Main here - main(params.toTypedArray()) - - // Copy over the extra files. - val source = extraFiles.orNull?.asFile - source?.copyRecursively(outputDir, overwrite = true) + """.trimIndent() + ) + + val params = mutableListOf() + params.add("-p") + params.add(platform) + params.add("-s") + params.add(specName) + params.add("-v") + params.add(specVersion) + params.add("-g") + params.add(packageName.substringBeforeLast('.')) + params.add("-a") + params.add(packageName.substringAfterLast('.')) + params.add("-i") + params.add(inputFile.toString()) + params.add("-o") + params.add(outputDir.toString()) + + if (headersToRemove.isNotEmpty()) { + params.add("-ignoreheaders") + params.add(headersToRemove.joinToString(",")) } + + // Running the Codegen Main here + main(params.toTypedArray()) + + // Copy over the extra files. + val source = extraFiles.orNull?.asFile + source?.copyRecursively(outputDir, overwrite = true) + } } diff --git a/gradle-plugin/plugin/src/main/java/com/yelp/codegen/plugin/GenerateTaskConfiguration.kt b/gradle-plugin/plugin/src/main/java/com/yelp/codegen/plugin/GenerateTaskConfiguration.kt index 0dd0bfa0..09af8711 100644 --- a/gradle-plugin/plugin/src/main/java/com/yelp/codegen/plugin/GenerateTaskConfiguration.kt +++ b/gradle-plugin/plugin/src/main/java/com/yelp/codegen/plugin/GenerateTaskConfiguration.kt @@ -6,21 +6,21 @@ import org.gradle.api.file.RegularFileProperty import javax.inject.Inject abstract class GenerateTaskConfiguration @Inject constructor(project: Project) { - val objects = project.objects + val objects = project.objects - val platform = objects.property(String::class.java).convention("kotlin") - val packageName = objects.property(String::class.java).convention("com.codegen.default") - val specName = objects.property(String::class.java).convention("defaultname") - abstract val inputFile: RegularFileProperty - val specVersion = objects.property(String::class.java).convention( - project.provider { - readVersionFromSpecfile(inputFile.get().asFile) - } - ) - val outputDir = objects.directoryProperty().convention(project.layout.buildDirectory.dir("gen").get()) + val platform = objects.property(String::class.java).convention("kotlin") + val packageName = objects.property(String::class.java).convention("com.codegen.default") + val specName = objects.property(String::class.java).convention("defaultname") + abstract val inputFile: RegularFileProperty + val specVersion = objects.property(String::class.java).convention( + project.provider { + readVersionFromSpecfile(inputFile.get().asFile) + } + ) + val outputDir = objects.directoryProperty().convention(project.layout.buildDirectory.dir("gen").get()) - val extraFiles = objects.directoryProperty() - val features: FeatureConfiguration = FeatureConfiguration(objects) + val extraFiles = objects.directoryProperty() + val features: FeatureConfiguration = FeatureConfiguration(objects) - fun features(action: Action) = action.execute(features) + fun features(action: Action) = action.execute(features) } diff --git a/gradle-plugin/plugin/src/main/java/com/yelp/codegen/plugin/VersionHelper.kt b/gradle-plugin/plugin/src/main/java/com/yelp/codegen/plugin/VersionHelper.kt index a097295a..d19bb7e6 100644 --- a/gradle-plugin/plugin/src/main/java/com/yelp/codegen/plugin/VersionHelper.kt +++ b/gradle-plugin/plugin/src/main/java/com/yelp/codegen/plugin/VersionHelper.kt @@ -4,17 +4,17 @@ import io.swagger.parser.SwaggerParser import java.io.File fun readVersionFromSpecfile(specFile: File): String { - val swaggerSpec = SwaggerParser().readWithInfo(specFile.absolutePath, listOf(), false).swagger + val swaggerSpec = SwaggerParser().readWithInfo(specFile.absolutePath, listOf(), false).swagger - return when (val version = swaggerSpec.info.version) { - is String -> { - println("Successfully read version from Swagger Spec file: $version") - version - } - else -> { - val defaultVersion = "0.0.0" - println("Issue in reading version from Swagger Spec file. Falling back to $defaultVersion") - defaultVersion - } + return when (val version = swaggerSpec.info.version) { + is String -> { + println("Successfully read version from Swagger Spec file: $version") + version } + else -> { + val defaultVersion = "0.0.0" + println("Issue in reading version from Swagger Spec file. Falling back to $defaultVersion") + defaultVersion + } + } } diff --git a/gradle-plugin/plugin/src/main/java/com/yelp/codegen/utils/KotlinLangUtils.kt b/gradle-plugin/plugin/src/main/java/com/yelp/codegen/utils/KotlinLangUtils.kt index d1d5b1de..691577d0 100644 --- a/gradle-plugin/plugin/src/main/java/com/yelp/codegen/utils/KotlinLangUtils.kt +++ b/gradle-plugin/plugin/src/main/java/com/yelp/codegen/utils/KotlinLangUtils.kt @@ -4,150 +4,150 @@ import io.swagger.codegen.DefaultCodegen object KotlinLangUtils { - internal val kotlinLanguageSpecificPrimitives = setOf( - "kotlin.Byte", - "kotlin.Short", - "kotlin.Int", - "kotlin.Long", - "kotlin.Float", - "kotlin.Double", - "kotlin.Boolean", - "kotlin.Char", - "kotlin.String", - "kotlin.Array", - "kotlin.collections.List", - "kotlin.collections.Map", - "kotlin.collections.Set" - ) + internal val kotlinLanguageSpecificPrimitives = setOf( + "kotlin.Byte", + "kotlin.Short", + "kotlin.Int", + "kotlin.Long", + "kotlin.Float", + "kotlin.Double", + "kotlin.Boolean", + "kotlin.Char", + "kotlin.String", + "kotlin.Array", + "kotlin.collections.List", + "kotlin.collections.Map", + "kotlin.collections.Set" + ) - // This includes hard reserved words defined by + // This includes hard reserved words defined by // https://github.com/JetBrains/kotlin/blob/2593ce73f17f63108392e0d8217bf4ecc1606b96/core/descriptors/src/org/jetbrains/kotlin/renderer/KeywordStringsGenerated.java // as well as keywords from https://kotlinlang.org/docs/reference/keyword-reference.html - internal val kotlinReservedWords = setOf( - "abstract", - "annotation", - "as", - "break", - "case", - "catch", - "class", - "companion", - "const", - "constructor", - "continue", - "crossinline", - "data", - "delegate", - "do", - "else", - "enum", - "external", - "false", - "final", - "finally", - "for", - "fun", - "if", - "in", - "infix", - "init", - "inline", - "inner", - "interface", - "internal", - "is", - "it", - "lateinit", - "lazy", - "noinline", - "null", - "object", - "open", - "operator", - "out", - "override", - "package", - "private", - "protected", - "public", - "reified", - "return", - "sealed", - "super", - "suspend", - "tailrec", - "this", - "throw", - "true", - "try", - "typealias", - "typeof", - "val", - "var", - "vararg", - "when", - "while" - ) + internal val kotlinReservedWords = setOf( + "abstract", + "annotation", + "as", + "break", + "case", + "catch", + "class", + "companion", + "const", + "constructor", + "continue", + "crossinline", + "data", + "delegate", + "do", + "else", + "enum", + "external", + "false", + "final", + "finally", + "for", + "fun", + "if", + "in", + "infix", + "init", + "inline", + "inner", + "interface", + "internal", + "is", + "it", + "lateinit", + "lazy", + "noinline", + "null", + "object", + "open", + "operator", + "out", + "override", + "package", + "private", + "protected", + "public", + "reified", + "return", + "sealed", + "super", + "suspend", + "tailrec", + "this", + "throw", + "true", + "try", + "typealias", + "typeof", + "val", + "var", + "vararg", + "when", + "while" + ) - internal val kotlinDefaultIncludes = setOf( - "kotlin.Byte", - "kotlin.Short", - "kotlin.Int", - "kotlin.Long", - "kotlin.Float", - "kotlin.Double", - "kotlin.Boolean", - "kotlin.Char", - "kotlin.Array", - "kotlin.String", - "kotlin.collections.List", - "kotlin.collections.Set", - "kotlin.collections.Map" - ) + internal val kotlinDefaultIncludes = setOf( + "kotlin.Byte", + "kotlin.Short", + "kotlin.Int", + "kotlin.Long", + "kotlin.Float", + "kotlin.Double", + "kotlin.Boolean", + "kotlin.Char", + "kotlin.Array", + "kotlin.String", + "kotlin.collections.List", + "kotlin.collections.Set", + "kotlin.collections.Map" + ) - internal val kotlinTypeMapping = mapOf( - "string" to "String", - "boolean" to "Boolean", - "integer" to "Int", - "float" to "Float", - "long" to "Long", - "double" to "Double", - "number" to "BigDecimal", - "date" to "LocalDate", - "DateTime" to "ZonedDateTime", - "date-time" to "ZonedDateTime", - "file" to "File", - "array" to "List", - "list" to "List", - "map" to "Map", - "object" to "Map", - "binary" to "List" - ) + internal val kotlinTypeMapping = mapOf( + "string" to "String", + "boolean" to "Boolean", + "integer" to "Int", + "float" to "Float", + "long" to "Long", + "double" to "Double", + "number" to "BigDecimal", + "date" to "LocalDate", + "DateTime" to "ZonedDateTime", + "date-time" to "ZonedDateTime", + "file" to "File", + "array" to "List", + "list" to "List", + "map" to "Map", + "object" to "Map", + "binary" to "List" + ) - internal val kotlinInstantiationTypes = mapOf( - "array" to "listOf", - "list" to "listOf", - "map" to "mapOf" - ) + internal val kotlinInstantiationTypes = mapOf( + "array" to "listOf", + "list" to "listOf", + "map" to "mapOf" + ) - internal val kotlinImportMapping = mapOf( - "Boolean" to "kotlin.Boolean", - "String" to "kotlin.String", - "Int" to "kotlin.Int", - "Float" to "kotlin.Float", - "Long" to "kotlin.Long", - "Double" to "kotlin.Double", - "BigDecimal" to "java.math.BigDecimal", - "LocalDate" to "org.threeten.bp.LocalDate", - "ZonedDateTime" to "org.threeten.bp.ZonedDateTime", - "File" to "java.io.File", - "List" to "kotlin.collections.List", - "List" to "kotlin.collections.List", - "Map" to "kotlin.collections.Map", - "Map" to "kotlin.collections.Map", - "Timestamp" to "java.sql.Timestamp", - "UUID" to "java.util.UUID" - ) + internal val kotlinImportMapping = mapOf( + "Boolean" to "kotlin.Boolean", + "String" to "kotlin.String", + "Int" to "kotlin.Int", + "Float" to "kotlin.Float", + "Long" to "kotlin.Long", + "Double" to "kotlin.Double", + "BigDecimal" to "java.math.BigDecimal", + "LocalDate" to "org.threeten.bp.LocalDate", + "ZonedDateTime" to "org.threeten.bp.ZonedDateTime", + "File" to "java.io.File", + "List" to "kotlin.collections.List", + "List" to "kotlin.collections.List", + "Map" to "kotlin.collections.Map", + "Map" to "kotlin.collections.Map", + "Timestamp" to "java.sql.Timestamp", + "UUID" to "java.util.UUID" + ) } /** @@ -158,21 +158,21 @@ object KotlinLangUtils { * @return sanitized string */ internal fun String.sanitizeKotlinSpecificNames(replacements: Map): String { - var word = this - for ((key, value) in replacements) { - word = word.replace("\\Q$key\\E".toRegex(), value) - } + var word = this + for ((key, value) in replacements) { + word = word.replace("\\Q$key\\E".toRegex(), value) + } - // Fallback, replace unknowns with underscore. - word = word.replace("\\W+".toRegex(), "_") - if (word.matches("\\d.*".toRegex())) { - word = "_$word" - } + // Fallback, replace unknowns with underscore. + word = word.replace("\\W+".toRegex(), "_") + if (word.matches("\\d.*".toRegex())) { + word = "_$word" + } - // _, __, and ___ are reserved in Kotlin. Treat all names with only underscores consistently, regardless of count. - if (word.matches("^_+$".toRegex())) { - word = word.replace("\\Q_\\E".toRegex(), "Underscore") - } + // _, __, and ___ are reserved in Kotlin. Treat all names with only underscores consistently, regardless of count. + if (word.matches("^_+$".toRegex())) { + word = word.replace("\\Q_\\E".toRegex(), "Underscore") + } - return word + return word } diff --git a/gradle-plugin/plugin/src/main/java/com/yelp/codegen/utils/StringUtils.kt b/gradle-plugin/plugin/src/main/java/com/yelp/codegen/utils/StringUtils.kt index 70b2a439..da340d52 100644 --- a/gradle-plugin/plugin/src/main/java/com/yelp/codegen/utils/StringUtils.kt +++ b/gradle-plugin/plugin/src/main/java/com/yelp/codegen/utils/StringUtils.kt @@ -5,23 +5,23 @@ private const val ANSI_RED = "\u001B[31m" private const val ANSI_RESET = "\u001B[0m" fun String.toCamelCase(): String { - val split = this.split(Regex("[ _]")).map { it.split(Regex("(?=\\p{Upper})")) }.flatten() - return split.map { it.toLowerCase() }.mapIndexed { index, subString -> - if (index == 0) { - subString - } else { - subString.capitalize() - } - }.joinToString("") + val split = this.split(Regex("[ _]")).map { it.split(Regex("(?=\\p{Upper})")) }.flatten() + return split.map { it.toLowerCase() }.mapIndexed { index, subString -> + if (index == 0) { + subString + } else { + subString.capitalize() + } + }.joinToString("") } fun String.toPascalCase(): String { - return this.toCamelCase().capitalize() + return this.toCamelCase().capitalize() } fun String.safeSuffix(suffix: String) = - if (!this.endsWith(suffix)) "$this$suffix" else this + if (!this.endsWith(suffix)) "$this$suffix" else this fun String.red(): String { - return "$ANSI_RED${this}$ANSI_RESET" + return "$ANSI_RED${this}$ANSI_RESET" } diff --git a/gradle-plugin/plugin/src/main/resources/kotlin/data_class.mustache b/gradle-plugin/plugin/src/main/resources/kotlin/data_class.mustache index 8ef6fba5..a192984f 100644 --- a/gradle-plugin/plugin/src/main/resources/kotlin/data_class.mustache +++ b/gradle-plugin/plugin/src/main/resources/kotlin/data_class.mustache @@ -4,7 +4,7 @@ * @property {{{name}}}{{#description}} {{description}}{{/description}} {{/vars}} */ -@JsonClass(generateAdapter = true) +@Serializable {{#hasVars}}data {{/hasVars}}class {{classname}}{{#hasVars}}( {{#requiredVars}} {{>data_class_req_var}}{{^-last}}, @@ -18,7 +18,7 @@ * {{{description}}}{{/description}} * Values:{{#allowableValues}} {{#enumVars}}{{&name}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}} */ - @JsonClass(generateAdapter = false) + @Serializable enum class {{enumName}}(val value: {{complexType}}) { -{{#allowableValues}}{{#enumVars}} @Json(name = {{{value}}}) {{&name}}({{{value}}}){{^-last}},{{/-last}}{{{newline}}}{{/enumVars}}{{/allowableValues}} } +{{#allowableValues}}{{#enumVars}} {{&name}}({{{value}}}){{^-last}},{{/-last}}{{{newline}}}{{/enumVars}}{{/allowableValues}} } {{/isEnum}}{{/vars}}}{{/hasEnums}}{{/hasVars}} \ No newline at end of file diff --git a/gradle-plugin/plugin/src/main/resources/kotlin/data_class_opt_var.mustache b/gradle-plugin/plugin/src/main/resources/kotlin/data_class_opt_var.mustache index 2e2566e2..7e17adf1 100644 --- a/gradle-plugin/plugin/src/main/resources/kotlin/data_class_opt_var.mustache +++ b/gradle-plugin/plugin/src/main/resources/kotlin/data_class_opt_var.mustache @@ -1 +1 @@ - @Json(name = "{{{baseName}}}") @field:Json(name = "{{{baseName}}}") {{#vendorExtensions.x-nullable}}@XNullable {{/vendorExtensions.x-nullable}}var {{{name}}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}} = {{#defaultvalue}}{{defaultvalue}}{{/defaultvalue}}{{^defaultvalue}}null{{/defaultvalue}} \ No newline at end of file + @SerialName("{{{baseName}}}") {{#vendorExtensions.x-nullable}}@XNullable {{/vendorExtensions.x-nullable}}var {{{name}}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}} = {{#defaultvalue}}{{defaultvalue}}{{/defaultvalue}}{{^defaultvalue}}null{{/defaultvalue}} diff --git a/gradle-plugin/plugin/src/main/resources/kotlin/data_class_req_var.mustache b/gradle-plugin/plugin/src/main/resources/kotlin/data_class_req_var.mustache index 362c506a..87abfec8 100644 --- a/gradle-plugin/plugin/src/main/resources/kotlin/data_class_req_var.mustache +++ b/gradle-plugin/plugin/src/main/resources/kotlin/data_class_req_var.mustache @@ -1 +1 @@ - @Json(name = "{{{baseName}}}") @field:Json(name = "{{{baseName}}}") var {{{name}}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}} \ No newline at end of file + @SerialName("{{{baseName}}}") var {{{name}}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}} diff --git a/gradle-plugin/plugin/src/main/resources/kotlin/enum_class.mustache b/gradle-plugin/plugin/src/main/resources/kotlin/enum_class.mustache index 845b13f8..55d47abb 100644 --- a/gradle-plugin/plugin/src/main/resources/kotlin/enum_class.mustache +++ b/gradle-plugin/plugin/src/main/resources/kotlin/enum_class.mustache @@ -2,6 +2,6 @@ * {{{description}}}{{/description}} * Values: {{#allowableValues}}{{#enumVars}}{{&name}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}} */ -@JsonClass(generateAdapter = false) +@Serializable enum class {{classname}}(val value: {{dataType}}) { -{{#allowableValues}}{{#enumVars}} @Json(name = {{{value}}}) {{&name}}({{{value}}}){{^-last}},{{/-last}}{{{newline}}}{{/enumVars}}{{/allowableValues}}} \ No newline at end of file +{{#allowableValues}}{{#enumVars}} @SerialName({{{value}}}) {{&name}}({{{value}}}){{^-last}},{{/-last}}{{{newline}}}{{/enumVars}}{{/allowableValues}}} diff --git a/gradle-plugin/plugin/src/main/resources/kotlin/file_header.mustache b/gradle-plugin/plugin/src/main/resources/kotlin/file_header.mustache index 13c90449..2c59c535 100644 --- a/gradle-plugin/plugin/src/main/resources/kotlin/file_header.mustache +++ b/gradle-plugin/plugin/src/main/resources/kotlin/file_header.mustache @@ -1,5 +1,5 @@ /** * NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: {{{appName}}} - * + * API Version: {{{version}}} * More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen */ diff --git a/gradle-plugin/plugin/src/test/java/com/yelp/codegen/KotlinGeneratorTest.kt b/gradle-plugin/plugin/src/test/java/com/yelp/codegen/KotlinGeneratorTest.kt index 9dcb51a3..9f7183a3 100644 --- a/gradle-plugin/plugin/src/test/java/com/yelp/codegen/KotlinGeneratorTest.kt +++ b/gradle-plugin/plugin/src/test/java/com/yelp/codegen/KotlinGeneratorTest.kt @@ -16,455 +16,455 @@ import java.io.File class KotlinGeneratorTest { - @Test - fun propertiesAreCorrect() { - val generator = KotlinGenerator() - generator.additionalProperties()[GROUP_ID] = "com.yelp" - generator.additionalProperties()[ARTIFACT_ID] = "test" - - assertEquals("android", generator.platform) - assertEquals("kotlin", generator.name) - assertEquals("Generates code for a Kotlin Android client.", generator.help) - assertEquals("com.yelp.test.models", generator.modelPackage()) - assertEquals("com.yelp.test.apis", generator.apiPackage()) - } - - @Test - fun escapeUnsafeCharacters_withNothingToEscape() { - assertEquals("Nothing", KotlinGenerator().escapeUnsafeCharacters("Nothing")) - } - - @Test - fun escapeUnsafeCharacters_withAComment() { - assertEquals("/_* A risky string *_/", KotlinGenerator().escapeUnsafeCharacters("/* A risky string */")) - } - - @Test - fun addRequiredImports_withModelwithVars() { - val model = CodegenModel() - val property = CodegenProperty() - property.vendorExtensions = mutableMapOf() - model.allVars.add(property) - - KotlinGenerator().addRequiredImports(model) - - assertTrue(model.imports.contains("com.squareup.moshi.Json")) - assertTrue(model.imports.contains("com.squareup.moshi.JsonClass")) - assertFalse(model.imports.contains("com.yelp.test.tools.XNullable")) - } - - @Test - fun addRequiredImports_withEnum() { - val model = CodegenModel() - model.isEnum = true - - KotlinGenerator().addRequiredImports(model) - - assertTrue(model.imports.contains("com.squareup.moshi.Json")) - assertTrue(model.imports.contains("com.squareup.moshi.JsonClass")) - assertFalse(model.imports.contains("com.yelp.test.tools.XNullable")) - } - - @Test - fun addRequiredImports_withAlias() { - val model = CodegenModel() - model.isAlias = true - - KotlinGenerator().addRequiredImports(model) - - assertFalse(model.imports.contains("com.squareup.moshi.Json")) - assertFalse(model.imports.contains("com.squareup.moshi.JsonClass")) - assertFalse(model.imports.contains("com.yelp.test.tools.XNullable")) - } - - @Test - fun addRequiredImports_withXNullable() { - val generator = KotlinGenerator() - generator.additionalProperties()[GROUP_ID] = "com.yelp" - generator.additionalProperties()[ARTIFACT_ID] = "test" - val model = CodegenModel() - val xNullableProperty = CodegenProperty() - xNullableProperty.vendorExtensions = mutableMapOf() - xNullableProperty.vendorExtensions[X_NULLABLE] = true - model.allVars.add(xNullableProperty) - - generator.addRequiredImports(model) - - assertTrue(model.imports.contains("com.squareup.moshi.Json")) - assertTrue(model.imports.contains("com.squareup.moshi.JsonClass")) - assertTrue(model.imports.contains("com.yelp.test.tools.XNullable")) - } - - @Test - fun postProcessModelProperty() { - val generator = KotlinGenerator() - val model = CodegenModel() - val property = CodegenProperty() - model.classname = "com.yelp.test.models.Model" - property.isEnum = true - property.datatypeWithEnum = null - - generator.postProcessModelProperty(model, property) - - assertNotNull(property.datatypeWithEnum) - } - - @Test - fun isReservedWord_withReservedWord() { - assertTrue(KotlinGenerator().isReservedWord("abstract")) - } - - @Test - fun isReservedWord_withNotReserved() { - assertFalse(KotlinGenerator().isReservedWord("something")) - } - - @Test - fun escapeReservedWord_withReservedWord() { - assertEquals("`abstract`", KotlinGenerator().escapeReservedWord("abstract")) - } - - @Test - fun escapeReservedWord_withNotReserved() { - assertEquals("something", KotlinGenerator().escapeReservedWord("something")) - } - - @Test - fun escapeQuotationMark() { - assertEquals("hello", KotlinGenerator().escapeQuotationMark("\"hello\"")) - } - - @Test - fun modelDocFileFolder() { - val generator = KotlinGenerator() - generator.additionalProperties()[GROUP_ID] = "com.yelp" - generator.additionalProperties()[ARTIFACT_ID] = "test" - assertTrue(generator.modelDocFileFolder().endsWith("docs/")) - } - - @Test - fun modelFileFolder() { - val generator = KotlinGenerator() - generator.additionalProperties()[GROUP_ID] = "com.yelp" - generator.additionalProperties()[ARTIFACT_ID] = "test" - val sep: String = File.separator - assertTrue(generator.modelFileFolder().endsWith("com${sep}yelp${sep}test${sep}models")) - } - - @Test - fun toEnumVarName_withEmptyValue() { - assertEquals("EMPTY", KotlinGenerator().toEnumVarName("", "")) - } - - @Test - fun toEnumVarName_withUnderscore() { - assertEquals("UNDERSCORE", KotlinGenerator().toEnumVarName("_", "")) - } - - @Test - fun toEnumVarName_withAnEnumValue() { - assertEquals("USER", KotlinGenerator().toEnumVarName("user", "")) - } - - @Test - fun toVarName() { - assertEquals("property", KotlinGenerator().toVarName("property")) - } - - @Test - fun toVarName_withUnderscores() { - assertEquals("userProperty", KotlinGenerator().toVarName("user_property")) - } - - @Test - fun toVarName_withReservedKeywork() { - assertEquals("`object`", KotlinGenerator().toVarName("object")) - } - - @Test - fun toModelImport_withFullyQualifiedImport() { - assertEquals("java.util.UUID", KotlinGenerator().toModelImport("java.util.UUID")) - } - - @Test - fun toModelImport_withNotFullyQualifiedImport() { - val generator = KotlinGenerator() - generator.additionalProperties()[GROUP_ID] = "com.yelp" - generator.additionalProperties()[ARTIFACT_ID] = "test" - - assertEquals("com.yelp.test.models.Model", generator.toModelImport("Model")) - } - - @Test - fun addImport_withNullType() { - val model = CodegenModel() - KotlinGenerator().addImport(model, null) - assertTrue(model.imports.isEmpty()) - } - - @Test - fun addImport_withBlankType() { - val model = CodegenModel() - KotlinGenerator().addImport(model, "") - assertTrue(model.imports.isEmpty()) - } - - @Test - fun addImport_withDefaultIncludes() { - val model = CodegenModel() - KotlinGenerator().addImport(model, "kotlin.collections.Map") - KotlinGenerator().addImport(model, "kotlin.collections.Set") - KotlinGenerator().addImport(model, "kotlin.collections.List") - assertTrue(model.imports.isEmpty()) - } - - @Test - fun addImport_withLanguageSpecificPrimitive() { - val model = CodegenModel() - val generator = KotlinGenerator() - generator.languageSpecificPrimitives().clear() - generator.languageSpecificPrimitives().add("kotlin.AnotherType") - generator.addImport(model, "kotlin.AnotherType") - assertTrue(model.imports.isEmpty()) - } - - @Test - fun addImport_withJavaUUID() { - val model = CodegenModel() - KotlinGenerator().addImport(model, "UUID") - assertEquals(1, model.imports.size) - assertTrue(model.imports.contains("UUID")) - } - - @Test - fun toModelName_willCapitalize() { - assertEquals("Model", KotlinGenerator().toModelName("model")) - } - - @Test - fun toModelName_withImportMapping() { - val generator = KotlinGenerator() - generator.importMapping()["threeten"] = "org.threeten.bp.LocalDate" - assertEquals("threeten", generator.toModelName("threeten")) - } - - @Test - fun toModelName_withSpace() { - assertEquals("ModelWithSpace", KotlinGenerator().toModelName("model with space")) - } - - @Test - fun toModelName_withDots() { - assertEquals("ModelWithDotS", KotlinGenerator().toModelName("model with dot.s")) - } - - @Test - fun toModelName_withUnderscores() { - assertEquals("ModelWithUserscoreS", KotlinGenerator().toModelName("model with userscore_s")) - } - - @Test - fun toModelFilename_withSpace() { - assertEquals("ModelWithSpace", KotlinGenerator().toModelFilename("model with space")) - } - - @Test - fun toModelFilename_withDots() { - assertEquals("ModelWithDotS", KotlinGenerator().toModelFilename("model with dot.s")) - } - - @Test - fun toModelFilename_withUnderscores() { - assertEquals("ModelWithUserscoreS", KotlinGenerator().toModelFilename("model with userscore_s")) - } - - @Test - fun toEnumName_willCapitalize() { - val property = CodegenProperty().apply { name = "model" } - assertEquals("ModelEnum", KotlinGenerator().toEnumName(property)) - } - - @Test - fun toEnumName_withSpace() { - val property = CodegenProperty().apply { name = "model with space" } - assertEquals("ModelWithSpaceEnum", KotlinGenerator().toEnumName(property)) - } - - @Test - fun toEnumName_withDots() { - val property = CodegenProperty().apply { name = "model with dot.s" } - assertEquals("ModelWithDotSEnum", KotlinGenerator().toEnumName(property)) - } - - @Test - fun toEnumName_withUnderscores() { - val property = CodegenProperty().apply { name = "model with underscore_s" } - assertEquals("ModelWithUnderscoreSEnum", KotlinGenerator().toEnumName(property)) - } - - @Test - fun removeNonNameElementToCamelCase_withSquareBrackets() { - assertEquals("type", KotlinGenerator().removeNonNameElementToCamelCase("type[]")) - assertEquals("typeValue", KotlinGenerator().removeNonNameElementToCamelCase("type[value]")) - assertEquals("type", KotlinGenerator().removeNonNameElementToCamelCase("type[")) - assertEquals("type", KotlinGenerator().removeNonNameElementToCamelCase("type]")) - assertEquals("type", KotlinGenerator().removeNonNameElementToCamelCase("[type]")) - assertEquals("typeKey", KotlinGenerator().removeNonNameElementToCamelCase("[type]key")) - } - - @Test - fun fromOperation_withBasePath_removeLeadingSlash() { - val generator = KotlinGenerator() - generator.basePath = "/v2" - val operation = Operation() - val swagger = Swagger() - - val codegenOperation = generator.fromOperation("/helloworld", "GET", operation, mutableMapOf(), swagger) - - assertEquals("helloworld", codegenOperation.path) - } - - @Test - fun fromOperation_withNoBasePath_leadingSlashIsNotRemoved() { - val generator = KotlinGenerator() - generator.basePath = null - val operation = Operation() - val swagger = Swagger() - - val codegenOperation = generator.fromOperation("/helloworld", "GET", operation, mutableMapOf(), swagger) - - assertEquals("/helloworld", codegenOperation.path) - } - - @Test - fun preprocessSwagger() { - val generator = KotlinGenerator() - generator.additionalProperties()[SPEC_VERSION] = "42.0.0" - - val swagger = Swagger() - swagger.info = Info() - swagger.info.version = "1.0.0" - swagger.basePath = "/v2" - generator.preprocessSwagger(swagger) - - assertEquals("42.0.0", swagger.info.version) - assertEquals("/v2", generator.basePath) - } - - @Test - fun processTopLevelHeaders_withNoHeaders_hasOperationHeadersIsFalse() { - val generator = KotlinGenerator() - val operation = CodegenOperation() - operation.vendorExtensions = mutableMapOf() - - generator.processTopLevelHeaders(operation) - - assertEquals(false, operation.vendorExtensions["hasOperationHeaders"]) - } - - @Test - fun processTopLevelHeaders_withOperationId_hasXOperationIdHeader() { - val testOperationId = "aTestOperationId" - val generator = KotlinGenerator() - val operation = CodegenOperation() - operation.vendorExtensions = mutableMapOf(X_OPERATION_ID to (testOperationId as Any)) - - generator.processTopLevelHeaders(operation) - - assertEquals(true, operation.vendorExtensions["hasOperationHeaders"]) - val headerMap = operation.vendorExtensions["operationHeaders"] as List<*> - assertEquals(1, headerMap.size) - val firstPair = headerMap[0] as Pair<*, *> - assertEquals(HEADER_X_OPERATION_ID, firstPair.first as String) - assertEquals(testOperationId, firstPair.second as String) - } - - @Test - fun processTopLevelHeaders_withOperationIdAndHeadersToIgnore_hasNoHeaders() { - val testOperationId = "aTestOperationId" - val generator = KotlinGenerator() - val operation = CodegenOperation() - generator.additionalProperties()[HEADERS_TO_IGNORE] = HEADER_X_OPERATION_ID - operation.vendorExtensions = mutableMapOf(X_OPERATION_ID to (testOperationId as Any)) - - generator.processTopLevelHeaders(operation) - - assertEquals(false, operation.vendorExtensions["hasOperationHeaders"]) - val headerMap = operation.vendorExtensions["operationHeaders"] as List<*> - assertEquals(0, headerMap.size) - } - - @Test - fun processTopLevelHeaders_withConsumes_hasContentTypeHeader() { - val generator = KotlinGenerator() - val operation = CodegenOperation() - operation.vendorExtensions = mutableMapOf() - operation.consumes = listOf( - mapOf("mediaType" to "application/json") - ) - - generator.processTopLevelHeaders(operation) - - assertEquals(true, operation.vendorExtensions["hasOperationHeaders"]) - val headerMap = operation.vendorExtensions["operationHeaders"] as List<*> - assertEquals(1, headerMap.size) - val firstPair = headerMap[0] as Pair<*, *> - assertEquals(HEADER_CONTENT_TYPE, firstPair.first as String) - assertEquals("application/json", firstPair.second as String) - } - - @Test - fun processTopLevelHeaders_withConsumesAndHeadersToIgnore_hasNoContentTypeHeader() { - val generator = KotlinGenerator() - val operation = CodegenOperation() - generator.additionalProperties()[HEADERS_TO_IGNORE] = HEADER_CONTENT_TYPE - operation.vendorExtensions = mutableMapOf() - operation.consumes = listOf( - mapOf("mediaType" to "application/json") - ) - - generator.processTopLevelHeaders(operation) - - assertEquals(false, operation.vendorExtensions["hasOperationHeaders"]) - val headerMap = operation.vendorExtensions["operationHeaders"] as List<*> - assertEquals(0, headerMap.size) - } - - @Test - fun processTopLevelHeaders_withFormParams_hasNoContentTypeHeader() { - val generator = KotlinGenerator() - val operation = CodegenOperation() - operation.vendorExtensions = mutableMapOf() - operation.formParams = listOf(CodegenParameter()) - operation.consumes = listOf( - mapOf("mediaType" to "application/json") - ) - - generator.processTopLevelHeaders(operation) - - assertEquals(false, operation.vendorExtensions["hasOperationHeaders"]) - } - - @Test - fun processTopLevelHeaders_withConsumesAndOperationId_hasTwoHeaders() { - val testOperationId = "aTestOperationId" - val generator = KotlinGenerator() - val operation = CodegenOperation() - operation.vendorExtensions = mutableMapOf(X_OPERATION_ID to (testOperationId as Any)) - operation.consumes = listOf( - mapOf("mediaType" to "application/json") - ) - - generator.processTopLevelHeaders(operation) - - assertEquals(true, operation.vendorExtensions["hasOperationHeaders"]) - val headerMap = operation.vendorExtensions["operationHeaders"] as List<*> - assertEquals(2, headerMap.size) - val firstPair = headerMap[0] as Pair<*, *> - assertEquals(HEADER_X_OPERATION_ID, firstPair.first as String) - assertEquals(testOperationId, firstPair.second as String) - val secondPair = headerMap[1] as Pair<*, *> - assertEquals(HEADER_CONTENT_TYPE, secondPair.first as String) - assertEquals("application/json", secondPair.second as String) - } + @Test + fun propertiesAreCorrect() { + val generator = KotlinGenerator() + generator.additionalProperties()[GROUP_ID] = "com.yelp" + generator.additionalProperties()[ARTIFACT_ID] = "test" + + assertEquals("android", generator.platform) + assertEquals("kotlin", generator.name) + assertEquals("Generates code for a Kotlin Android client.", generator.help) + assertEquals("com.yelp.test.models", generator.modelPackage()) + assertEquals("com.yelp.test.apis", generator.apiPackage()) + } + + @Test + fun escapeUnsafeCharacters_withNothingToEscape() { + assertEquals("Nothing", KotlinGenerator().escapeUnsafeCharacters("Nothing")) + } + + @Test + fun escapeUnsafeCharacters_withAComment() { + assertEquals("/_* A risky string *_/", KotlinGenerator().escapeUnsafeCharacters("/* A risky string */")) + } + + @Test + fun addRequiredImports_withModelwithVars() { + val model = CodegenModel() + val property = CodegenProperty() + property.vendorExtensions = mutableMapOf() + model.allVars.add(property) + + KotlinGenerator().addRequiredImports(model) + + assertTrue(model.imports.contains("kotlinx.serialization.Serializable")) + assertTrue(model.imports.contains("kotlinx.serialization.SerialName")) + assertFalse(model.imports.contains("com.yelp.test.tools.XNullable")) + } + + @Test + fun addRequiredImports_withEnum() { + val model = CodegenModel() + model.isEnum = true + + KotlinGenerator().addRequiredImports(model) + + assertTrue(model.imports.contains("kotlinx.serialization.Serializable")) + assertTrue(model.imports.contains("kotlinx.serialization.SerialName")) + assertFalse(model.imports.contains("com.yelp.test.tools.XNullable")) + } + + @Test + fun addRequiredImports_withAlias() { + val model = CodegenModel() + model.isAlias = true + + KotlinGenerator().addRequiredImports(model) + + assertFalse(model.imports.contains("kotlinx.serialization.Serializable")) + assertFalse(model.imports.contains("kotlinx.serialization.SerialName")) + assertFalse(model.imports.contains("com.yelp.test.tools.XNullable")) + } + + @Test + fun addRequiredImports_withXNullable() { + val generator = KotlinGenerator() + generator.additionalProperties()[GROUP_ID] = "com.yelp" + generator.additionalProperties()[ARTIFACT_ID] = "test" + val model = CodegenModel() + val xNullableProperty = CodegenProperty() + xNullableProperty.vendorExtensions = mutableMapOf() + xNullableProperty.vendorExtensions[X_NULLABLE] = true + model.allVars.add(xNullableProperty) + + generator.addRequiredImports(model) + + assertTrue(model.imports.contains("kotlinx.serialization.Serializable")) + assertTrue(model.imports.contains("kotlinx.serialization.SerialName")) + assertTrue(model.imports.contains("com.yelp.test.tools.XNullable")) + } + + @Test + fun postProcessModelProperty() { + val generator = KotlinGenerator() + val model = CodegenModel() + val property = CodegenProperty() + model.classname = "com.yelp.test.models.Model" + property.isEnum = true + property.datatypeWithEnum = null + + generator.postProcessModelProperty(model, property) + + assertNotNull(property.datatypeWithEnum) + } + + @Test + fun isReservedWord_withReservedWord() { + assertTrue(KotlinGenerator().isReservedWord("abstract")) + } + + @Test + fun isReservedWord_withNotReserved() { + assertFalse(KotlinGenerator().isReservedWord("something")) + } + + @Test + fun escapeReservedWord_withReservedWord() { + assertEquals("`abstract`", KotlinGenerator().escapeReservedWord("abstract")) + } + + @Test + fun escapeReservedWord_withNotReserved() { + assertEquals("something", KotlinGenerator().escapeReservedWord("something")) + } + + @Test + fun escapeQuotationMark() { + assertEquals("hello", KotlinGenerator().escapeQuotationMark("\"hello\"")) + } + + @Test + fun modelDocFileFolder() { + val generator = KotlinGenerator() + generator.additionalProperties()[GROUP_ID] = "com.yelp" + generator.additionalProperties()[ARTIFACT_ID] = "test" + assertTrue(generator.modelDocFileFolder().endsWith("docs/")) + } + + @Test + fun modelFileFolder() { + val generator = KotlinGenerator() + generator.additionalProperties()[GROUP_ID] = "com.yelp" + generator.additionalProperties()[ARTIFACT_ID] = "test" + val sep: String = File.separator + assertTrue(generator.modelFileFolder().endsWith("com${sep}yelp${sep}test${sep}models")) + } + + @Test + fun toEnumVarName_withEmptyValue() { + assertEquals("EMPTY", KotlinGenerator().toEnumVarName("", "")) + } + + @Test + fun toEnumVarName_withUnderscore() { + assertEquals("UNDERSCORE", KotlinGenerator().toEnumVarName("_", "")) + } + + @Test + fun toEnumVarName_withAnEnumValue() { + assertEquals("USER", KotlinGenerator().toEnumVarName("user", "")) + } + + @Test + fun toVarName() { + assertEquals("property", KotlinGenerator().toVarName("property")) + } + + @Test + fun toVarName_withUnderscores() { + assertEquals("userProperty", KotlinGenerator().toVarName("user_property")) + } + + @Test + fun toVarName_withReservedKeywork() { + assertEquals("`object`", KotlinGenerator().toVarName("object")) + } + + @Test + fun toModelImport_withFullyQualifiedImport() { + assertEquals("java.util.UUID", KotlinGenerator().toModelImport("java.util.UUID")) + } + + @Test + fun toModelImport_withNotFullyQualifiedImport() { + val generator = KotlinGenerator() + generator.additionalProperties()[GROUP_ID] = "com.yelp" + generator.additionalProperties()[ARTIFACT_ID] = "test" + + assertEquals("com.yelp.test.models.Model", generator.toModelImport("Model")) + } + + @Test + fun addImport_withNullType() { + val model = CodegenModel() + KotlinGenerator().addImport(model, null) + assertTrue(model.imports.isEmpty()) + } + + @Test + fun addImport_withBlankType() { + val model = CodegenModel() + KotlinGenerator().addImport(model, "") + assertTrue(model.imports.isEmpty()) + } + + @Test + fun addImport_withDefaultIncludes() { + val model = CodegenModel() + KotlinGenerator().addImport(model, "kotlin.collections.Map") + KotlinGenerator().addImport(model, "kotlin.collections.Set") + KotlinGenerator().addImport(model, "kotlin.collections.List") + assertTrue(model.imports.isEmpty()) + } + + @Test + fun addImport_withLanguageSpecificPrimitive() { + val model = CodegenModel() + val generator = KotlinGenerator() + generator.languageSpecificPrimitives().clear() + generator.languageSpecificPrimitives().add("kotlin.AnotherType") + generator.addImport(model, "kotlin.AnotherType") + assertTrue(model.imports.isEmpty()) + } + + @Test + fun addImport_withJavaUUID() { + val model = CodegenModel() + KotlinGenerator().addImport(model, "UUID") + assertEquals(1, model.imports.size) + assertTrue(model.imports.contains("UUID")) + } + + @Test + fun toModelName_willCapitalize() { + assertEquals("Model", KotlinGenerator().toModelName("model")) + } + + @Test + fun toModelName_withImportMapping() { + val generator = KotlinGenerator() + generator.importMapping()["threeten"] = "org.threeten.bp.LocalDate" + assertEquals("threeten", generator.toModelName("threeten")) + } + + @Test + fun toModelName_withSpace() { + assertEquals("ModelWithSpace", KotlinGenerator().toModelName("model with space")) + } + + @Test + fun toModelName_withDots() { + assertEquals("ModelWithDotS", KotlinGenerator().toModelName("model with dot.s")) + } + + @Test + fun toModelName_withUnderscores() { + assertEquals("ModelWithUserscoreS", KotlinGenerator().toModelName("model with userscore_s")) + } + + @Test + fun toModelFilename_withSpace() { + assertEquals("ModelWithSpace", KotlinGenerator().toModelFilename("model with space")) + } + + @Test + fun toModelFilename_withDots() { + assertEquals("ModelWithDotS", KotlinGenerator().toModelFilename("model with dot.s")) + } + + @Test + fun toModelFilename_withUnderscores() { + assertEquals("ModelWithUserscoreS", KotlinGenerator().toModelFilename("model with userscore_s")) + } + + @Test + fun toEnumName_willCapitalize() { + val property = CodegenProperty().apply { name = "model" } + assertEquals("ModelEnum", KotlinGenerator().toEnumName(property)) + } + + @Test + fun toEnumName_withSpace() { + val property = CodegenProperty().apply { name = "model with space" } + assertEquals("ModelWithSpaceEnum", KotlinGenerator().toEnumName(property)) + } + + @Test + fun toEnumName_withDots() { + val property = CodegenProperty().apply { name = "model with dot.s" } + assertEquals("ModelWithDotSEnum", KotlinGenerator().toEnumName(property)) + } + + @Test + fun toEnumName_withUnderscores() { + val property = CodegenProperty().apply { name = "model with underscore_s" } + assertEquals("ModelWithUnderscoreSEnum", KotlinGenerator().toEnumName(property)) + } + + @Test + fun removeNonNameElementToCamelCase_withSquareBrackets() { + assertEquals("type", KotlinGenerator().removeNonNameElementToCamelCase("type[]")) + assertEquals("typeValue", KotlinGenerator().removeNonNameElementToCamelCase("type[value]")) + assertEquals("type", KotlinGenerator().removeNonNameElementToCamelCase("type[")) + assertEquals("type", KotlinGenerator().removeNonNameElementToCamelCase("type]")) + assertEquals("type", KotlinGenerator().removeNonNameElementToCamelCase("[type]")) + assertEquals("typeKey", KotlinGenerator().removeNonNameElementToCamelCase("[type]key")) + } + + @Test + fun fromOperation_withBasePath_removeLeadingSlash() { + val generator = KotlinGenerator() + generator.basePath = "/v2" + val operation = Operation() + val swagger = Swagger() + + val codegenOperation = generator.fromOperation("/helloworld", "GET", operation, mutableMapOf(), swagger) + + assertEquals("helloworld", codegenOperation.path) + } + + @Test + fun fromOperation_withNoBasePath_leadingSlashIsNotRemoved() { + val generator = KotlinGenerator() + generator.basePath = null + val operation = Operation() + val swagger = Swagger() + + val codegenOperation = generator.fromOperation("/helloworld", "GET", operation, mutableMapOf(), swagger) + + assertEquals("/helloworld", codegenOperation.path) + } + + @Test + fun preprocessSwagger() { + val generator = KotlinGenerator() + generator.additionalProperties()[SPEC_VERSION] = "42.0.0" + + val swagger = Swagger() + swagger.info = Info() + swagger.info.version = "1.0.0" + swagger.basePath = "/v2" + generator.preprocessSwagger(swagger) + + assertEquals("42.0.0", swagger.info.version) + assertEquals("/v2", generator.basePath) + } + + @Test + fun processTopLevelHeaders_withNoHeaders_hasOperationHeadersIsFalse() { + val generator = KotlinGenerator() + val operation = CodegenOperation() + operation.vendorExtensions = mutableMapOf() + + generator.processTopLevelHeaders(operation) + + assertEquals(false, operation.vendorExtensions["hasOperationHeaders"]) + } + + @Test + fun processTopLevelHeaders_withOperationId_hasXOperationIdHeader() { + val testOperationId = "aTestOperationId" + val generator = KotlinGenerator() + val operation = CodegenOperation() + operation.vendorExtensions = mutableMapOf(X_OPERATION_ID to (testOperationId as Any)) + + generator.processTopLevelHeaders(operation) + + assertEquals(true, operation.vendorExtensions["hasOperationHeaders"]) + val headerMap = operation.vendorExtensions["operationHeaders"] as List<*> + assertEquals(1, headerMap.size) + val firstPair = headerMap[0] as Pair<*, *> + assertEquals(HEADER_X_OPERATION_ID, firstPair.first as String) + assertEquals(testOperationId, firstPair.second as String) + } + + @Test + fun processTopLevelHeaders_withOperationIdAndHeadersToIgnore_hasNoHeaders() { + val testOperationId = "aTestOperationId" + val generator = KotlinGenerator() + val operation = CodegenOperation() + generator.additionalProperties()[HEADERS_TO_IGNORE] = HEADER_X_OPERATION_ID + operation.vendorExtensions = mutableMapOf(X_OPERATION_ID to (testOperationId as Any)) + + generator.processTopLevelHeaders(operation) + + assertEquals(false, operation.vendorExtensions["hasOperationHeaders"]) + val headerMap = operation.vendorExtensions["operationHeaders"] as List<*> + assertEquals(0, headerMap.size) + } + + @Test + fun processTopLevelHeaders_withConsumes_hasContentTypeHeader() { + val generator = KotlinGenerator() + val operation = CodegenOperation() + operation.vendorExtensions = mutableMapOf() + operation.consumes = listOf( + mapOf("mediaType" to "application/json") + ) + + generator.processTopLevelHeaders(operation) + + assertEquals(true, operation.vendorExtensions["hasOperationHeaders"]) + val headerMap = operation.vendorExtensions["operationHeaders"] as List<*> + assertEquals(1, headerMap.size) + val firstPair = headerMap[0] as Pair<*, *> + assertEquals(HEADER_CONTENT_TYPE, firstPair.first as String) + assertEquals("application/json", firstPair.second as String) + } + + @Test + fun processTopLevelHeaders_withConsumesAndHeadersToIgnore_hasNoContentTypeHeader() { + val generator = KotlinGenerator() + val operation = CodegenOperation() + generator.additionalProperties()[HEADERS_TO_IGNORE] = HEADER_CONTENT_TYPE + operation.vendorExtensions = mutableMapOf() + operation.consumes = listOf( + mapOf("mediaType" to "application/json") + ) + + generator.processTopLevelHeaders(operation) + + assertEquals(false, operation.vendorExtensions["hasOperationHeaders"]) + val headerMap = operation.vendorExtensions["operationHeaders"] as List<*> + assertEquals(0, headerMap.size) + } + + @Test + fun processTopLevelHeaders_withFormParams_hasNoContentTypeHeader() { + val generator = KotlinGenerator() + val operation = CodegenOperation() + operation.vendorExtensions = mutableMapOf() + operation.formParams = listOf(CodegenParameter()) + operation.consumes = listOf( + mapOf("mediaType" to "application/json") + ) + + generator.processTopLevelHeaders(operation) + + assertEquals(false, operation.vendorExtensions["hasOperationHeaders"]) + } + + @Test + fun processTopLevelHeaders_withConsumesAndOperationId_hasTwoHeaders() { + val testOperationId = "aTestOperationId" + val generator = KotlinGenerator() + val operation = CodegenOperation() + operation.vendorExtensions = mutableMapOf(X_OPERATION_ID to (testOperationId as Any)) + operation.consumes = listOf( + mapOf("mediaType" to "application/json") + ) + + generator.processTopLevelHeaders(operation) + + assertEquals(true, operation.vendorExtensions["hasOperationHeaders"]) + val headerMap = operation.vendorExtensions["operationHeaders"] as List<*> + assertEquals(2, headerMap.size) + val firstPair = headerMap[0] as Pair<*, *> + assertEquals(HEADER_X_OPERATION_ID, firstPair.first as String) + assertEquals(testOperationId, firstPair.second as String) + val secondPair = headerMap[1] as Pair<*, *> + assertEquals(HEADER_CONTENT_TYPE, secondPair.first as String) + assertEquals("application/json", secondPair.second as String) + } } diff --git a/gradle-plugin/plugin/src/test/java/com/yelp/codegen/KotlinGenerator_TypeMappersTest.kt b/gradle-plugin/plugin/src/test/java/com/yelp/codegen/KotlinGenerator_TypeMappersTest.kt index ea209be1..1d2dde50 100644 --- a/gradle-plugin/plugin/src/test/java/com/yelp/codegen/KotlinGenerator_TypeMappersTest.kt +++ b/gradle-plugin/plugin/src/test/java/com/yelp/codegen/KotlinGenerator_TypeMappersTest.kt @@ -7,98 +7,98 @@ import org.junit.Test class KotlinGenerator_TypeMappersTest { - @Test - fun listTypeWrapper_withSimpleType() { - assertEquals("List", KotlinGenerator().listTypeWrapper("List", "String")) - } - - @Test - fun listTypeWrapper_withMultipleNesting() { - assertEquals("List>", KotlinGenerator().listTypeWrapper("List", "List")) - } - - @Test - fun listTypeUnwrapper_withSimpleType() { - assertEquals("String", KotlinGenerator().listTypeUnwrapper("String")) - } - - @Test - fun listTypeUnwrapper_withListType() { - assertEquals("String", KotlinGenerator().listTypeUnwrapper("List")) - } - - @Test - fun isListTypeWrapped_withSimpleType() { - assertFalse(KotlinGenerator().isListTypeWrapped("String")) - } - - @Test - fun isListTypeWrapped_withListType() { - assertTrue(KotlinGenerator().isListTypeWrapped("List")) - } - - @Test - fun isListTypeWrapped_withMapType() { - assertFalse(KotlinGenerator().isListTypeWrapped("Map")) - } - - @Test - fun mapTypeWrapper_withSimpleType() { - assertEquals("Map", KotlinGenerator().mapTypeWrapper("Map", "Any")) - } - - @Test - fun mapTypeWrapper_withMultipleNesting() { - assertEquals("HashMap?>", KotlinGenerator().mapTypeWrapper("HashMap", "List?")) - } - - @Test - fun mapTypeUnwrapper_withSimpleType() { - assertEquals("String", KotlinGenerator().mapTypeUnwrapper("String")) - } - - @Test - fun mapTypeUnwrapper_withMapType() { - assertEquals("Int", KotlinGenerator().mapTypeUnwrapper("Map")) - } - - @Test - fun isMapTypeWrapped_withSimpleType() { - assertFalse(KotlinGenerator().isMapTypeWrapped("String")) - } - - @Test - fun isMapTypeWrapped_withListType() { - assertFalse(KotlinGenerator().isMapTypeWrapped("List")) - } - - @Test - fun isMapTypeWrapped_withMapType() { - assertTrue(KotlinGenerator().isMapTypeWrapped("Map")) - } - - @Test - fun nullableTypeWrapper_withSimpleType() { - assertEquals("String?", KotlinGenerator().nullableTypeWrapper("String")) - } - - @Test - fun resolveInnerType_withSimpleType() { - assertEquals("String", KotlinGenerator().resolveInnerType("String")) - } - - @Test - fun resolveInnerType_withListType() { - assertEquals("String", KotlinGenerator().resolveInnerType("List")) - } - - @Test - fun resolveInnerType_withMapType() { - assertEquals("Int", KotlinGenerator().resolveInnerType("Map")) - } - - @Test - fun resolveInnerType_withComplexType() { - assertEquals("Int", KotlinGenerator().resolveInnerType("Map>>>")) - } + @Test + fun listTypeWrapper_withSimpleType() { + assertEquals("List", KotlinGenerator().listTypeWrapper("List", "String")) + } + + @Test + fun listTypeWrapper_withMultipleNesting() { + assertEquals("List>", KotlinGenerator().listTypeWrapper("List", "List")) + } + + @Test + fun listTypeUnwrapper_withSimpleType() { + assertEquals("String", KotlinGenerator().listTypeUnwrapper("String")) + } + + @Test + fun listTypeUnwrapper_withListType() { + assertEquals("String", KotlinGenerator().listTypeUnwrapper("List")) + } + + @Test + fun isListTypeWrapped_withSimpleType() { + assertFalse(KotlinGenerator().isListTypeWrapped("String")) + } + + @Test + fun isListTypeWrapped_withListType() { + assertTrue(KotlinGenerator().isListTypeWrapped("List")) + } + + @Test + fun isListTypeWrapped_withMapType() { + assertFalse(KotlinGenerator().isListTypeWrapped("Map")) + } + + @Test + fun mapTypeWrapper_withSimpleType() { + assertEquals("Map", KotlinGenerator().mapTypeWrapper("Map", "Any")) + } + + @Test + fun mapTypeWrapper_withMultipleNesting() { + assertEquals("HashMap?>", KotlinGenerator().mapTypeWrapper("HashMap", "List?")) + } + + @Test + fun mapTypeUnwrapper_withSimpleType() { + assertEquals("String", KotlinGenerator().mapTypeUnwrapper("String")) + } + + @Test + fun mapTypeUnwrapper_withMapType() { + assertEquals("Int", KotlinGenerator().mapTypeUnwrapper("Map")) + } + + @Test + fun isMapTypeWrapped_withSimpleType() { + assertFalse(KotlinGenerator().isMapTypeWrapped("String")) + } + + @Test + fun isMapTypeWrapped_withListType() { + assertFalse(KotlinGenerator().isMapTypeWrapped("List")) + } + + @Test + fun isMapTypeWrapped_withMapType() { + assertTrue(KotlinGenerator().isMapTypeWrapped("Map")) + } + + @Test + fun nullableTypeWrapper_withSimpleType() { + assertEquals("String?", KotlinGenerator().nullableTypeWrapper("String")) + } + + @Test + fun resolveInnerType_withSimpleType() { + assertEquals("String", KotlinGenerator().resolveInnerType("String")) + } + + @Test + fun resolveInnerType_withListType() { + assertEquals("String", KotlinGenerator().resolveInnerType("List")) + } + + @Test + fun resolveInnerType_withMapType() { + assertEquals("Int", KotlinGenerator().resolveInnerType("Map")) + } + + @Test + fun resolveInnerType_withComplexType() { + assertEquals("Int", KotlinGenerator().resolveInnerType("Map>>>")) + } } diff --git a/gradle-plugin/plugin/src/test/java/com/yelp/codegen/KotlinLangUtilsTest.kt b/gradle-plugin/plugin/src/test/java/com/yelp/codegen/KotlinLangUtilsTest.kt index 36c46cf1..56d6ec68 100644 --- a/gradle-plugin/plugin/src/test/java/com/yelp/codegen/KotlinLangUtilsTest.kt +++ b/gradle-plugin/plugin/src/test/java/com/yelp/codegen/KotlinLangUtilsTest.kt @@ -6,28 +6,28 @@ import org.junit.Test class KotlinLangUtilsTest { - @Test - fun sanitizeKotlinSpecificNames_withReplacementInMap() { - assertEquals("valueSemicolon", "value;".sanitizeKotlinSpecificNames(mapOf(";" to "Semicolon"))) - } + @Test + fun sanitizeKotlinSpecificNames_withReplacementInMap() { + assertEquals("valueSemicolon", "value;".sanitizeKotlinSpecificNames(mapOf(";" to "Semicolon"))) + } - @Test - fun sanitizeKotlinSpecificNames_withDash() { - assertEquals("value_", "value-".sanitizeKotlinSpecificNames(emptyMap())) - } + @Test + fun sanitizeKotlinSpecificNames_withDash() { + assertEquals("value_", "value-".sanitizeKotlinSpecificNames(emptyMap())) + } - @Test - fun sanitizeKotlinSpecificNames_withStartingNumber() { - assertEquals("_42value", "42value".sanitizeKotlinSpecificNames(emptyMap())) - } + @Test + fun sanitizeKotlinSpecificNames_withStartingNumber() { + assertEquals("_42value", "42value".sanitizeKotlinSpecificNames(emptyMap())) + } - @Test - fun sanitizeKotlinSpecificNames_withUnderscore() { - assertEquals("Underscore", "_".sanitizeKotlinSpecificNames(emptyMap())) - } + @Test + fun sanitizeKotlinSpecificNames_withUnderscore() { + assertEquals("Underscore", "_".sanitizeKotlinSpecificNames(emptyMap())) + } - @Test - fun sanitizeKotlinSpecificNames_withMultipleUnderscores() { - assertEquals("UnderscoreUnderscoreUnderscore", "___".sanitizeKotlinSpecificNames(emptyMap())) - } + @Test + fun sanitizeKotlinSpecificNames_withMultipleUnderscores() { + assertEquals("UnderscoreUnderscoreUnderscore", "___".sanitizeKotlinSpecificNames(emptyMap())) + } } diff --git a/gradle-plugin/plugin/src/test/java/com/yelp/codegen/MainTest.kt b/gradle-plugin/plugin/src/test/java/com/yelp/codegen/MainTest.kt index a7c21d45..8a2c2da5 100644 --- a/gradle-plugin/plugin/src/test/java/com/yelp/codegen/MainTest.kt +++ b/gradle-plugin/plugin/src/test/java/com/yelp/codegen/MainTest.kt @@ -5,36 +5,36 @@ import org.junit.rules.TemporaryFolder import java.io.File class MainTest { - @get:Rule - val temporaryFolder = TemporaryFolder() + @get:Rule + val temporaryFolder = TemporaryFolder() - private fun runGenerator(platform: String) { - val junitTestsSpecsPath = File( - // Repo root - File(".").absoluteFile.parentFile.parentFile.parentFile.absolutePath, - "samples${File.separator}junit-tests${File.separator}junit_tests_specs.json" - ).path + private fun runGenerator(platform: String) { + val junitTestsSpecsPath = File( + // Repo root + File(".").absoluteFile.parentFile.parentFile.parentFile.absolutePath, + "samples${File.separator}junit-tests${File.separator}junit_tests_specs.json" + ).path - main( - listOf( - "-p", platform, - "-i", junitTestsSpecsPath, - "-o", temporaryFolder.newFolder("kotlin").absolutePath, - "-s", "junittests", - "-v", "0.0.1", - "-g", "com.yelp.codegen", - "-a", " generatecodesamples" - ).toTypedArray() - ) - } + main( + listOf( + "-p", platform, + "-i", junitTestsSpecsPath, + "-o", temporaryFolder.newFolder("kotlin").absolutePath, + "-s", "junittests", + "-v", "0.0.1", + "-g", "com.yelp.codegen", + "-a", " generatecodesamples" + ).toTypedArray() + ) + } - @Test - fun generateKotlinFromJUnitTestSampleSpecs() { - runGenerator("kotlin") - } + @Test + fun generateKotlinFromJUnitTestSampleSpecs() { + runGenerator("kotlin") + } - @Test - fun generateKotlinCoroutinesFromJUnitTestSampleSpecs() { - runGenerator("kotlin-coroutines") - } + @Test + fun generateKotlinCoroutinesFromJUnitTestSampleSpecs() { + runGenerator("kotlin-coroutines") + } } diff --git a/gradle-plugin/plugin/src/test/java/com/yelp/codegen/StringUtilsTest.kt b/gradle-plugin/plugin/src/test/java/com/yelp/codegen/StringUtilsTest.kt index 5d8a7f56..5b627213 100644 --- a/gradle-plugin/plugin/src/test/java/com/yelp/codegen/StringUtilsTest.kt +++ b/gradle-plugin/plugin/src/test/java/com/yelp/codegen/StringUtilsTest.kt @@ -9,67 +9,67 @@ import org.junit.Test class StringUtilsTest { - @Test - fun toCamelCase_withNoSeparator() { - assertEquals("helloWorld", "helloWorld".toCamelCase()) - } + @Test + fun toCamelCase_withNoSeparator() { + assertEquals("helloWorld", "helloWorld".toCamelCase()) + } - @Test - fun toCamelCase_withUpperCaseString() { - assertEquals("HelloWorld", "HelloWorld".toCamelCase()) - } + @Test + fun toCamelCase_withUpperCaseString() { + assertEquals("HelloWorld", "HelloWorld".toCamelCase()) + } - @Test - fun toCamelCase_withUnderscore() { - assertEquals("helloWorld", "hello_world".toCamelCase()) - assertEquals("followTheWhiteRabbit", "follow_the_white_rabbit".toCamelCase()) - } + @Test + fun toCamelCase_withUnderscore() { + assertEquals("helloWorld", "hello_world".toCamelCase()) + assertEquals("followTheWhiteRabbit", "follow_the_white_rabbit".toCamelCase()) + } - @Test - fun toCamelCase_withSpace() { - assertEquals("helloWorld", "hello world".toCamelCase()) - assertEquals("followTheWhiteRabbit", "follow the white rabbit".toCamelCase()) - } + @Test + fun toCamelCase_withSpace() { + assertEquals("helloWorld", "hello world".toCamelCase()) + assertEquals("followTheWhiteRabbit", "follow the white rabbit".toCamelCase()) + } - @Test - fun toPascalCase_withNoSeparator() { - assertEquals("HelloWorld", "helloWorld".toPascalCase()) - } + @Test + fun toPascalCase_withNoSeparator() { + assertEquals("HelloWorld", "helloWorld".toPascalCase()) + } - @Test - fun toPascalCase_withUpperCaseString() { - assertEquals("HelloWorld", "HelloWorld".toPascalCase()) - } + @Test + fun toPascalCase_withUpperCaseString() { + assertEquals("HelloWorld", "HelloWorld".toPascalCase()) + } - @Test - fun toPascalCase_withUnderscore() { - assertEquals("HelloWorld", "hello_world".toPascalCase()) - assertEquals("FollowTheWhiteRabbit", "follow_the_white_rabbit".toPascalCase()) - } + @Test + fun toPascalCase_withUnderscore() { + assertEquals("HelloWorld", "hello_world".toPascalCase()) + assertEquals("FollowTheWhiteRabbit", "follow_the_white_rabbit".toPascalCase()) + } - @Test - fun toPascalCase_withSpace() { - assertEquals("HelloWorld", "hello world".toPascalCase()) - assertEquals("FollowTheWhiteRabbit", "follow the white rabbit".toPascalCase()) - } + @Test + fun toPascalCase_withSpace() { + assertEquals("HelloWorld", "hello world".toPascalCase()) + assertEquals("FollowTheWhiteRabbit", "follow the white rabbit".toPascalCase()) + } - @Test - fun safeSuffix_addsSuffix() { - assertEquals("String?", "String".safeSuffix("?")) - } + @Test + fun safeSuffix_addsSuffix() { + assertEquals("String?", "String".safeSuffix("?")) + } - @Test - fun safeSuffix_withSuffixAlreadyPresent_doesNotAddSuffix() { - assertEquals("String?", "String?".safeSuffix("?")) - } + @Test + fun safeSuffix_withSuffixAlreadyPresent_doesNotAddSuffix() { + assertEquals("String?", "String?".safeSuffix("?")) + } - @Test - fun red() { - assertEquals("\u001B[31mHelloWorld\u001B[0m", "HelloWorld".red()) - } + @Test + fun red() { + assertEquals("\u001B[31mHelloWorld\u001B[0m", "HelloWorld".red()) + } - @Test - fun red_withEmptyString() { - assertEquals("\u001B[31m\u001B[0m", "".red()) - } + @Test + fun red_withEmptyString() { + assertEquals("\u001B[31m\u001B[0m", "".red()) + } } diff --git a/gradle-plugin/plugin/src/test/java/com/yelp/plugin/PluginTests.kt b/gradle-plugin/plugin/src/test/java/com/yelp/plugin/PluginTests.kt index 4140ee49..83d94a23 100644 --- a/gradle-plugin/plugin/src/test/java/com/yelp/plugin/PluginTests.kt +++ b/gradle-plugin/plugin/src/test/java/com/yelp/plugin/PluginTests.kt @@ -9,43 +9,43 @@ import org.junit.rules.TemporaryFolder import java.io.File class PluginTests { - @get:Rule - val temporaryFolder = TemporaryFolder(File(".")) - - @Test - fun basicPluginTest() { - val projectDir = temporaryFolder.newFolder("project") - File("src/test/testProject").copyRecursively(projectDir) - - val result = GradleRunner.create().withProjectDir(projectDir) - .forwardStdOutput(System.out.writer()) - .forwardStdError(System.err.writer()) - .withArguments("generateSwagger") - .build() - - Assert.assertEquals(TaskOutcome.SUCCESS, result.task(":generateSwagger")?.outcome) - - val result2ndRun = GradleRunner.create().withProjectDir(projectDir) - .forwardStdOutput(System.out.writer()) - .forwardStdError(System.err.writer()) - .withArguments("generateSwagger") - .build() - Assert.assertEquals(TaskOutcome.UP_TO_DATE, result2ndRun.task(":generateSwagger")?.outcome) - } - - @Test - fun testMinSupportdGradleVersion() { - val projectDir = temporaryFolder.newFolder("project") - File("src/test/testProject").copyRecursively(projectDir) - - val result = GradleRunner.create() - .withProjectDir(projectDir) - .withGradleVersion("5.4.1") - .forwardStdOutput(System.out.writer()) - .forwardStdError(System.err.writer()) - .withArguments("generateSwagger") - .build() - - Assert.assertEquals(TaskOutcome.SUCCESS, result.task(":generateSwagger")?.outcome) - } + @get:Rule + val temporaryFolder = TemporaryFolder(File(".")) + + @Test + fun basicPluginTest() { + val projectDir = temporaryFolder.newFolder("project") + File("src/test/testProject").copyRecursively(projectDir) + + val result = GradleRunner.create().withProjectDir(projectDir) + .forwardStdOutput(System.out.writer()) + .forwardStdError(System.err.writer()) + .withArguments("generateSwagger") + .build() + + Assert.assertEquals(TaskOutcome.SUCCESS, result.task(":generateSwagger")?.outcome) + + val result2ndRun = GradleRunner.create().withProjectDir(projectDir) + .forwardStdOutput(System.out.writer()) + .forwardStdError(System.err.writer()) + .withArguments("generateSwagger") + .build() + Assert.assertEquals(TaskOutcome.UP_TO_DATE, result2ndRun.task(":generateSwagger")?.outcome) + } + + @Test + fun testMinSupportdGradleVersion() { + val projectDir = temporaryFolder.newFolder("project") + File("src/test/testProject").copyRecursively(projectDir) + + val result = GradleRunner.create() + .withProjectDir(projectDir) + .withGradleVersion("5.4.1") + .forwardStdOutput(System.out.writer()) + .forwardStdError(System.err.writer()) + .withArguments("generateSwagger") + .build() + + Assert.assertEquals(TaskOutcome.SUCCESS, result.task(":generateSwagger")?.outcome) + } } diff --git a/samples/groovy-android/build.gradle b/samples/groovy-android/build.gradle index 3a5bb141..2fb99842 100644 --- a/samples/groovy-android/build.gradle +++ b/samples/groovy-android/build.gradle @@ -19,14 +19,12 @@ dependencies { // Kotlin implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.70" - // Moshi + OkHttp + Retrofit - implementation "com.squareup.moshi:moshi:1.9.2" - implementation "com.squareup.moshi:moshi-adapters:1.9.2" + // kotlinx.serialization + OkHttp + Retrofit + implementation("org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.20.0") implementation "com.squareup.okhttp3:okhttp:3.12.3" implementation "com.squareup.retrofit2:retrofit:2.7.1" implementation "com.squareup.retrofit2:converter-moshi:2.7.1" implementation "com.squareup.retrofit2:adapter-rxjava2:2.7.1" - kapt "com.squareup.moshi:moshi-kotlin-codegen:1.9.2" // Date Support implementation "com.jakewharton.threetenabp:threetenabp:1.2.2" diff --git a/samples/junit-tests/build.gradle b/samples/junit-tests/build.gradle index ebcf3933..72efb159 100644 --- a/samples/junit-tests/build.gradle +++ b/samples/junit-tests/build.gradle @@ -9,16 +9,15 @@ dependencies { // Kotlin implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.70" - // Moshi + OkHttp + Retrofit - implementation "com.squareup.moshi:moshi:1.9.2" - implementation "com.squareup.moshi:moshi-adapters:1.9.2" + // kotlinx.serialization + OkHttp + Retrofit + implementation("org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.20.0") implementation "com.squareup.okhttp3:okhttp:3.12.3" implementation "com.squareup.retrofit2:retrofit:2.7.1" implementation "com.squareup.retrofit2:converter-moshi:2.7.1" implementation "com.squareup.retrofit2:adapter-rxjava2:2.7.1" - kapt "com.squareup.moshi:moshi-kotlin-codegen:1.9.2" + implementation("com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:0.5.0") - // Date Support + // Date Support implementation "com.jakewharton.threetenabp:threetenabp:1.2.2" // RxJava diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/apis/FileApi.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/apis/FileApi.kt index d2023f40..a904910d 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/apis/FileApi.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/apis/FileApi.kt @@ -1,6 +1,6 @@ /** * NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: JUnit Tests - * + * API Version: 1.1.0 * More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen */ @@ -13,43 +13,43 @@ import retrofit2.http.POST @JvmSuppressWildcards interface FileApi { - /** - * The endpoint is owned by junittests service owner - * @param clientFile (required) - */ - @retrofit2.http.Multipart - @Headers( - "X-Operation-ID: post_file" - ) - @POST("/post/file") - fun postFile( - @retrofit2.http.Part("client_file\"; filename=\"client_file") clientFile: RequestBody - ): Completable - /** - * The endpoint is owned by junittests service owner - * @param clientFile (required) - */ - @retrofit2.http.FormUrlEncoded - @Headers( - "X-Operation-ID: post_file_without_multipart_form_data" - ) - @POST("/post/file_without_consumes") - @Deprecated(message = "Unsafe to use") - fun postFileWithoutMultipartFormData( - @retrofit2.http.Field("client_file\"; filename=\"client_file") clientFile: RequestBody - ): Completable - /** - * The endpoint is owned by junittests service owner - * @param clientFile (required) - * @param certificateFile (required) - */ - @retrofit2.http.Multipart - @Headers( - "X-Operation-ID: post_multiple_files" - ) - @POST("/post/multiple_files") - fun postMultipleFiles( - @retrofit2.http.Part("client_file\"; filename=\"client_file") clientFile: RequestBody, - @retrofit2.http.Part("certificate_file\"; filename=\"certificate_file") certificateFile: RequestBody - ): Completable + /** + * The endpoint is owned by junittests service owner + * @param clientFile (required) + */ + @retrofit2.http.Multipart + @Headers( + "X-Operation-ID: post_file" + ) + @POST("/post/file") + fun postFile( + @retrofit2.http.Part("client_file\"; filename=\"client_file") clientFile: RequestBody + ): Completable + /** + * The endpoint is owned by junittests service owner + * @param clientFile (required) + */ + @retrofit2.http.FormUrlEncoded + @Headers( + "X-Operation-ID: post_file_without_multipart_form_data" + ) + @POST("/post/file_without_consumes") + @Deprecated(message = "Unsafe to use") + fun postFileWithoutMultipartFormData( + @retrofit2.http.Field("client_file\"; filename=\"client_file") clientFile: RequestBody + ): Completable + /** + * The endpoint is owned by junittests service owner + * @param clientFile (required) + * @param certificateFile (required) + */ + @retrofit2.http.Multipart + @Headers( + "X-Operation-ID: post_multiple_files" + ) + @POST("/post/multiple_files") + fun postMultipleFiles( + @retrofit2.http.Part("client_file\"; filename=\"client_file") clientFile: RequestBody, + @retrofit2.http.Part("certificate_file\"; filename=\"certificate_file") certificateFile: RequestBody + ): Completable } diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/apis/ModelNameCheckApi.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/apis/ModelNameCheckApi.kt index 5cea583a..868b96e4 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/apis/ModelNameCheckApi.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/apis/ModelNameCheckApi.kt @@ -1,6 +1,6 @@ /** * NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: JUnit Tests - * + * API Version: 1.1.0 * More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen */ @@ -16,36 +16,36 @@ import retrofit2.http.Headers @JvmSuppressWildcards interface ModelNameCheckApi { - /** - * The endpoint is owned by junittests service owner - */ - @Headers( - "X-Operation-ID: getInlinedModelWithNoNames" - ) - @GET("/model_name/no_x-model_or_title") - fun getInlinedModelWithNoNames(): Single - /** - * The endpoint is owned by junittests service owner - */ - @Headers( - "X-Operation-ID: getInlinedModelWithTitleOnly" - ) - @GET("/model_name/title_only") - fun getInlinedModelWithTitleOnly(): Single - /** - * The endpoint is owned by junittests service owner - */ - @Headers( - "X-Operation-ID: getInlinedModelWithXModelAndTitle" - ) - @GET("/model_name/x-model_and_title") - fun getInlinedModelWithXModelAndTitle(): Single - /** - * The endpoint is owned by junittests service owner - */ - @Headers( - "X-Operation-ID: getInlinedModelWithXModelOnly" - ) - @GET("/model_name/x-model_only") - fun getInlinedModelWithXModelOnly(): Single + /** + * The endpoint is owned by junittests service owner + */ + @Headers( + "X-Operation-ID: getInlinedModelWithNoNames" + ) + @GET("/model_name/no_x-model_or_title") + fun getInlinedModelWithNoNames(): Single + /** + * The endpoint is owned by junittests service owner + */ + @Headers( + "X-Operation-ID: getInlinedModelWithTitleOnly" + ) + @GET("/model_name/title_only") + fun getInlinedModelWithTitleOnly(): Single + /** + * The endpoint is owned by junittests service owner + */ + @Headers( + "X-Operation-ID: getInlinedModelWithXModelAndTitle" + ) + @GET("/model_name/x-model_and_title") + fun getInlinedModelWithXModelAndTitle(): Single + /** + * The endpoint is owned by junittests service owner + */ + @Headers( + "X-Operation-ID: getInlinedModelWithXModelOnly" + ) + @GET("/model_name/x-model_only") + fun getInlinedModelWithXModelOnly(): Single } diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/apis/ResourceApi.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/apis/ResourceApi.kt index e830258a..1bf6fb63 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/apis/ResourceApi.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/apis/ResourceApi.kt @@ -1,6 +1,6 @@ /** * NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: JUnit Tests - * + * API Version: 1.1.0 * More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen */ @@ -24,140 +24,140 @@ import retrofit2.http.Headers @JvmSuppressWildcards interface ResourceApi { - /** - * The endpoint is owned by junittests service owner - */ - @Headers( - "X-Operation-ID: get_empty_endpoint" - ) - @GET("/empty_endpoint") - fun getEmptyEndpoint(): Single - /** - * The endpoint is owned by junittests service owner - * @param propertyFormat (required) - */ - @Headers( - "X-Operation-ID: get_format_endpoint" - ) - @GET("/format_endpoint/{property_format}") - fun getFormatEndpoint( - @retrofit2.http.Path("property_format") propertyFormat: String - ): Single - /** - * The endpoint is owned by junittests service owner - */ - @Headers( - "X-Operation-ID: get_nested_additional_properties" - ) - @GET("/nested_additional_properties") - fun getNestedAdditionalProperties(): Single - /** - * The endpoint is owned by junittests service owner - */ - @Headers( - "X-Operation-ID: get_nested_additional_properties_custom_description" - ) - @GET("/nested_additional_properties/custom_description") - fun getNestedAdditionalPropertiesCustomDescription(): Single - /** - * The endpoint is owned by junittests service owner - * @param valueType (required) - * @param size (required) - */ - @Headers( - "X-Operation-ID: get_property_array" - ) - @GET("/property_array/{value_type}/{size}") - fun getPropertyArray( - @retrofit2.http.Path("value_type") valueType: String, - @retrofit2.http.Path("size") size: String - ): Single - /** - * The endpoint is owned by junittests service owner - * @param valueType (required) - * @param size (required) - */ - @Headers( - "X-Operation-ID: get_property_map" - ) - @GET("/property_map/{value_type}/{size}") - fun getPropertyMap( - @retrofit2.http.Path("value_type") valueType: String, - @retrofit2.http.Path("size") size: String - ): Single - /** - * The endpoint is owned by junittests service owner - */ - @Headers( - "X-Operation-ID: get_required_type_endpoint" - ) - @GET("/required/type_endpoint") - fun getRequiredTypeEndpoint(): Single - /** - * The endpoint is owned by junittests service owner - */ - @Headers( - "X-Operation-ID: get_reserved_keywords" - ) - @GET("/reserved_keywords") - fun getReservedKeywords(): Single - /** - * Test symbols in parameter name - * Make sure that symbols in parameter name are treated properly - * The endpoint is owned by junittests service owner - * @param parameter (optional) - * @param brackets (optional) - * @param bracketsWithText (optional) - * @param dot (optional) - * @param dotWithText (optional) - */ - @Headers( - "X-Operation-ID: getSymbolsInParameterName" - ) - @GET("/symbols/in/parameter/name") - fun getSymbolsInParameterName( - @retrofit2.http.Query("parameter") parameter: String?, - @retrofit2.http.Query("brackets[]") brackets: String?, - @retrofit2.http.Query("brackets[withText]") bracketsWithText: String?, - @retrofit2.http.Query("dot.") dot: String?, - @retrofit2.http.Query("dot.withText") dotWithText: String? - ): Completable - /** - * The endpoint is owned by junittests service owner - */ - @Headers( - "X-Operation-ID: get_top_level_enum" - ) - @GET("/top_level_enum") - fun getTopLevelEnum(): Single - /** - * The endpoint is owned by junittests service owner - */ - @Headers( - "X-Operation-ID: get_top_level_enum_nested" - ) - @GET("/top_level_enum/nested") - fun getTopLevelEnumNested(): Single>> - /** - * The endpoint is owned by junittests service owner - * @param size (required) - */ - @Headers( - "X-Operation-ID: get_top_level_map" - ) - @GET("/top_level_map/{size}") - fun getTopLevelMap( - @retrofit2.http.Path("size") size: String - ): Single - /** - * The endpoint is owned by junittests service owner - * @param propertyType (required) - */ - @Headers( - "X-Operation-ID: get_type_endpoint" - ) - @GET("/type_endpoint/{property_type}") - fun getTypeEndpoint( - @retrofit2.http.Path("property_type") propertyType: String - ): Single + /** + * The endpoint is owned by junittests service owner + */ + @Headers( + "X-Operation-ID: get_empty_endpoint" + ) + @GET("/empty_endpoint") + fun getEmptyEndpoint(): Single + /** + * The endpoint is owned by junittests service owner + * @param propertyFormat (required) + */ + @Headers( + "X-Operation-ID: get_format_endpoint" + ) + @GET("/format_endpoint/{property_format}") + fun getFormatEndpoint( + @retrofit2.http.Path("property_format") propertyFormat: String + ): Single + /** + * The endpoint is owned by junittests service owner + */ + @Headers( + "X-Operation-ID: get_nested_additional_properties" + ) + @GET("/nested_additional_properties") + fun getNestedAdditionalProperties(): Single + /** + * The endpoint is owned by junittests service owner + */ + @Headers( + "X-Operation-ID: get_nested_additional_properties_custom_description" + ) + @GET("/nested_additional_properties/custom_description") + fun getNestedAdditionalPropertiesCustomDescription(): Single + /** + * The endpoint is owned by junittests service owner + * @param valueType (required) + * @param size (required) + */ + @Headers( + "X-Operation-ID: get_property_array" + ) + @GET("/property_array/{value_type}/{size}") + fun getPropertyArray( + @retrofit2.http.Path("value_type") valueType: String, + @retrofit2.http.Path("size") size: String + ): Single + /** + * The endpoint is owned by junittests service owner + * @param valueType (required) + * @param size (required) + */ + @Headers( + "X-Operation-ID: get_property_map" + ) + @GET("/property_map/{value_type}/{size}") + fun getPropertyMap( + @retrofit2.http.Path("value_type") valueType: String, + @retrofit2.http.Path("size") size: String + ): Single + /** + * The endpoint is owned by junittests service owner + */ + @Headers( + "X-Operation-ID: get_required_type_endpoint" + ) + @GET("/required/type_endpoint") + fun getRequiredTypeEndpoint(): Single + /** + * The endpoint is owned by junittests service owner + */ + @Headers( + "X-Operation-ID: get_reserved_keywords" + ) + @GET("/reserved_keywords") + fun getReservedKeywords(): Single + /** + * Test symbols in parameter name + * Make sure that symbols in parameter name are treated properly + * The endpoint is owned by junittests service owner + * @param parameter (optional) + * @param brackets (optional) + * @param bracketsWithText (optional) + * @param dot (optional) + * @param dotWithText (optional) + */ + @Headers( + "X-Operation-ID: getSymbolsInParameterName" + ) + @GET("/symbols/in/parameter/name") + fun getSymbolsInParameterName( + @retrofit2.http.Query("parameter") parameter: String?, + @retrofit2.http.Query("brackets[]") brackets: String?, + @retrofit2.http.Query("brackets[withText]") bracketsWithText: String?, + @retrofit2.http.Query("dot.") dot: String?, + @retrofit2.http.Query("dot.withText") dotWithText: String? + ): Completable + /** + * The endpoint is owned by junittests service owner + */ + @Headers( + "X-Operation-ID: get_top_level_enum" + ) + @GET("/top_level_enum") + fun getTopLevelEnum(): Single + /** + * The endpoint is owned by junittests service owner + */ + @Headers( + "X-Operation-ID: get_top_level_enum_nested" + ) + @GET("/top_level_enum/nested") + fun getTopLevelEnumNested(): Single>> + /** + * The endpoint is owned by junittests service owner + * @param size (required) + */ + @Headers( + "X-Operation-ID: get_top_level_map" + ) + @GET("/top_level_map/{size}") + fun getTopLevelMap( + @retrofit2.http.Path("size") size: String + ): Single + /** + * The endpoint is owned by junittests service owner + * @param propertyType (required) + */ + @Headers( + "X-Operation-ID: get_type_endpoint" + ) + @GET("/type_endpoint/{property_type}") + fun getTypeEndpoint( + @retrofit2.http.Path("property_type") propertyType: String + ): Single } diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/apis/XnullableApi.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/apis/XnullableApi.kt index efef469e..f5069841 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/apis/XnullableApi.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/apis/XnullableApi.kt @@ -1,6 +1,6 @@ /** * NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: JUnit Tests - * + * API Version: 1.1.0 * More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen */ @@ -20,93 +20,93 @@ import retrofit2.http.Headers @JvmSuppressWildcards interface XnullableApi { - /** - * The endpoint is owned by junittests service owner - * @param propertyFormat (required) - */ - @Headers( - "X-Operation-ID: get_xnullable_format_endpoint" - ) - @GET("/xnullable/format_endpoint/{property_format}") - fun getXnullableFormatEndpoint( - @retrofit2.http.Path("property_format") propertyFormat: String - ): Single - /** - * The endpoint is owned by junittests service owner - */ - @Headers( - "X-Operation-ID: get_xnullable_nested_additional_properties" - ) - @GET("/xnullable/nested_additional_properties") - fun getXnullableNestedAdditionalProperties(): Single - /** - * The endpoint is owned by junittests service owner - * @param valueType (required) - * @param size (required) - */ - @Headers( - "X-Operation-ID: get_xnullable_property_array" - ) - @GET("/xnullable/property_array/{value_type}/{size}") - fun getXnullablePropertyArray( - @retrofit2.http.Path("value_type") valueType: String, - @retrofit2.http.Path("size") size: String - ): Single - /** - * The endpoint is owned by junittests service owner - * @param valueType (required) - * @param size (required) - */ - @Headers( - "X-Operation-ID: get_xnullable_property_map" - ) - @GET("/xnullable/property_map/{value_type}/{size}") - fun getXnullablePropertyMap( - @retrofit2.http.Path("value_type") valueType: String, - @retrofit2.http.Path("size") size: String - ): Single - /** - * The endpoint is owned by junittests service owner - * @param size (required) - */ - @Headers( - "X-Operation-ID: get_xnullable_required_property_array" - ) - @GET("/xnullable/required/property_array/{size}") - fun getXnullableRequiredPropertyArray( - @retrofit2.http.Path("size") size: String - ): Single - /** - * The endpoint is owned by junittests service owner - * @param size (required) - */ - @Headers( - "X-Operation-ID: get_xnullable_required_property_map" - ) - @GET("/xnullable/required/property_map/{size}") - fun getXnullableRequiredPropertyMap( - @retrofit2.http.Path("size") size: String - ): Single - /** - * The endpoint is owned by junittests service owner - * @param propertyType (required) - */ - @Headers( - "X-Operation-ID: get_xnullable_required_type_endpoint" - ) - @GET("/xnullable/required/type_endpoint/{property_type}") - fun getXnullableRequiredTypeEndpoint( - @retrofit2.http.Path("property_type") propertyType: String - ): Single - /** - * The endpoint is owned by junittests service owner - * @param propertyType (required) - */ - @Headers( - "X-Operation-ID: get_xnullable_type_endpoint" - ) - @GET("/xnullable/type_endpoint/{property_type}") - fun getXnullableTypeEndpoint( - @retrofit2.http.Path("property_type") propertyType: String - ): Single + /** + * The endpoint is owned by junittests service owner + * @param propertyFormat (required) + */ + @Headers( + "X-Operation-ID: get_xnullable_format_endpoint" + ) + @GET("/xnullable/format_endpoint/{property_format}") + fun getXnullableFormatEndpoint( + @retrofit2.http.Path("property_format") propertyFormat: String + ): Single + /** + * The endpoint is owned by junittests service owner + */ + @Headers( + "X-Operation-ID: get_xnullable_nested_additional_properties" + ) + @GET("/xnullable/nested_additional_properties") + fun getXnullableNestedAdditionalProperties(): Single + /** + * The endpoint is owned by junittests service owner + * @param valueType (required) + * @param size (required) + */ + @Headers( + "X-Operation-ID: get_xnullable_property_array" + ) + @GET("/xnullable/property_array/{value_type}/{size}") + fun getXnullablePropertyArray( + @retrofit2.http.Path("value_type") valueType: String, + @retrofit2.http.Path("size") size: String + ): Single + /** + * The endpoint is owned by junittests service owner + * @param valueType (required) + * @param size (required) + */ + @Headers( + "X-Operation-ID: get_xnullable_property_map" + ) + @GET("/xnullable/property_map/{value_type}/{size}") + fun getXnullablePropertyMap( + @retrofit2.http.Path("value_type") valueType: String, + @retrofit2.http.Path("size") size: String + ): Single + /** + * The endpoint is owned by junittests service owner + * @param size (required) + */ + @Headers( + "X-Operation-ID: get_xnullable_required_property_array" + ) + @GET("/xnullable/required/property_array/{size}") + fun getXnullableRequiredPropertyArray( + @retrofit2.http.Path("size") size: String + ): Single + /** + * The endpoint is owned by junittests service owner + * @param size (required) + */ + @Headers( + "X-Operation-ID: get_xnullable_required_property_map" + ) + @GET("/xnullable/required/property_map/{size}") + fun getXnullableRequiredPropertyMap( + @retrofit2.http.Path("size") size: String + ): Single + /** + * The endpoint is owned by junittests service owner + * @param propertyType (required) + */ + @Headers( + "X-Operation-ID: get_xnullable_required_type_endpoint" + ) + @GET("/xnullable/required/type_endpoint/{property_type}") + fun getXnullableRequiredTypeEndpoint( + @retrofit2.http.Path("property_type") propertyType: String + ): Single + /** + * The endpoint is owned by junittests service owner + * @param propertyType (required) + */ + @Headers( + "X-Operation-ID: get_xnullable_type_endpoint" + ) + @GET("/xnullable/type_endpoint/{property_type}") + fun getXnullableTypeEndpoint( + @retrofit2.http.Path("property_type") propertyType: String + ): Single } diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/EmptyModel.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/EmptyModel.kt index b130ce58..4c6951d9 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/EmptyModel.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/EmptyModel.kt @@ -1,14 +1,14 @@ /** * NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: JUnit Tests - * + * API Version: 1.1.0 * More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen */ package com.yelp.codegen.generatecodesamples.models -import com.squareup.moshi.JsonClass +import kotlinx.serialization.Serializable /** */ -@JsonClass(generateAdapter = true) +@Serializable class EmptyModel diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/FormatResponses.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/FormatResponses.kt index 70c79918..abcc6458 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/FormatResponses.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/FormatResponses.kt @@ -1,13 +1,13 @@ /** * NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: JUnit Tests - * + * API Version: 1.1.0 * More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen */ package com.yelp.codegen.generatecodesamples.models -import com.squareup.moshi.Json -import com.squareup.moshi.JsonClass +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable import org.threeten.bp.LocalDate import org.threeten.bp.ZonedDateTime @@ -16,18 +16,19 @@ import org.threeten.bp.ZonedDateTime * @property datetimeProperty * @property enumProperty */ -@JsonClass(generateAdapter = true) +@Serializable data class FormatResponses( - @Json(name = "date_property") @field:Json(name = "date_property") var dateProperty: LocalDate? = null, - @Json(name = "datetime_property") @field:Json(name = "datetime_property") var datetimeProperty: ZonedDateTime? = null, - @Json(name = "enum_property") @field:Json(name = "enum_property") var enumProperty: FormatResponses.EnumPropertyEnum? = null + @SerialName("date_property") var dateProperty: LocalDate? = null, + @SerialName("datetime_property") var datetimeProperty: ZonedDateTime? = null, + @SerialName("enum_property") var enumProperty: FormatResponses.EnumPropertyEnum? = null + ) { - /** - * Values: VALUE1, VALUE2 - */ - @JsonClass(generateAdapter = false) - enum class EnumPropertyEnum(val value: String) { - @Json(name = "VALUE1") VALUE1("VALUE1"), - @Json(name = "VALUE2") VALUE2("VALUE2") - } + /** + * Values: VALUE1, VALUE2 + */ + @Serializable + enum class EnumPropertyEnum(val value: String) { + VALUE1("VALUE1"), + VALUE2("VALUE2") + } } diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/InlineResponse200.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/InlineResponse200.kt index 05e2e92d..f9eeaa33 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/InlineResponse200.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/InlineResponse200.kt @@ -1,27 +1,28 @@ /** * NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: JUnit Tests - * + * API Version: 1.1.0 * More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen */ package com.yelp.codegen.generatecodesamples.models -import com.squareup.moshi.Json -import com.squareup.moshi.JsonClass +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable /** * @property noXmodelNoTitle */ -@JsonClass(generateAdapter = true) +@Serializable data class InlineResponse200( - @Json(name = "no_xmodel_no_title") @field:Json(name = "no_xmodel_no_title") var noXmodelNoTitle: InlineResponse200.NoXmodelNoTitleEnum? = null + @SerialName("no_xmodel_no_title") var noXmodelNoTitle: InlineResponse200.NoXmodelNoTitleEnum? = null + ) { - /** - * Values: VAL1, VAL2 - */ - @JsonClass(generateAdapter = false) - enum class NoXmodelNoTitleEnum(val value: String) { - @Json(name = "val1") VAL1("val1"), - @Json(name = "val2") VAL2("val2") - } + /** + * Values: VAL1, VAL2 + */ + @Serializable + enum class NoXmodelNoTitleEnum(val value: String) { + VAL1("val1"), + VAL2("val2") + } } diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/ModelWithOnlyTitle.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/ModelWithOnlyTitle.kt index fd534d26..85f1d18c 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/ModelWithOnlyTitle.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/ModelWithOnlyTitle.kt @@ -1,27 +1,28 @@ /** * NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: JUnit Tests - * + * API Version: 1.1.0 * More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen */ package com.yelp.codegen.generatecodesamples.models -import com.squareup.moshi.Json -import com.squareup.moshi.JsonClass +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable /** * @property titleOnly */ -@JsonClass(generateAdapter = true) +@Serializable data class ModelWithOnlyTitle( - @Json(name = "title_only") @field:Json(name = "title_only") var titleOnly: ModelWithOnlyTitle.TitleOnlyEnum? = null + @SerialName("title_only") var titleOnly: ModelWithOnlyTitle.TitleOnlyEnum? = null + ) { - /** - * Values: VAL1, VAL2 - */ - @JsonClass(generateAdapter = false) - enum class TitleOnlyEnum(val value: String) { - @Json(name = "val1") VAL1("val1"), - @Json(name = "val2") VAL2("val2") - } + /** + * Values: VAL1, VAL2 + */ + @Serializable + enum class TitleOnlyEnum(val value: String) { + VAL1("val1"), + VAL2("val2") + } } diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/ModelWithOnlyXModel.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/ModelWithOnlyXModel.kt index 4effdbd7..1acf2f5f 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/ModelWithOnlyXModel.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/ModelWithOnlyXModel.kt @@ -1,27 +1,28 @@ /** * NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: JUnit Tests - * + * API Version: 1.1.0 * More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen */ package com.yelp.codegen.generatecodesamples.models -import com.squareup.moshi.Json -import com.squareup.moshi.JsonClass +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable /** * @property xmodelOnly */ -@JsonClass(generateAdapter = true) +@Serializable data class ModelWithOnlyXModel( - @Json(name = "xmodel_only") @field:Json(name = "xmodel_only") var xmodelOnly: ModelWithOnlyXModel.XmodelOnlyEnum? = null + @SerialName("xmodel_only") var xmodelOnly: ModelWithOnlyXModel.XmodelOnlyEnum? = null + ) { - /** - * Values: VAL1, VAL2 - */ - @JsonClass(generateAdapter = false) - enum class XmodelOnlyEnum(val value: String) { - @Json(name = "val1") VAL1("val1"), - @Json(name = "val2") VAL2("val2") - } + /** + * Values: VAL1, VAL2 + */ + @Serializable + enum class XmodelOnlyEnum(val value: String) { + VAL1("val1"), + VAL2("val2") + } } diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/ModelWithXModelAndTitle.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/ModelWithXModelAndTitle.kt index bf7436fe..94a9517e 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/ModelWithXModelAndTitle.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/ModelWithXModelAndTitle.kt @@ -1,27 +1,28 @@ /** * NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: JUnit Tests - * + * API Version: 1.1.0 * More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen */ package com.yelp.codegen.generatecodesamples.models -import com.squareup.moshi.Json -import com.squareup.moshi.JsonClass +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable /** * @property xmodelAndTitle */ -@JsonClass(generateAdapter = true) +@Serializable data class ModelWithXModelAndTitle( - @Json(name = "xmodel_and_title") @field:Json(name = "xmodel_and_title") var xmodelAndTitle: ModelWithXModelAndTitle.XmodelAndTitleEnum? = null + @SerialName("xmodel_and_title") var xmodelAndTitle: ModelWithXModelAndTitle.XmodelAndTitleEnum? = null + ) { - /** - * Values: VAL1, VAL2 - */ - @JsonClass(generateAdapter = false) - enum class XmodelAndTitleEnum(val value: String) { - @Json(name = "val1") VAL1("val1"), - @Json(name = "val2") VAL2("val2") - } + /** + * Values: VAL1, VAL2 + */ + @Serializable + enum class XmodelAndTitleEnum(val value: String) { + VAL1("val1"), + VAL2("val2") + } } diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/NestedAdditionalProperties.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/NestedAdditionalProperties.kt index 8e4a44bf..343d5f04 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/NestedAdditionalProperties.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/NestedAdditionalProperties.kt @@ -1,6 +1,6 @@ /** * NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: JUnit Tests - * + * API Version: 1.1.0 * More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen */ diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/NestedAdditionalPropertiesCustomDescription.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/NestedAdditionalPropertiesCustomDescription.kt index 9a05a438..db3d9778 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/NestedAdditionalPropertiesCustomDescription.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/NestedAdditionalPropertiesCustomDescription.kt @@ -1,6 +1,6 @@ /** * NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: JUnit Tests - * + * API Version: 1.1.0 * More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen */ diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/PropertyArray.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/PropertyArray.kt index 12a51043..31e77815 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/PropertyArray.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/PropertyArray.kt @@ -1,21 +1,22 @@ /** * NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: JUnit Tests - * + * API Version: 1.1.0 * More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen */ package com.yelp.codegen.generatecodesamples.models -import com.squareup.moshi.Json -import com.squareup.moshi.JsonClass +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable import java.math.BigDecimal /** * @property numberArray * @property stringArray */ -@JsonClass(generateAdapter = true) +@Serializable data class PropertyArray( - @Json(name = "number_array") @field:Json(name = "number_array") var numberArray: List? = null, - @Json(name = "string_array") @field:Json(name = "string_array") var stringArray: List? = null + @SerialName("number_array") var numberArray: List? = null, + @SerialName("string_array") var stringArray: List? = null + ) diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/PropertyMap.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/PropertyMap.kt index e2b2e1d6..f8f03ebe 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/PropertyMap.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/PropertyMap.kt @@ -1,13 +1,13 @@ /** * NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: JUnit Tests - * + * API Version: 1.1.0 * More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen */ package com.yelp.codegen.generatecodesamples.models -import com.squareup.moshi.Json -import com.squareup.moshi.JsonClass +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable import java.math.BigDecimal /** @@ -15,9 +15,10 @@ import java.math.BigDecimal * @property objectMap * @property stringMap */ -@JsonClass(generateAdapter = true) +@Serializable data class PropertyMap( - @Json(name = "number_map") @field:Json(name = "number_map") var numberMap: Map? = null, - @Json(name = "object_map") @field:Json(name = "object_map") var objectMap: Map? = null, - @Json(name = "string_map") @field:Json(name = "string_map") var stringMap: Map? = null + @SerialName("number_map") var numberMap: Map? = null, + @SerialName("object_map") var objectMap: Map? = null, + @SerialName("string_map") var stringMap: Map? = null + ) diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/RequiredTypeResponses.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/RequiredTypeResponses.kt index ba701e71..92572141 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/RequiredTypeResponses.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/RequiredTypeResponses.kt @@ -1,13 +1,13 @@ /** * NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: JUnit Tests - * + * API Version: 1.1.0 * More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen */ package com.yelp.codegen.generatecodesamples.models -import com.squareup.moshi.Json -import com.squareup.moshi.JsonClass +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable import java.math.BigDecimal /** @@ -17,20 +17,21 @@ import java.math.BigDecimal * @property numberProperty * @property stringProperty */ -@JsonClass(generateAdapter = true) +@Serializable data class RequiredTypeResponses( - @Json(name = "boolean_property") @field:Json(name = "boolean_property") var booleanProperty: Boolean, - @Json(name = "enum_property") @field:Json(name = "enum_property") var enumProperty: RequiredTypeResponses.EnumPropertyEnum, - @Json(name = "integer_property") @field:Json(name = "integer_property") var integerProperty: Int, - @Json(name = "number_property") @field:Json(name = "number_property") var numberProperty: BigDecimal, - @Json(name = "string_property") @field:Json(name = "string_property") var stringProperty: String + @SerialName("boolean_property") var booleanProperty: Boolean, + @SerialName("enum_property") var enumProperty: RequiredTypeResponses.EnumPropertyEnum, + @SerialName("integer_property") var integerProperty: Int, + @SerialName("number_property") var numberProperty: BigDecimal, + @SerialName("string_property") var stringProperty: String + ) { - /** - * Values: VALUE1, VALUE2 - */ - @JsonClass(generateAdapter = false) - enum class EnumPropertyEnum(val value: String) { - @Json(name = "VALUE1") VALUE1("VALUE1"), - @Json(name = "VALUE2") VALUE2("VALUE2") - } + /** + * Values: VALUE1, VALUE2 + */ + @Serializable + enum class EnumPropertyEnum(val value: String) { + VALUE1("VALUE1"), + VALUE2("VALUE2") + } } diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/ReservedKeywords.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/ReservedKeywords.kt index 110d73be..2322a531 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/ReservedKeywords.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/ReservedKeywords.kt @@ -1,13 +1,13 @@ /** * NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: JUnit Tests - * + * API Version: 1.1.0 * More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen */ package com.yelp.codegen.generatecodesamples.models -import com.squareup.moshi.Json -import com.squareup.moshi.JsonClass +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable /** * @property `class` @@ -17,12 +17,13 @@ import com.squareup.moshi.JsonClass * @property `var` * @property `when` */ -@JsonClass(generateAdapter = true) +@Serializable data class ReservedKeywords( - @Json(name = "class") @field:Json(name = "class") var `class`: String? = null, - @Json(name = "for") @field:Json(name = "for") var `for`: String? = null, - @Json(name = "operator") @field:Json(name = "operator") var `operator`: String? = null, - @Json(name = "val") @field:Json(name = "val") var `val`: String? = null, - @Json(name = "var") @field:Json(name = "var") var `var`: String? = null, - @Json(name = "when") @field:Json(name = "when") var `when`: String? = null + @SerialName("class") var `class`: String? = null, + @SerialName("for") var `for`: String? = null, + @SerialName("operator") var `operator`: String? = null, + @SerialName("val") var `val`: String? = null, + @SerialName("var") var `var`: String? = null, + @SerialName("when") var `when`: String? = null + ) diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/TopLevelEnum.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/TopLevelEnum.kt index 3e95e645..fbaaf1be 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/TopLevelEnum.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/TopLevelEnum.kt @@ -1,19 +1,19 @@ /** * NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: JUnit Tests - * + * API Version: 1.1.0 * More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen */ package com.yelp.codegen.generatecodesamples.models -import com.squareup.moshi.Json -import com.squareup.moshi.JsonClass +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable /** * Values: VALUE1,VALUE2 */ -@JsonClass(generateAdapter = false) +@Serializable enum class TopLevelEnum(val value: String) { - @Json(name = "TOP_LEVEL_VALUE1") VALUE1("TOP_LEVEL_VALUE1"), - @Json(name = "TOP_LEVEL_VALUE2") VALUE2("TOP_LEVEL_VALUE2") + @SerialName("TOP_LEVEL_VALUE1") VALUE1("TOP_LEVEL_VALUE1"), + @SerialName("TOP_LEVEL_VALUE2") VALUE2("TOP_LEVEL_VALUE2") } diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/TopLevelMap.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/TopLevelMap.kt index c003e56e..edd04f42 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/TopLevelMap.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/TopLevelMap.kt @@ -1,6 +1,6 @@ /** * NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: JUnit Tests - * + * API Version: 1.1.0 * More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen */ diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/TypeResponses.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/TypeResponses.kt index c8322292..9c216b53 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/TypeResponses.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/TypeResponses.kt @@ -1,13 +1,13 @@ /** * NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: JUnit Tests - * + * API Version: 1.1.0 * More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen */ package com.yelp.codegen.generatecodesamples.models -import com.squareup.moshi.Json -import com.squareup.moshi.JsonClass +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable import java.math.BigDecimal /** @@ -16,10 +16,11 @@ import java.math.BigDecimal * @property numberProperty * @property stringProperty */ -@JsonClass(generateAdapter = true) +@Serializable data class TypeResponses( - @Json(name = "boolean_property") @field:Json(name = "boolean_property") var booleanProperty: Boolean? = null, - @Json(name = "integer_property") @field:Json(name = "integer_property") var integerProperty: Int? = null, - @Json(name = "number_property") @field:Json(name = "number_property") var numberProperty: BigDecimal? = null, - @Json(name = "string_property") @field:Json(name = "string_property") var stringProperty: String? = null + @SerialName("boolean_property") var booleanProperty: Boolean? = null, + @SerialName("integer_property") var integerProperty: Int? = null, + @SerialName("number_property") var numberProperty: BigDecimal? = null, + @SerialName("string_property") var stringProperty: String? = null + ) diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullableFormatResponses.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullableFormatResponses.kt index 7c10a255..5d69d63a 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullableFormatResponses.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullableFormatResponses.kt @@ -1,14 +1,14 @@ /** * NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: JUnit Tests - * + * API Version: 1.1.0 * More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen */ package com.yelp.codegen.generatecodesamples.models -import com.squareup.moshi.Json -import com.squareup.moshi.JsonClass import com.yelp.codegen.generatecodesamples.tools.XNullable +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable import org.threeten.bp.LocalDate import org.threeten.bp.ZonedDateTime @@ -17,9 +17,10 @@ import org.threeten.bp.ZonedDateTime * @property datetimeProperty * @property doubleProperty */ -@JsonClass(generateAdapter = true) +@Serializable data class XnullableFormatResponses( - @Json(name = "date_property") @field:Json(name = "date_property") @XNullable var dateProperty: LocalDate? = null, - @Json(name = "datetime_property") @field:Json(name = "datetime_property") @XNullable var datetimeProperty: ZonedDateTime? = null, - @Json(name = "double_property") @field:Json(name = "double_property") @XNullable var doubleProperty: Double? = null + @SerialName("date_property") @XNullable var dateProperty: LocalDate? = null, + @SerialName("datetime_property") @XNullable var datetimeProperty: ZonedDateTime? = null, + @SerialName("double_property") @XNullable var doubleProperty: Double? = null + ) diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullableMap.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullableMap.kt index 0b60d554..05e10d5e 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullableMap.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullableMap.kt @@ -1,6 +1,6 @@ /** * NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: JUnit Tests - * + * API Version: 1.1.0 * More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen */ diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullableNestedAdditionalProperties.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullableNestedAdditionalProperties.kt index d603a32d..f1d9fd42 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullableNestedAdditionalProperties.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullableNestedAdditionalProperties.kt @@ -1,6 +1,6 @@ /** * NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: JUnit Tests - * + * API Version: 1.1.0 * More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen */ diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullablePropertyArray.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullablePropertyArray.kt index 72f19717..4b9880c4 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullablePropertyArray.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullablePropertyArray.kt @@ -1,22 +1,23 @@ /** * NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: JUnit Tests - * + * API Version: 1.1.0 * More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen */ package com.yelp.codegen.generatecodesamples.models -import com.squareup.moshi.Json -import com.squareup.moshi.JsonClass import com.yelp.codegen.generatecodesamples.tools.XNullable +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable import java.math.BigDecimal /** * @property numberArray * @property stringArray */ -@JsonClass(generateAdapter = true) +@Serializable data class XnullablePropertyArray( - @Json(name = "number_array") @field:Json(name = "number_array") @XNullable var numberArray: List? = null, - @Json(name = "string_array") @field:Json(name = "string_array") @XNullable var stringArray: List? = null + @SerialName("number_array") @XNullable var numberArray: List? = null, + @SerialName("string_array") @XNullable var stringArray: List? = null + ) diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullablePropertyMap.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullablePropertyMap.kt index a60855b9..954efac6 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullablePropertyMap.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullablePropertyMap.kt @@ -1,14 +1,14 @@ /** * NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: JUnit Tests - * + * API Version: 1.1.0 * More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen */ package com.yelp.codegen.generatecodesamples.models -import com.squareup.moshi.Json -import com.squareup.moshi.JsonClass import com.yelp.codegen.generatecodesamples.tools.XNullable +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable import java.math.BigDecimal /** @@ -16,9 +16,10 @@ import java.math.BigDecimal * @property objectMap * @property stringMap */ -@JsonClass(generateAdapter = true) +@Serializable data class XnullablePropertyMap( - @Json(name = "number_map") @field:Json(name = "number_map") @XNullable var numberMap: Map? = null, - @Json(name = "object_map") @field:Json(name = "object_map") @XNullable var objectMap: Map? = null, - @Json(name = "string_map") @field:Json(name = "string_map") @XNullable var stringMap: Map? = null + @SerialName("number_map") @XNullable var numberMap: Map? = null, + @SerialName("object_map") @XNullable var objectMap: Map? = null, + @SerialName("string_map") @XNullable var stringMap: Map? = null + ) diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullableRequiredPropertyArray.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullableRequiredPropertyArray.kt index af9ef5ab..e59f8661 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullableRequiredPropertyArray.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullableRequiredPropertyArray.kt @@ -1,22 +1,23 @@ /** * NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: JUnit Tests - * + * API Version: 1.1.0 * More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen */ package com.yelp.codegen.generatecodesamples.models -import com.squareup.moshi.Json -import com.squareup.moshi.JsonClass import com.yelp.codegen.generatecodesamples.tools.XNullable +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable import java.math.BigDecimal /** * @property numberArray * @property stringArray */ -@JsonClass(generateAdapter = true) +@Serializable data class XnullableRequiredPropertyArray( - @Json(name = "number_array") @field:Json(name = "number_array") @XNullable var numberArray: List? = null, - @Json(name = "string_array") @field:Json(name = "string_array") @XNullable var stringArray: List? = null + @SerialName("number_array") @XNullable var numberArray: List? = null, + @SerialName("string_array") @XNullable var stringArray: List? = null + ) diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullableRequiredPropertyMap.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullableRequiredPropertyMap.kt index e926c81c..381cc2b9 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullableRequiredPropertyMap.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullableRequiredPropertyMap.kt @@ -1,14 +1,14 @@ /** * NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: JUnit Tests - * + * API Version: 1.1.0 * More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen */ package com.yelp.codegen.generatecodesamples.models -import com.squareup.moshi.Json -import com.squareup.moshi.JsonClass import com.yelp.codegen.generatecodesamples.tools.XNullable +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable import java.math.BigDecimal /** @@ -16,9 +16,10 @@ import java.math.BigDecimal * @property objectMap * @property stringMap */ -@JsonClass(generateAdapter = true) +@Serializable data class XnullableRequiredPropertyMap( - @Json(name = "number_map") @field:Json(name = "number_map") @XNullable var numberMap: Map? = null, - @Json(name = "object_map") @field:Json(name = "object_map") @XNullable var objectMap: Map? = null, - @Json(name = "string_map") @field:Json(name = "string_map") @XNullable var stringMap: Map? = null + @SerialName("number_map") @XNullable var numberMap: Map? = null, + @SerialName("object_map") @XNullable var objectMap: Map? = null, + @SerialName("string_map") @XNullable var stringMap: Map? = null + ) diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullableRequiredTypeResponses.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullableRequiredTypeResponses.kt index 7d20c77b..3ced2729 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullableRequiredTypeResponses.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullableRequiredTypeResponses.kt @@ -1,14 +1,14 @@ /** * NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: JUnit Tests - * + * API Version: 1.1.0 * More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen */ package com.yelp.codegen.generatecodesamples.models -import com.squareup.moshi.Json -import com.squareup.moshi.JsonClass import com.yelp.codegen.generatecodesamples.tools.XNullable +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable import java.math.BigDecimal /** @@ -18,20 +18,21 @@ import java.math.BigDecimal * @property numberProperty * @property stringProperty */ -@JsonClass(generateAdapter = true) +@Serializable data class XnullableRequiredTypeResponses( - @Json(name = "boolean_property") @field:Json(name = "boolean_property") @XNullable var booleanProperty: Boolean? = null, - @Json(name = "enum_property") @field:Json(name = "enum_property") @XNullable var enumProperty: XnullableRequiredTypeResponses.EnumPropertyEnum? = null, - @Json(name = "integer_property") @field:Json(name = "integer_property") @XNullable var integerProperty: Int? = null, - @Json(name = "number_property") @field:Json(name = "number_property") @XNullable var numberProperty: BigDecimal? = null, - @Json(name = "string_property") @field:Json(name = "string_property") @XNullable var stringProperty: String? = null + @SerialName("boolean_property") @XNullable var booleanProperty: Boolean? = null, + @SerialName("enum_property") @XNullable var enumProperty: XnullableRequiredTypeResponses.EnumPropertyEnum? = null, + @SerialName("integer_property") @XNullable var integerProperty: Int? = null, + @SerialName("number_property") @XNullable var numberProperty: BigDecimal? = null, + @SerialName("string_property") @XNullable var stringProperty: String? = null + ) { - /** - * Values: VALUE1, VALUE2 - */ - @JsonClass(generateAdapter = false) - enum class EnumPropertyEnum(val value: String) { - @Json(name = "VALUE1") VALUE1("VALUE1"), - @Json(name = "VALUE2") VALUE2("VALUE2") - } + /** + * Values: VALUE1, VALUE2 + */ + @Serializable + enum class EnumPropertyEnum(val value: String) { + VALUE1("VALUE1"), + VALUE2("VALUE2") + } } diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullableTypeResponses.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullableTypeResponses.kt index 0a693c92..ff0e0cdf 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullableTypeResponses.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/models/XnullableTypeResponses.kt @@ -1,14 +1,14 @@ /** * NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: JUnit Tests - * + * API Version: 1.1.0 * More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen */ package com.yelp.codegen.generatecodesamples.models -import com.squareup.moshi.Json -import com.squareup.moshi.JsonClass import com.yelp.codegen.generatecodesamples.tools.XNullable +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable import java.math.BigDecimal /** @@ -18,20 +18,21 @@ import java.math.BigDecimal * @property numberProperty * @property stringProperty */ -@JsonClass(generateAdapter = true) +@Serializable data class XnullableTypeResponses( - @Json(name = "boolean_property") @field:Json(name = "boolean_property") @XNullable var booleanProperty: Boolean? = null, - @Json(name = "enum_property") @field:Json(name = "enum_property") @XNullable var enumProperty: XnullableTypeResponses.EnumPropertyEnum? = null, - @Json(name = "integer_property") @field:Json(name = "integer_property") @XNullable var integerProperty: Int? = null, - @Json(name = "number_property") @field:Json(name = "number_property") @XNullable var numberProperty: BigDecimal? = null, - @Json(name = "string_property") @field:Json(name = "string_property") @XNullable var stringProperty: String? = null + @SerialName("boolean_property") @XNullable var booleanProperty: Boolean? = null, + @SerialName("enum_property") @XNullable var enumProperty: XnullableTypeResponses.EnumPropertyEnum? = null, + @SerialName("integer_property") @XNullable var integerProperty: Int? = null, + @SerialName("number_property") @XNullable var numberProperty: BigDecimal? = null, + @SerialName("string_property") @XNullable var stringProperty: String? = null + ) { - /** - * Values: VALUE1, VALUE2 - */ - @JsonClass(generateAdapter = false) - enum class EnumPropertyEnum(val value: String) { - @Json(name = "VALUE1") VALUE1("VALUE1"), - @Json(name = "VALUE2") VALUE2("VALUE2") - } + /** + * Values: VALUE1, VALUE2 + */ + @Serializable + enum class EnumPropertyEnum(val value: String) { + VALUE1("VALUE1"), + VALUE2("VALUE2") + } } diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/tools/CollectionFormatConverterFactory.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/tools/CollectionFormatConverterFactory.kt index 679552b9..b984113d 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/tools/CollectionFormatConverterFactory.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/tools/CollectionFormatConverterFactory.kt @@ -6,27 +6,27 @@ import java.lang.reflect.Type internal class CollectionFormatConverterFactory : Converter.Factory() { - override fun stringConverter(type: Type, annotations: Array, retrofit: Retrofit): Converter<*, String>? { - val rawType = getRawType(type) - if (rawType == String::class.java || rawType == List::class.java) - annotations.forEach { - when (it) { - is CSV -> return CollectionFormatConverter(",") - is SSV -> return CollectionFormatConverter(" ") - is TSV -> return CollectionFormatConverter("\t") - is PIPES -> return CollectionFormatConverter("|") - } - } - return null - } - - private class CollectionFormatConverter(private val separator: String) : Converter { - override fun convert(value: Any): String { - when (value) { - is String -> return value - is List<*> -> return value.joinToString(separator) - } - throw RuntimeException("Unsupported type") + override fun stringConverter(type: Type, annotations: Array, retrofit: Retrofit): Converter<*, String>? { + val rawType = getRawType(type) + if (rawType == String::class.java || rawType == List::class.java) + annotations.forEach { + when (it) { + is CSV -> return CollectionFormatConverter(",") + is SSV -> return CollectionFormatConverter(" ") + is TSV -> return CollectionFormatConverter("\t") + is PIPES -> return CollectionFormatConverter("|") } + } + return null + } + + private class CollectionFormatConverter(private val separator: String) : Converter { + override fun convert(value: Any): String { + when (value) { + is String -> return value + is List<*> -> return value.joinToString(separator) + } + throw RuntimeException("Unsupported type") } + } } diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/tools/EnumToValueConverterFactory.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/tools/EnumToValueConverterFactory.kt index 9d2571c5..c55da60a 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/tools/EnumToValueConverterFactory.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/tools/EnumToValueConverterFactory.kt @@ -7,28 +7,28 @@ import java.lang.reflect.Type internal class EnumToValueConverterFactory : Converter.Factory() { - private val enumConverter = EnumToValueConverter() + private val enumConverter = EnumToValueConverter() - override fun stringConverter(type: Type, annotations: Array, retrofit: Retrofit): Converter<*, String>? { - return if (type is Class<*> && type.isEnum) { - enumConverter - } else { - null - } + override fun stringConverter(type: Type, annotations: Array, retrofit: Retrofit): Converter<*, String>? { + return if (type is Class<*> && type.isEnum) { + enumConverter + } else { + null } + } - internal class EnumToValueConverter : Converter { - override fun convert(enum: Any): String? { - val enumName = (enum as Enum<*>).name - val jsonAnnotation: Json? = enum.javaClass.getField(enumName).getAnnotation(Json::class.java) + internal class EnumToValueConverter : Converter { + override fun convert(enum: Any): String? { + val enumName = (enum as Enum<*>).name + val jsonAnnotation: Json? = enum.javaClass.getField(enumName).getAnnotation(Json::class.java) - // Checking if the Enum is annotated with @Json to get the name. - // If not, fallback to enum default (.toString()) - return if (jsonAnnotation != null) { - jsonAnnotation.name - } else { - enum.toString() - } - } + // Checking if the Enum is annotated with @Json to get the name. + // If not, fallback to enum default (.toString()) + return if (jsonAnnotation != null) { + jsonAnnotation.name + } else { + enum.toString() + } } + } } diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/tools/GeneratedCodeConverters.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/tools/GeneratedCodeConverters.kt index 09ef3b3b..99821c4f 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/tools/GeneratedCodeConverters.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/tools/GeneratedCodeConverters.kt @@ -5,32 +5,32 @@ import retrofit2.Converter import retrofit2.converter.moshi.MoshiConverterFactory object GeneratedCodeConverters { - private val moshi = Moshi.Builder() - .add(XNullableAdapterFactory()) - .add(TypesAdapterFactory()) - .build() + private val moshi = Moshi.Builder() + .add(XNullableAdapterFactory()) + .add(TypesAdapterFactory()) + .build() - /** - * Creates everything needed for retrofit to make it work with the client lib, including a - * [Moshi] instance. If you want to use your own instance of moshi, use - * converterFactory(moshi) instead, and add [XNullableAdapterFactory], [KotlinJsonAdapterFactory] and - * [TypesAdapterFactory] to your moshi builder (in a similar way how we are instantiating the `moshi` field here). - */ - @JvmStatic - fun converterFactory(): Converter.Factory { - return WrapperConverterFactory( - CollectionFormatConverterFactory(), - EnumToValueConverterFactory(), - MoshiConverterFactory.create(moshi) - ) - } + /** + * Creates everything needed for retrofit to make it work with the client lib, including a + * [Moshi] instance. If you want to use your own instance of moshi, use + * converterFactory(moshi) instead, and add [XNullableAdapterFactory], [KotlinJsonAdapterFactory] and + * [TypesAdapterFactory] to your moshi builder (in a similar way how we are instantiating the `moshi` field here). + */ + @JvmStatic + fun converterFactory(): Converter.Factory { + return WrapperConverterFactory( + CollectionFormatConverterFactory(), + EnumToValueConverterFactory(), + MoshiConverterFactory.create(moshi) + ) + } - @JvmStatic - fun converterFactory(moshi: Moshi): Converter.Factory { - return WrapperConverterFactory( - CollectionFormatConverterFactory(), - EnumToValueConverterFactory(), - MoshiConverterFactory.create(moshi) - ) - } + @JvmStatic + fun converterFactory(moshi: Moshi): Converter.Factory { + return WrapperConverterFactory( + CollectionFormatConverterFactory(), + EnumToValueConverterFactory(), + MoshiConverterFactory.create(moshi) + ) + } } diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/tools/TypesAdapters.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/tools/TypesAdapters.kt index 8a647e32..00975121 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/tools/TypesAdapters.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/tools/TypesAdapters.kt @@ -19,20 +19,20 @@ import java.math.BigDecimal * such as [LocalDate], [ZonedDateTime], [BigDecimal]. */ class TypesAdapterFactory : JsonAdapter.Factory { - private val types = mapOf>( - LocalDate::class.java to LocalDateAdapter(), - ZonedDateTime::class.java to ZonedDateTimeAdapter(), - BigDecimal::class.java to BigDecimalJsonAdapter() - ) + private val types = mapOf>( + LocalDate::class.java to LocalDateAdapter(), + ZonedDateTime::class.java to ZonedDateTimeAdapter(), + BigDecimal::class.java to BigDecimalJsonAdapter() + ) - override fun create(type: Type, annotations: MutableSet, moshi: Moshi): JsonAdapter<*>? { - if (annotations.isEmpty()) { - for (targetType in types.keys) { - if (Util.typesMatch(type, targetType)) return types[targetType] - } - } - return null + override fun create(type: Type, annotations: MutableSet, moshi: Moshi): JsonAdapter<*>? { + if (annotations.isEmpty()) { + for (targetType in types.keys) { + if (Util.typesMatch(type, targetType)) return types[targetType] + } } + return null + } } /** @@ -42,49 +42,49 @@ class TypesAdapterFactory : JsonAdapter.Factory { */ internal abstract class XNullableJsonAdapter : JsonAdapter() { - abstract fun fromNonNullString(nextString: String): T + abstract fun fromNonNullString(nextString: String): T - override fun fromJson(reader: JsonReader): T? { - return if (reader.peek() != JsonReader.Token.NULL) { - fromNonNullString(reader.nextString()) - } else { - reader.nextNull() - null - } + override fun fromJson(reader: JsonReader): T? { + return if (reader.peek() != JsonReader.Token.NULL) { + fromNonNullString(reader.nextString()) + } else { + reader.nextNull() + null } + } } internal class LocalDateAdapter : XNullableJsonAdapter() { - private val formatter = DateTimeFormatter.ISO_LOCAL_DATE + private val formatter = DateTimeFormatter.ISO_LOCAL_DATE - override fun fromNonNullString(nextString: String): LocalDate = LocalDate.parse(nextString, formatter) + override fun fromNonNullString(nextString: String): LocalDate = LocalDate.parse(nextString, formatter) - override fun toJson(writer: JsonWriter, value: LocalDate?) { - value?.let { writer.value(it.format(formatter)) } - } + override fun toJson(writer: JsonWriter, value: LocalDate?) { + value?.let { writer.value(it.format(formatter)) } + } } internal class ZonedDateTimeAdapter : XNullableJsonAdapter() { - private val formatter = DateTimeFormatter.ISO_DATE_TIME + private val formatter = DateTimeFormatter.ISO_DATE_TIME - override fun fromNonNullString(nextString: String): ZonedDateTime { - return try { - ZonedDateTime.parse(nextString, formatter) - } catch (parseException: DateTimeException) { - val localDateTime = LocalDateTime.parse(nextString, formatter) - localDateTime.atZone(ZoneId.of("Z")) - } + override fun fromNonNullString(nextString: String): ZonedDateTime { + return try { + ZonedDateTime.parse(nextString, formatter) + } catch (parseException: DateTimeException) { + val localDateTime = LocalDateTime.parse(nextString, formatter) + localDateTime.atZone(ZoneId.of("Z")) } + } - override fun toJson(writer: JsonWriter, value: ZonedDateTime?) { - value?.let { writer.value(it.format(formatter)) } - } + override fun toJson(writer: JsonWriter, value: ZonedDateTime?) { + value?.let { writer.value(it.format(formatter)) } + } } internal class BigDecimalJsonAdapter : XNullableJsonAdapter() { - override fun fromNonNullString(nextString: String) = BigDecimal(nextString) + override fun fromNonNullString(nextString: String) = BigDecimal(nextString) - override fun toJson(writer: JsonWriter, value: BigDecimal?) { - value?.let { writer.value(it) } - } + override fun toJson(writer: JsonWriter, value: BigDecimal?) { + value?.let { writer.value(it) } + } } diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/tools/WrapperConverterFactory.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/tools/WrapperConverterFactory.kt index 87c2ef16..f88d0cbb 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/tools/WrapperConverterFactory.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/tools/WrapperConverterFactory.kt @@ -8,44 +8,44 @@ import java.lang.reflect.Type internal class WrapperConverterFactory(private vararg val factories: Converter.Factory) : Converter.Factory() { - override fun responseBodyConverter( - type: Type, - annotations: Array, - retrofit: Retrofit - ): Converter? { - return factories.mapFirstNonNull { - it.responseBodyConverter(type, annotations, retrofit) - } + override fun responseBodyConverter( + type: Type, + annotations: Array, + retrofit: Retrofit + ): Converter? { + return factories.mapFirstNonNull { + it.responseBodyConverter(type, annotations, retrofit) } + } - override fun requestBodyConverter( - type: Type, - parameterAnnotations: Array, - methodAnnotations: Array, - retrofit: Retrofit - ): Converter<*, RequestBody>? { - return factories.mapFirstNonNull { - it.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit) - } + override fun requestBodyConverter( + type: Type, + parameterAnnotations: Array, + methodAnnotations: Array, + retrofit: Retrofit + ): Converter<*, RequestBody>? { + return factories.mapFirstNonNull { + it.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit) } + } - override fun stringConverter( - type: Type, - annotations: Array, - retrofit: Retrofit - ): Converter<*, String>? { - return factories.mapFirstNonNull { - it.stringConverter(type, annotations, retrofit) - } + override fun stringConverter( + type: Type, + annotations: Array, + retrofit: Retrofit + ): Converter<*, String>? { + return factories.mapFirstNonNull { + it.stringConverter(type, annotations, retrofit) } + } - private inline fun Array.mapFirstNonNull(transform: (T) -> R?): R? { - for (element in this) { - val transformed = transform(element) - if (transformed != null) { - return transformed - } - } - return null + private inline fun Array.mapFirstNonNull(transform: (T) -> R?): R? { + for (element in this) { + val transformed = transform(element) + if (transformed != null) { + return transformed + } } + return null + } } diff --git a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/tools/XNullableAdapterFactory.kt b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/tools/XNullableAdapterFactory.kt index f577d042..80c0744e 100644 --- a/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/tools/XNullableAdapterFactory.kt +++ b/samples/junit-tests/src/main/java/com/yelp/codegen/generatecodesamples/tools/XNullableAdapterFactory.kt @@ -7,43 +7,43 @@ import com.squareup.moshi.Moshi import java.lang.reflect.Type class XNullableAdapterFactory : JsonAdapter.Factory { - override fun create(type: Type, annotations: MutableSet, moshi: Moshi): JsonAdapter<*>? { - if (annotations.any { it is XNullable }) { - return object : JsonAdapter() { - override fun fromJson(reader: JsonReader): Any? { - return if (reader.peek() != JsonReader.Token.NULL) { - val nextAdapter = moshi.nextAdapter( - this@XNullableAdapterFactory, - type, - annotations.removeXNullableAnnotation() - ) - nextAdapter?.fromJson(reader) - } else { - reader.nextNull() - } - } + override fun create(type: Type, annotations: MutableSet, moshi: Moshi): JsonAdapter<*>? { + if (annotations.any { it is XNullable }) { + return object : JsonAdapter() { + override fun fromJson(reader: JsonReader): Any? { + return if (reader.peek() != JsonReader.Token.NULL) { + val nextAdapter = moshi.nextAdapter( + this@XNullableAdapterFactory, + type, + annotations.removeXNullableAnnotation() + ) + nextAdapter?.fromJson(reader) + } else { + reader.nextNull() + } + } - override fun toJson(writer: JsonWriter, value: Any?) { - if (value == null) { - val serializeNulls = writer.serializeNulls - writer.serializeNulls = true - writer.nullValue() - writer.serializeNulls = serializeNulls - } else { - val nextAdapter = moshi.nextAdapter( - this@XNullableAdapterFactory, - type, - annotations.removeXNullableAnnotation() - ) - nextAdapter?.toJson(writer, value) - } - } - } + override fun toJson(writer: JsonWriter, value: Any?) { + if (value == null) { + val serializeNulls = writer.serializeNulls + writer.serializeNulls = true + writer.nullValue() + writer.serializeNulls = serializeNulls + } else { + val nextAdapter = moshi.nextAdapter( + this@XNullableAdapterFactory, + type, + annotations.removeXNullableAnnotation() + ) + nextAdapter?.toJson(writer, value) + } } - return null + } } + return null + } - private fun Set.removeXNullableAnnotation(): MutableSet { - return this.filter { it !is XNullable }.toMutableSet() - } + private fun Set.removeXNullableAnnotation(): MutableSet { + return this.filter { it !is XNullable }.toMutableSet() + } } diff --git a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/EmptyEndpointTest.kt b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/EmptyEndpointTest.kt index 8d1ad4fe..b42aa20d 100644 --- a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/EmptyEndpointTest.kt +++ b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/EmptyEndpointTest.kt @@ -9,14 +9,14 @@ import org.junit.Test class EmptyEndpointTest { - @get:Rule - val mockServerRule = MockServerApiRule() + @get:Rule + val mockServerRule = MockServerApiRule() - @Test - fun emptyEndpointTest_withEmptyBody() { - mockServerRule.server.enqueue(MockResponse().setBody("{}")) + @Test + fun emptyEndpointTest_withEmptyBody() { + mockServerRule.server.enqueue(MockResponse().setBody("{}")) - val returned = mockServerRule.getApi().getEmptyEndpoint().blockingGet() - assertNotNull(returned) - } + val returned = mockServerRule.getApi().getEmptyEndpoint().blockingGet() + assertNotNull(returned) + } } diff --git a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/FormatEndpointTest.kt b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/FormatEndpointTest.kt index 1cb5f9fa..74274ead 100644 --- a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/FormatEndpointTest.kt +++ b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/FormatEndpointTest.kt @@ -13,105 +13,105 @@ import org.threeten.bp.ZonedDateTime class FormatEndpointTest { - @get:Rule - val rule = MockServerApiRule() + @get:Rule + val rule = MockServerApiRule() - @Test - fun formatEndpoint_withEnumFormat() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun formatEndpoint_withEnumFormat() { + rule.server.enqueue( + MockResponse().setBody( + """ { "enum_property": "VALUE1" } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getFormatEndpoint("enum").blockingGet() - assertEquals(FormatResponses.EnumPropertyEnum.VALUE1, returned.enumProperty) - } + val returned = rule.getApi().getFormatEndpoint("enum").blockingGet() + assertEquals(FormatResponses.EnumPropertyEnum.VALUE1, returned.enumProperty) + } - @Test - fun formatEndpoint_withDateFormat() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun formatEndpoint_withDateFormat() { + rule.server.enqueue( + MockResponse().setBody( + """ { "date_property": "1970-01-01" } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getFormatEndpoint("date").blockingGet() - assertEquals(LocalDate.of(1970, 1, 1), returned.dateProperty) - } + val returned = rule.getApi().getFormatEndpoint("date").blockingGet() + assertEquals(LocalDate.of(1970, 1, 1), returned.dateProperty) + } - @Test - fun formatEndpoint_withDateTimeAndTimezoneFormat() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun formatEndpoint_withDateTimeAndTimezoneFormat() { + rule.server.enqueue( + MockResponse().setBody( + """ { "datetime_property": "1970-01-01T00:00:00+01:00" } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getFormatEndpoint("datetime_with_timezone").blockingGet() - assertEquals(ZonedDateTime.of(1970, 1, 1, 0, 0, 0, 0, ZoneId.of("+01:00")), returned.datetimeProperty) - } + val returned = rule.getApi().getFormatEndpoint("datetime_with_timezone").blockingGet() + assertEquals(ZonedDateTime.of(1970, 1, 1, 0, 0, 0, 0, ZoneId.of("+01:00")), returned.datetimeProperty) + } - @Test - fun formatEndpoint_withDateTimeAndUtcFormat() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun formatEndpoint_withDateTimeAndUtcFormat() { + rule.server.enqueue( + MockResponse().setBody( + """ { "datetime_property": "1970-01-01T00:00:00Z" } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getFormatEndpoint("datetime_with_utc").blockingGet() - assertEquals(ZonedDateTime.of(1970, 1, 1, 0, 0, 0, 0, ZoneId.of("Z")), returned.datetimeProperty) - } + val returned = rule.getApi().getFormatEndpoint("datetime_with_utc").blockingGet() + assertEquals(ZonedDateTime.of(1970, 1, 1, 0, 0, 0, 0, ZoneId.of("Z")), returned.datetimeProperty) + } - @Test - fun formatEndpoint_withDateTimeFractionalAndTimezoneFormat() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun formatEndpoint_withDateTimeFractionalAndTimezoneFormat() { + rule.server.enqueue( + MockResponse().setBody( + """ { "datetime_property": "1970-01-01T00:00:00.01+01:00" } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - // 10000000 nanoseconds == 0.01 seconds. - val returned = rule.getApi() - .getFormatEndpoint("datetime_with_fractionalsec_and_timezone").blockingGet() - assertEquals(ZonedDateTime.of(1970, 1, 1, 0, 0, 0, 10000000, ZoneId.of("+01:00")), returned.datetimeProperty) - } + // 10000000 nanoseconds == 0.01 seconds. + val returned = rule.getApi() + .getFormatEndpoint("datetime_with_fractionalsec_and_timezone").blockingGet() + assertEquals(ZonedDateTime.of(1970, 1, 1, 0, 0, 0, 10000000, ZoneId.of("+01:00")), returned.datetimeProperty) + } - @Test - fun formatEndpoint_withDateTimeFractionalAndUtcFormat() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun formatEndpoint_withDateTimeFractionalAndUtcFormat() { + rule.server.enqueue( + MockResponse().setBody( + """ { "datetime_property": "1970-01-01T00:00:00.01Z" } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - // 10000000 nanoseconds == 0.01 seconds. - val returned = rule.getApi().getFormatEndpoint("datetime_with_fractionalsec_and_utc").blockingGet() - assertEquals(ZonedDateTime.of(1970, 1, 1, 0, 0, 0, 10000000, ZoneId.of("Z")), returned.datetimeProperty) - } + // 10000000 nanoseconds == 0.01 seconds. + val returned = rule.getApi().getFormatEndpoint("datetime_with_fractionalsec_and_utc").blockingGet() + assertEquals(ZonedDateTime.of(1970, 1, 1, 0, 0, 0, 10000000, ZoneId.of("Z")), returned.datetimeProperty) + } } diff --git a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/ModelNameCheckEndpointTest.kt b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/ModelNameCheckEndpointTest.kt index e57830ba..3038c1a8 100644 --- a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/ModelNameCheckEndpointTest.kt +++ b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/ModelNameCheckEndpointTest.kt @@ -13,54 +13,57 @@ import org.junit.Test class ModelNameCheckEndpointTest { - @get:Rule - val rule = MockServerApiRule() + @get:Rule + val rule = MockServerApiRule() - @Test - fun getInlinedModelWithNoNames() { - rule.server.enqueue(MockResponse().setBody("{}")) + @Test + fun getInlinedModelWithNoNames() { + rule.server.enqueue(MockResponse().setBody("{}")) - val returned = rule.getApi().getInlinedModelWithNoNames().blockingGet() - assertTrue( - // We're not running instance-check or equality with the object (as done on the other tests) - // because the model name is generated by codegen, and so changes into the junit_tests_specs.json - // file might cause failure of this test. - // Checking that the returned class has a name, kinda similar, to what we expect should be fine - // as changes to the specific endpoint (like adding title/x-model) are ok to break this test - // and as codegen generates the name as inline_reponse_(_) - checkNotNull(returned::class.qualifiedName).startsWith( - "com.yelp.codegen.generatecodesamples.models.InlineResponse200" - ) - ) - } + val returned = rule.getApi().getInlinedModelWithNoNames().blockingGet() + assertTrue( + // We're not running instance-check or equality with the object (as done on the other tests) + // because the model name is generated by codegen, and so changes into the junit_tests_specs.json + // file might cause failure of this test. + // Checking that the returned class has a name, kinda similar, to what we expect should be fine + // as changes to the specific endpoint (like adding title/x-model) are ok to break this test + // and as codegen generates the name as inline_reponse_(_) + checkNotNull(returned::class.qualifiedName).startsWith( + "com.yelp.codegen.generatecodesamples.models.InlineResponse200" + ) + ) + } - @Test - fun getInlinedModelWithTitleOnly() { - rule.server.enqueue(MockResponse().setBody("{\"title_only\": \"val1\"}")) + @Test + fun getInlinedModelWithTitleOnly() { + rule.server.enqueue( + MockResponse() + .setBody("{\"title_only\": \"val1\"}") + ) - val returned = rule.getApi().getInlinedModelWithTitleOnly().blockingGet() + val returned = rule.getApi().getInlinedModelWithTitleOnly().blockingGet() - assertEquals(returned, ModelWithOnlyTitle(titleOnly = ModelWithOnlyTitle.TitleOnlyEnum.VAL1)) - } + assertEquals(returned, ModelWithOnlyTitle(titleOnly = ModelWithOnlyTitle.TitleOnlyEnum.VAL1)) + } - @Test - fun getInlinedModelWithXModelAndTitle() { - rule.server.enqueue(MockResponse().setBody("{\"xmodel_and_title\": \"val1\"}")) + @Test + fun getInlinedModelWithXModelAndTitle() { + rule.server.enqueue(MockResponse().setBody("{\"xmodel_and_title\": \"val1\"}")) - val returned = rule.getApi().getInlinedModelWithXModelAndTitle().blockingGet() + val returned = rule.getApi().getInlinedModelWithXModelAndTitle().blockingGet() - assertEquals( - returned, - ModelWithXModelAndTitle(xmodelAndTitle = ModelWithXModelAndTitle.XmodelAndTitleEnum.VAL1) - ) - } + assertEquals( + returned, + ModelWithXModelAndTitle(xmodelAndTitle = ModelWithXModelAndTitle.XmodelAndTitleEnum.VAL1) + ) + } - @Test - fun getInlinedModelWithXModelOnly() { - rule.server.enqueue(MockResponse().setBody("{\"xmodel_only\": \"val1\"}")) + @Test + fun getInlinedModelWithXModelOnly() { + rule.server.enqueue(MockResponse().setBody("{\"xmodel_only\": \"val1\"}")) - val returned = rule.getApi().getInlinedModelWithXModelOnly().blockingGet() + val returned = rule.getApi().getInlinedModelWithXModelOnly().blockingGet() - assertEquals(returned, ModelWithOnlyXModel(xmodelOnly = ModelWithOnlyXModel.XmodelOnlyEnum.VAL1)) - } + assertEquals(returned, ModelWithOnlyXModel(xmodelOnly = ModelWithOnlyXModel.XmodelOnlyEnum.VAL1)) + } } diff --git a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/NestedAdditionalPropertiesCustomDescriptionTest.kt b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/NestedAdditionalPropertiesCustomDescriptionTest.kt index 84a747dd..e4902673 100644 --- a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/NestedAdditionalPropertiesCustomDescriptionTest.kt +++ b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/NestedAdditionalPropertiesCustomDescriptionTest.kt @@ -12,14 +12,14 @@ import org.junit.Test class NestedAdditionalPropertiesCustomDescriptionTest { - @get:Rule - val rule = MockServerApiRule() - - @Test - fun nestedAdditionalProperties() { - rule.server.enqueue( - MockResponse().setBody( - """ + @get:Rule + val rule = MockServerApiRule() + + @Test + fun nestedAdditionalProperties() { + rule.server.enqueue( + MockResponse().setBody( + """ { "key1": { "subkey1": "subvalue1", @@ -30,28 +30,28 @@ class NestedAdditionalPropertiesCustomDescriptionTest { }, "key3": {} } - """.trimIndent() - ) - ) - - val returned = rule.getApi().getNestedAdditionalProperties().blockingGet() - - assertFalse(returned.isEmpty()) - - // Check that size are correct - assertEquals(3, returned.keys.size) - assertEquals(2, returned["key1"]?.keys?.size) - assertEquals(1, returned["key2"]?.keys?.size) - assertEquals(0, returned["key3"]?.keys?.size) - - // Check that sizes are mapped correctly - assertTrue(returned["key1"] is TopLevelMap) - assertTrue(returned["key2"] is TopLevelMap) - assertTrue(returned["key3"] is TopLevelMap) - - // Check that values are correct - assertEquals("subvalue1", returned["key1"]?.get("subkey1")) - assertEquals("subvalue2", returned["key1"]?.get("subkey2")) - assertEquals("subvalue1", returned["key2"]?.get("subkey1")) - } + """.trimIndent() + ) + ) + + val returned = rule.getApi().getNestedAdditionalProperties().blockingGet() + + assertFalse(returned.isEmpty()) + + // Check that size are correct + assertEquals(3, returned.keys.size) + assertEquals(2, returned["key1"]?.keys?.size) + assertEquals(1, returned["key2"]?.keys?.size) + assertEquals(0, returned["key3"]?.keys?.size) + + // Check that sizes are mapped correctly + assertTrue(returned["key1"] is TopLevelMap) + assertTrue(returned["key2"] is TopLevelMap) + assertTrue(returned["key3"] is TopLevelMap) + + // Check that values are correct + assertEquals("subvalue1", returned["key1"]?.get("subkey1")) + assertEquals("subvalue2", returned["key1"]?.get("subkey2")) + assertEquals("subvalue1", returned["key2"]?.get("subkey1")) + } } diff --git a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/NestedAdditionalPropertiesEndpointTest.kt b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/NestedAdditionalPropertiesEndpointTest.kt index 487aa4cc..b4b2dc7c 100644 --- a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/NestedAdditionalPropertiesEndpointTest.kt +++ b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/NestedAdditionalPropertiesEndpointTest.kt @@ -12,14 +12,14 @@ import org.junit.Test class NestedAdditionalPropertiesEndpointTest { - @get:Rule - val rule = MockServerApiRule() - - @Test - fun nestedAdditionalProperties() { - rule.server.enqueue( - MockResponse().setBody( - """ + @get:Rule + val rule = MockServerApiRule() + + @Test + fun nestedAdditionalProperties() { + rule.server.enqueue( + MockResponse().setBody( + """ { "key1": { "subkey1": "subvalue1", @@ -30,28 +30,28 @@ class NestedAdditionalPropertiesEndpointTest { }, "key3": {} } - """.trimIndent() - ) - ) - - val returned = rule.getApi().getNestedAdditionalProperties().blockingGet() - - assertFalse(returned.isEmpty()) - - // Check that size are correct - assertEquals(3, returned.keys.size) - assertEquals(2, returned["key1"]?.keys?.size) - assertEquals(1, returned["key2"]?.keys?.size) - assertEquals(0, returned["key3"]?.keys?.size) - - // Check that sizes are mapped correctly - assertTrue(returned["key1"] is TopLevelMap) - assertTrue(returned["key2"] is TopLevelMap) - assertTrue(returned["key3"] is TopLevelMap) - - // Check that values are correct - assertEquals("subvalue1", returned["key1"]?.get("subkey1")) - assertEquals("subvalue2", returned["key1"]?.get("subkey2")) - assertEquals("subvalue1", returned["key2"]?.get("subkey1")) - } + """.trimIndent() + ) + ) + + val returned = rule.getApi().getNestedAdditionalProperties().blockingGet() + + assertFalse(returned.isEmpty()) + + // Check that size are correct + assertEquals(3, returned.keys.size) + assertEquals(2, returned["key1"]?.keys?.size) + assertEquals(1, returned["key2"]?.keys?.size) + assertEquals(0, returned["key3"]?.keys?.size) + + // Check that sizes are mapped correctly + assertTrue(returned["key1"] is TopLevelMap) + assertTrue(returned["key2"] is TopLevelMap) + assertTrue(returned["key3"] is TopLevelMap) + + // Check that values are correct + assertEquals("subvalue1", returned["key1"]?.get("subkey1")) + assertEquals("subvalue2", returned["key1"]?.get("subkey2")) + assertEquals("subvalue1", returned["key2"]?.get("subkey1")) + } } diff --git a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/PostFileEndpointTest.kt b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/PostFileEndpointTest.kt index bee36485..a37edd31 100644 --- a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/PostFileEndpointTest.kt +++ b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/PostFileEndpointTest.kt @@ -15,69 +15,69 @@ import org.junit.Test class PostFileEndpointTest { - @get:Rule - val rule = MockServerApiRule() + @get:Rule + val rule = MockServerApiRule() - @Test - fun sendFileTest() { - rule.server.enqueue(MockResponse()) + @Test + fun sendFileTest() { + rule.server.enqueue(MockResponse()) - rule.getApi().postFile( - clientFile = RequestBody.create(MediaType.parse("application/json"), "{}") - ).blockingGet() + rule.getApi().postFile( + clientFile = RequestBody.create(MediaType.parse("application/json"), "{}") + ).blockingGet() - val fileApiStats = rule.server.takeRequest().decodeMultiPartBody() - assertNotNull(fileApiStats.boundary) - assertEquals( - listOf( - MultiPartInfo( - contentDisposition = "form-data; name=\"client_file\"; filename=\"client_file\"", - contentType = "application/json; charset=utf-8", - contentLength = "2", - fileContent = "{}" - ) - ), - fileApiStats.parts + val fileApiStats = rule.server.takeRequest().decodeMultiPartBody() + assertNotNull(fileApiStats.boundary) + assertEquals( + listOf( + MultiPartInfo( + contentDisposition = "form-data; name=\"client_file\"; filename=\"client_file\"", + contentType = "application/json; charset=utf-8", + contentLength = "2", + fileContent = "{}" ) - } + ), + fileApiStats.parts + ) + } - @Test - fun sendMultipleFilesTest() { - rule.server.enqueue(MockResponse()) + @Test + fun sendMultipleFilesTest() { + rule.server.enqueue(MockResponse()) - rule.getApi().postMultipleFiles( - clientFile = RequestBody.create(MediaType.parse("application/json"), "{}"), - certificateFile = RequestBody.create(MediaType.parse("text/plain"), "Some Text") - ).blockingGet() + rule.getApi().postMultipleFiles( + clientFile = RequestBody.create(MediaType.parse("application/json"), "{}"), + certificateFile = RequestBody.create(MediaType.parse("text/plain"), "Some Text") + ).blockingGet() - val fileApiStats = rule.server.takeRequest().decodeMultiPartBody() - assertNotNull(fileApiStats.boundary) - assertEquals( - listOf( - MultiPartInfo( - contentDisposition = "form-data; name=\"client_file\"; filename=\"client_file\"", - contentType = "application/json; charset=utf-8", - contentLength = "2", - fileContent = "{}" - ), - MultiPartInfo( - contentDisposition = "form-data; name=\"certificate_file\"; filename=\"certificate_file\"", - contentType = "text/plain; charset=utf-8", - contentLength = "9", - fileContent = "Some Text" - ) - ), - fileApiStats.parts + val fileApiStats = rule.server.takeRequest().decodeMultiPartBody() + assertNotNull(fileApiStats.boundary) + assertEquals( + listOf( + MultiPartInfo( + contentDisposition = "form-data; name=\"client_file\"; filename=\"client_file\"", + contentType = "application/json; charset=utf-8", + contentLength = "2", + fileContent = "{}" + ), + MultiPartInfo( + contentDisposition = "form-data; name=\"certificate_file\"; filename=\"certificate_file\"", + contentType = "text/plain; charset=utf-8", + contentLength = "9", + fileContent = "Some Text" ) - } + ), + fileApiStats.parts + ) + } - @Test - fun ensureThatEndpointsWithFileAndNotMultipartFormDataAreMarkedAsDeprecated() { - assertTrue( - FileApi::class.java.methods - .first { it.name == "postFileWithoutMultipartFormData" } - .getAnnotationsByType(Deprecated::class.java) - .isNotEmpty() - ) - } + @Test + fun ensureThatEndpointsWithFileAndNotMultipartFormDataAreMarkedAsDeprecated() { + assertTrue( + FileApi::class.java.methods + .first { it.name == "postFileWithoutMultipartFormData" } + .getAnnotationsByType(Deprecated::class.java) + .isNotEmpty() + ) + } } diff --git a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/PropertyArrayEndpointTest.kt b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/PropertyArrayEndpointTest.kt index 19ddedaf..f47d799f 100644 --- a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/PropertyArrayEndpointTest.kt +++ b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/PropertyArrayEndpointTest.kt @@ -12,96 +12,96 @@ import org.junit.Test class PropertyArrayEndpointTest { - @get:Rule - val rule = MockServerApiRule() - - @Test - fun propertyArray_withEmptyString() { - rule.server.enqueue( - MockResponse().setBody( - """ + @get:Rule + val rule = MockServerApiRule() + + @Test + fun propertyArray_withEmptyString() { + rule.server.enqueue( + MockResponse().setBody( + """ { "string_array": [] } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getPropertyArray("string", "empty").blockingGet() + val returned = rule.getApi().getPropertyArray("string", "empty").blockingGet() - assertNull(returned.numberArray) - assertNotNull(returned.stringArray) + assertNull(returned.numberArray) + assertNotNull(returned.stringArray) - assertTrue(returned.stringArray?.isEmpty()!!) - } + assertTrue(returned.stringArray?.isEmpty()!!) + } - @Test - fun propertyArray_withEmptyNumber() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun propertyArray_withEmptyNumber() { + rule.server.enqueue( + MockResponse().setBody( + """ { "number_array": [] } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getPropertyArray("number", "empty").blockingGet() + val returned = rule.getApi().getPropertyArray("number", "empty").blockingGet() - assertNull(returned.stringArray) - assertNotNull(returned.numberArray) + assertNull(returned.stringArray) + assertNotNull(returned.numberArray) - assertTrue(returned.numberArray?.isEmpty()!!) - } + assertTrue(returned.numberArray?.isEmpty()!!) + } - @Test - fun propertyArray_withNonEmptyString() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun propertyArray_withNonEmptyString() { + rule.server.enqueue( + MockResponse().setBody( + """ { "string_array": [ "value1", "value2" ] } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getPropertyArray("string", "2").blockingGet() + val returned = rule.getApi().getPropertyArray("string", "2").blockingGet() - assertNull(returned.numberArray) - assertNotNull(returned.stringArray) + assertNull(returned.numberArray) + assertNotNull(returned.stringArray) - assertEquals(2, returned.stringArray?.size) - assertEquals("value1", returned.stringArray?.get(0)) - assertEquals("value2", returned.stringArray?.get(1)) - } + assertEquals(2, returned.stringArray?.size) + assertEquals("value1", returned.stringArray?.get(0)) + assertEquals("value2", returned.stringArray?.get(1)) + } - @Test - fun propertyArray_withNonEmptyNumber() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun propertyArray_withNonEmptyNumber() { + rule.server.enqueue( + MockResponse().setBody( + """ { "number_array": [ 1.1, 2.2 ] } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getPropertyArray("number", "2").blockingGet() + val returned = rule.getApi().getPropertyArray("number", "2").blockingGet() - assertNull(returned.stringArray) - assertNotNull(returned.numberArray) + assertNull(returned.stringArray) + assertNotNull(returned.numberArray) - assertEquals(2, returned.numberArray?.size) - assertEquals(1.1.toBigDecimal(), returned.numberArray?.get(0)) - assertEquals(2.2.toBigDecimal(), returned.numberArray?.get(1)) - } + assertEquals(2, returned.numberArray?.size) + assertEquals(1.1.toBigDecimal(), returned.numberArray?.get(0)) + assertEquals(2.2.toBigDecimal(), returned.numberArray?.get(1)) + } } diff --git a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/PropertyMapEndpointTest.kt b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/PropertyMapEndpointTest.kt index 7ae6ffa9..432a4deb 100644 --- a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/PropertyMapEndpointTest.kt +++ b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/PropertyMapEndpointTest.kt @@ -13,155 +13,155 @@ import org.junit.Test class PropertyMapEndpointTest { - @get:Rule - val rule = MockServerApiRule() - - @Test - fun propertyMap_withEmptyString() { - rule.server.enqueue( - MockResponse().setBody( - """ + @get:Rule + val rule = MockServerApiRule() + + @Test + fun propertyMap_withEmptyString() { + rule.server.enqueue( + MockResponse().setBody( + """ { "string_map": {} } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getPropertyMap("string", "empty").blockingGet() + val returned = rule.getApi().getPropertyMap("string", "empty").blockingGet() - assertNull(returned.numberMap) - assertNull(returned.objectMap) - assertNotNull(returned.stringMap) + assertNull(returned.numberMap) + assertNull(returned.objectMap) + assertNotNull(returned.stringMap) - assertTrue(returned.stringMap?.isEmpty()!!) - } + assertTrue(returned.stringMap?.isEmpty()!!) + } - @Test - fun propertyMap_withEmptyNumber() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun propertyMap_withEmptyNumber() { + rule.server.enqueue( + MockResponse().setBody( + """ { "number_map": {} } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getPropertyMap("number", "empty").blockingGet() + val returned = rule.getApi().getPropertyMap("number", "empty").blockingGet() - assertNull(returned.stringMap) - assertNull(returned.objectMap) - assertNotNull(returned.numberMap) + assertNull(returned.stringMap) + assertNull(returned.objectMap) + assertNotNull(returned.numberMap) - assertTrue(returned.numberMap?.isEmpty()!!) - } + assertTrue(returned.numberMap?.isEmpty()!!) + } - @Test - fun propertyMap_withEmptyObject() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun propertyMap_withEmptyObject() { + rule.server.enqueue( + MockResponse().setBody( + """ { "object_map": {} } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getPropertyMap("object", "empty").blockingGet() + val returned = rule.getApi().getPropertyMap("object", "empty").blockingGet() - assertNull(returned.stringMap) - assertNull(returned.numberMap) - assertNotNull(returned.objectMap) + assertNull(returned.stringMap) + assertNull(returned.numberMap) + assertNotNull(returned.objectMap) - assertTrue(returned.objectMap?.isEmpty()!!) - } + assertTrue(returned.objectMap?.isEmpty()!!) + } - @Test - fun propertyMap_withNonEmptyString() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun propertyMap_withNonEmptyString() { + rule.server.enqueue( + MockResponse().setBody( + """ { "string_map": { "key1": "value1", "key2": "value2" } } - """.trimIndent() - ) - ) - - val returned = rule.getApi().getPropertyMap("string", "2").blockingGet() - - assertNull(returned.numberMap) - assertNull(returned.objectMap) - assertNotNull(returned.stringMap) - - assertEquals(2, returned.stringMap?.size) - assertEquals("value1", returned.stringMap?.get("key1")) - assertEquals("value2", returned.stringMap?.get("key2")) - } - - @Test - fun propertyMap_withNonEmptyNumber() { - rule.server.enqueue( - MockResponse().setBody( - """ + """.trimIndent() + ) + ) + + val returned = rule.getApi().getPropertyMap("string", "2").blockingGet() + + assertNull(returned.numberMap) + assertNull(returned.objectMap) + assertNotNull(returned.stringMap) + + assertEquals(2, returned.stringMap?.size) + assertEquals("value1", returned.stringMap?.get("key1")) + assertEquals("value2", returned.stringMap?.get("key2")) + } + + @Test + fun propertyMap_withNonEmptyNumber() { + rule.server.enqueue( + MockResponse().setBody( + """ { "number_map": { "key1": 1.1, "key2": 2.2 } } - """.trimIndent() - ) - ) - - val returned = rule.getApi().getPropertyMap("number", "2").blockingGet() - - assertNull(returned.stringMap) - assertNull(returned.objectMap) - assertNotNull(returned.numberMap) - - assertEquals(2, returned.numberMap?.size) - assertEquals(1.1.toBigDecimal(), returned.numberMap?.get("key1")) - assertEquals(2.2.toBigDecimal(), returned.numberMap?.get("key2")) - } - - @Test - fun propertyMap_withNonEmptyObject() { - rule.server.enqueue( - MockResponse().setBody( - """ + """.trimIndent() + ) + ) + + val returned = rule.getApi().getPropertyMap("number", "2").blockingGet() + + assertNull(returned.stringMap) + assertNull(returned.objectMap) + assertNotNull(returned.numberMap) + + assertEquals(2, returned.numberMap?.size) + assertEquals(1.1.toBigDecimal(), returned.numberMap?.get("key1")) + assertEquals(2.2.toBigDecimal(), returned.numberMap?.get("key2")) + } + + @Test + fun propertyMap_withNonEmptyObject() { + rule.server.enqueue( + MockResponse().setBody( + """ { "object_map": { "key1": "1", "key2": "2" } } - """.trimIndent() - ) - ) - - val returned = rule.getApi().getPropertyMap("object", "2").blockingGet() - - assertNull(returned.stringMap) - assertNull(returned.numberMap) - assertNotNull(returned.objectMap) - - assertEquals(2, returned.objectMap?.size) - assertEquals("1", returned.objectMap?.get("key1") as String) - assertEquals("2", returned.objectMap?.get("key2") as String) - } - - @Test - fun propertyMap_withHeterogeneousObject() { - rule.server.enqueue( - MockResponse().setBody( - """ + """.trimIndent() + ) + ) + + val returned = rule.getApi().getPropertyMap("object", "2").blockingGet() + + assertNull(returned.stringMap) + assertNull(returned.numberMap) + assertNotNull(returned.objectMap) + + assertEquals(2, returned.objectMap?.size) + assertEquals("1", returned.objectMap?.get("key1") as String) + assertEquals("2", returned.objectMap?.get("key2") as String) + } + + @Test + fun propertyMap_withHeterogeneousObject() { + rule.server.enqueue( + MockResponse().setBody( + """ { "object_map": { "key1": "1", @@ -174,31 +174,31 @@ class PropertyMapEndpointTest { } } } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getPropertyMap("object", "heterogeneous").blockingGet() + val returned = rule.getApi().getPropertyMap("object", "heterogeneous").blockingGet() - assertNull(returned.stringMap) - assertNull(returned.numberMap) - assertNotNull(returned.objectMap) + assertNull(returned.stringMap) + assertNull(returned.numberMap) + assertNotNull(returned.objectMap) - assertEquals(4, returned.objectMap?.size) + assertEquals(4, returned.objectMap?.size) - assertEquals("1", returned.objectMap?.get("key1") as String) - assertEquals(2.0, returned.objectMap?.get("key2") as Double, 0.0) + assertEquals("1", returned.objectMap?.get("key1") as String) + assertEquals(2.0, returned.objectMap?.get("key2") as Double, 0.0) - assertFalse((returned.objectMap?.get("key3") as List<*>).isEmpty()) - assertEquals("array_value1", (returned.objectMap?.get("key3") as List<*>)[0]) + assertFalse((returned.objectMap?.get("key3") as List<*>).isEmpty()) + assertEquals("array_value1", (returned.objectMap?.get("key3") as List<*>)[0]) - assertFalse((returned.objectMap?.get("key4") as Map<*, *>).isEmpty()) - assertEquals( - "map_value1", - ( - @Suppress("UNCHECKED_CAST") - (returned.objectMap?.get("key4") as Map) - )["map_key1"] - ) - } + assertFalse((returned.objectMap?.get("key4") as Map<*, *>).isEmpty()) + assertEquals( + "map_value1", + ( + @Suppress("UNCHECKED_CAST") + (returned.objectMap?.get("key4") as Map) + )["map_key1"] + ) + } } diff --git a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/RequiredTypeEndpointTest.kt b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/RequiredTypeEndpointTest.kt index 252b5d15..67a81d2c 100644 --- a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/RequiredTypeEndpointTest.kt +++ b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/RequiredTypeEndpointTest.kt @@ -10,14 +10,14 @@ import org.junit.Test class RequiredTypeEndpointTest { - @get:Rule - val rule = MockServerApiRule() + @get:Rule + val rule = MockServerApiRule() - @Test - fun requiredTypeEndpoint() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun requiredTypeEndpoint() { + rule.server.enqueue( + MockResponse().setBody( + """ { "boolean_property": true, "enum_property": "VALUE1", @@ -25,15 +25,15 @@ class RequiredTypeEndpointTest { "number_property": 1.2, "string_property": "string" } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getRequiredTypeEndpoint().blockingGet() - assertEquals("string", returned.stringProperty) - assertEquals(true, returned.booleanProperty) - assertEquals(1, returned.integerProperty) - assertEquals(1.2.toBigDecimal(), returned.numberProperty) - assertEquals(RequiredTypeResponses.EnumPropertyEnum.VALUE1, returned.enumProperty) - } + val returned = rule.getApi().getRequiredTypeEndpoint().blockingGet() + assertEquals("string", returned.stringProperty) + assertEquals(true, returned.booleanProperty) + assertEquals(1, returned.integerProperty) + assertEquals(1.2.toBigDecimal(), returned.numberProperty) + assertEquals(RequiredTypeResponses.EnumPropertyEnum.VALUE1, returned.enumProperty) + } } diff --git a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/ReservedKeywordsEndpointTest.kt b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/ReservedKeywordsEndpointTest.kt index b2bd033b..5c2d94af 100644 --- a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/ReservedKeywordsEndpointTest.kt +++ b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/ReservedKeywordsEndpointTest.kt @@ -9,14 +9,14 @@ import org.junit.Test class ReservedKeywordsEndpointTest { - @get:Rule - val rule = MockServerApiRule() + @get:Rule + val rule = MockServerApiRule() - @Test - fun reservedKeywordsEndpoint() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun reservedKeywordsEndpoint() { + rule.server.enqueue( + MockResponse().setBody( + """ { "class": "class", "for": "for", @@ -25,16 +25,16 @@ class ReservedKeywordsEndpointTest { "var": "var", "when": "when" } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getReservedKeywords().blockingGet() - assertEquals("class", returned.`class`) - assertEquals("when", returned.`when`) - assertEquals("for", returned.`for`) - assertEquals("val", returned.`val`) - assertEquals("var", returned.`var`) - assertEquals("operator", returned.`operator`) - } + val returned = rule.getApi().getReservedKeywords().blockingGet() + assertEquals("class", returned.`class`) + assertEquals("when", returned.`when`) + assertEquals("for", returned.`for`) + assertEquals("val", returned.`val`) + assertEquals("var", returned.`var`) + assertEquals("operator", returned.`operator`) + } } diff --git a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/TopLevelEnumEndpointTest.kt b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/TopLevelEnumEndpointTest.kt index 709c9807..44002add 100644 --- a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/TopLevelEnumEndpointTest.kt +++ b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/TopLevelEnumEndpointTest.kt @@ -10,32 +10,32 @@ import org.junit.Test class TopLevelEnumEndpointTest { - @get:Rule - val rule = MockServerApiRule() + @get:Rule + val rule = MockServerApiRule() - @Test - fun topLevelEnumEndpoint() { - rule.server.enqueue(MockResponse().setBody("\"TOP_LEVEL_VALUE1\"")) + @Test + fun topLevelEnumEndpoint() { + rule.server.enqueue(MockResponse().setBody("\"TOP_LEVEL_VALUE1\"")) - val returned = rule.getApi().getTopLevelEnum().blockingGet() - assertEquals(TopLevelEnum.VALUE1, returned) - } + val returned = rule.getApi().getTopLevelEnum().blockingGet() + assertEquals(TopLevelEnum.VALUE1, returned) + } - @Test - fun topLevelEnumNestedEndpoint() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun topLevelEnumNestedEndpoint() { + rule.server.enqueue( + MockResponse().setBody( + """ { "key1": { "key2": "TOP_LEVEL_VALUE1" } } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getTopLevelEnumNested().blockingGet() - assertEquals(TopLevelEnum.VALUE1, returned["key1"]?.get("key2")) - } + val returned = rule.getApi().getTopLevelEnumNested().blockingGet() + assertEquals(TopLevelEnum.VALUE1, returned["key1"]?.get("key2")) + } } diff --git a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/TopLevelMapEndpointTest.kt b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/TopLevelMapEndpointTest.kt index 0af8c0bb..a7cac67d 100644 --- a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/TopLevelMapEndpointTest.kt +++ b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/TopLevelMapEndpointTest.kt @@ -10,35 +10,35 @@ import org.junit.Test class TopLevelMapEndpointTest { - @get:Rule - val rule = MockServerApiRule() + @get:Rule + val rule = MockServerApiRule() - @Test - fun topLevelMap_withEmptyResponse() { - rule.server.enqueue(MockResponse().setBody("{}")) + @Test + fun topLevelMap_withEmptyResponse() { + rule.server.enqueue(MockResponse().setBody("{}")) - val returned = rule.getApi().getTopLevelMap("empty").blockingGet() + val returned = rule.getApi().getTopLevelMap("empty").blockingGet() - assertTrue(returned.isEmpty()) - } + assertTrue(returned.isEmpty()) + } - @Test - fun topLevelMap_withNonEmptyResponse() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun topLevelMap_withNonEmptyResponse() { + rule.server.enqueue( + MockResponse().setBody( + """ { "key1": "value1", "key2": "value2" } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getTopLevelMap("2").blockingGet() + val returned = rule.getApi().getTopLevelMap("2").blockingGet() - assertEquals(2, returned.size) - assertEquals("value1", returned["key1"]) - assertEquals("value2", returned["key2"]) - } + assertEquals(2, returned.size) + assertEquals("value1", returned["key1"]) + assertEquals("value2", returned["key2"]) + } } diff --git a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/TypeEndpointTest.kt b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/TypeEndpointTest.kt index dfcf2c90..d342d6ae 100644 --- a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/TypeEndpointTest.kt +++ b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/TypeEndpointTest.kt @@ -9,70 +9,70 @@ import org.junit.Test class TypeEndpointTest { - @get:Rule - val rule = MockServerApiRule() + @get:Rule + val rule = MockServerApiRule() - @Test - fun typeEndpoint_withStringType() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun typeEndpoint_withStringType() { + rule.server.enqueue( + MockResponse().setBody( + """ { "string_property": "string" } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getTypeEndpoint("string").blockingGet() - assertEquals("string", returned.stringProperty) - } + val returned = rule.getApi().getTypeEndpoint("string").blockingGet() + assertEquals("string", returned.stringProperty) + } - @Test - fun typeEndpoint_withBooleanType() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun typeEndpoint_withBooleanType() { + rule.server.enqueue( + MockResponse().setBody( + """ { "boolean_property": true } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getTypeEndpoint("boolean").blockingGet() - assertEquals(true, returned.booleanProperty) - } + val returned = rule.getApi().getTypeEndpoint("boolean").blockingGet() + assertEquals(true, returned.booleanProperty) + } - @Test - fun typeEndpoint_withIntegerType() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun typeEndpoint_withIntegerType() { + rule.server.enqueue( + MockResponse().setBody( + """ { "integer_property": 1 } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getTypeEndpoint("integer").blockingGet() - assertEquals(1, returned.integerProperty) - } + val returned = rule.getApi().getTypeEndpoint("integer").blockingGet() + assertEquals(1, returned.integerProperty) + } - @Test - fun typeEndpoint_withNumberType() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun typeEndpoint_withNumberType() { + rule.server.enqueue( + MockResponse().setBody( + """ { "number_property": 1.2 } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getTypeEndpoint("number").blockingGet() - assertEquals(1.2.toBigDecimal(), returned.numberProperty) - } + val returned = rule.getApi().getTypeEndpoint("number").blockingGet() + assertEquals(1.2.toBigDecimal(), returned.numberProperty) + } } diff --git a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/ValidParameterTest.kt b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/ValidParameterTest.kt index ba7e70fd..3aaa4593 100644 --- a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/ValidParameterTest.kt +++ b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/ValidParameterTest.kt @@ -10,30 +10,30 @@ import org.junit.Test class ValidParameterTest { - @get:Rule - val mockServerRule = MockServerApiRule() + @get:Rule + val mockServerRule = MockServerApiRule() - @Test - fun symbolsInParameterName() { - mockServerRule.server.enqueue(MockResponse()) + @Test + fun symbolsInParameterName() { + mockServerRule.server.enqueue(MockResponse()) - val defaultApi = mockServerRule.getApi() - val pet = defaultApi.getSymbolsInParameterName( - parameter = "testParameter", - brackets = "testBrackets", - bracketsWithText = "testBracketsWithText", - dot = "testDot", - dotWithText = "testDotWithText" - ).blockingGet() + val defaultApi = mockServerRule.getApi() + val pet = defaultApi.getSymbolsInParameterName( + parameter = "testParameter", + brackets = "testBrackets", + bracketsWithText = "testBracketsWithText", + dot = "testDot", + dotWithText = "testDotWithText" + ).blockingGet() - val requestPath = mockServerRule.server.takeRequest().path - assertNull(pet) + val requestPath = mockServerRule.server.takeRequest().path + assertNull(pet) - // Let's check if the query parameters are encoded properly. - assertTrue("parameter=testParameter" in requestPath) - assertTrue("brackets%5B%5D=testBrackets" in requestPath) - assertTrue("brackets%5BwithText%5D=testBracketsWithText" in requestPath) - assertTrue("dot.=testDot" in requestPath) - assertTrue("dot.withText=testDotWithText" in requestPath) - } + // Let's check if the query parameters are encoded properly. + assertTrue("parameter=testParameter" in requestPath) + assertTrue("brackets%5B%5D=testBrackets" in requestPath) + assertTrue("brackets%5BwithText%5D=testBracketsWithText" in requestPath) + assertTrue("dot.=testDot" in requestPath) + assertTrue("dot.withText=testDotWithText" in requestPath) + } } diff --git a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/tools/MockServerApiRule.kt b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/tools/MockServerApiRule.kt index da417b4c..a7585ffe 100644 --- a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/tools/MockServerApiRule.kt +++ b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/tools/MockServerApiRule.kt @@ -1,6 +1,9 @@ package com.yelp.codegen.generatecodesamples.tools +import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory import io.reactivex.schedulers.Schedulers +import kotlinx.serialization.json.Json +import okhttp3.MediaType import okhttp3.mockwebserver.MockWebServer import org.junit.rules.ExternalResource import retrofit2.Retrofit @@ -12,26 +15,27 @@ import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory */ class MockServerApiRule : ExternalResource() { - lateinit var retrofit: Retrofit - val server = MockWebServer() + lateinit var retrofit: Retrofit + val server = MockWebServer() - override fun before() { - super.before() - server.start() + override fun before() { + super.before() + server.start() + val contentType = MediaType.get("application/json") - retrofit = Retrofit.Builder() - .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.trampoline())) - .addConverterFactory(GeneratedCodeConverters.converterFactory()) - .baseUrl(server.url("/")) - .build() - } + retrofit = Retrofit.Builder() + .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.trampoline())) + .addConverterFactory(Json.asConverterFactory(contentType)) + .baseUrl(server.url("/")) + .build() + } - override fun after() { - server.shutdown() - super.after() - } + override fun after() { + server.shutdown() + super.after() + } - inline fun getApi(): T { - return retrofit.create(T::class.java) - } + inline fun getApi(): T { + return retrofit.create(T::class.java) + } } diff --git a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/tools/MultiPartTestUtil.kt b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/tools/MultiPartTestUtil.kt index a2d47aba..f44d7251 100644 --- a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/tools/MultiPartTestUtil.kt +++ b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/tools/MultiPartTestUtil.kt @@ -5,90 +5,90 @@ import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue data class FileApiStats( - val boundary: String, - val parts: List + val boundary: String, + val parts: List ) data class MultiPartInfo( - val fileContent: String? = null, - val contentDisposition: String? = null, - val contentLength: String? = null, - val contentType: String? = null + val fileContent: String? = null, + val contentDisposition: String? = null, + val contentLength: String? = null, + val contentType: String? = null ) private fun processPart(part: String): MultiPartInfo { - // part would look like "\r\nHeader-Name: Header-Value\r\n...\r\n\r\nbody\r\n" - // Here we're removing the first and last part as we know that are empty - val partLines = part.split("\r\n").drop(1).dropLast(1) + // part would look like "\r\nHeader-Name: Header-Value\r\n...\r\n\r\nbody\r\n" + // Here we're removing the first and last part as we know that are empty + val partLines = part.split("\r\n").drop(1).dropLast(1) - val indexBoundaryHeadersContent = partLines.indexOf("") + val indexBoundaryHeadersContent = partLines.indexOf("") - val headers = partLines.subList(0, indexBoundaryHeadersContent).map { - val (name, value) = it.split(": ", limit = 2) - // Note: in theory we can have the same header name multiples times - // We're not dealing with it as this is a test utility ;) - name to value - }.toMap() + val headers = partLines.subList(0, indexBoundaryHeadersContent).map { + val (name, value) = it.split(": ", limit = 2) + // Note: in theory we can have the same header name multiples times + // We're not dealing with it as this is a test utility ;) + name to value + }.toMap() - val content = partLines.subList(indexBoundaryHeadersContent, partLines.size).drop(1).joinToString("\r\n") - return MultiPartInfo( - fileContent = content, - contentDisposition = headers["Content-Disposition"], - contentType = headers["Content-Type"], - contentLength = headers["Content-Length"] - ) + val content = partLines.subList(indexBoundaryHeadersContent, partLines.size).drop(1).joinToString("\r\n") + return MultiPartInfo( + fileContent = content, + contentDisposition = headers["Content-Disposition"], + contentType = headers["Content-Type"], + contentLength = headers["Content-Length"] + ) } /** * Extract statistics from the body of the recorded request (assuming that it is multipart body) */ fun RecordedRequest.decodeMultiPartBody(): FileApiStats { - /** - * requestBody has to be compliant to the HTTP Specifications for MultiPart (RFC 2387) - * - * This means that the body will look like - * --\r\n - * : \r\n - * [: \r\n] - * \r\n - * \r\n - * --\r\n - * : \r\n - * [: \r\n] - * \r\n - * \r\n - * ----\r\n - * \r\n - */ - val requestBody = this.body.readUtf8() + /** + * requestBody has to be compliant to the HTTP Specifications for MultiPart (RFC 2387) + * + * This means that the body will look like + * --\r\n + * : \r\n + * [: \r\n] + * \r\n + * \r\n + * --\r\n + * : \r\n + * [: \r\n] + * \r\n + * \r\n + * ----\r\n + * \r\n + */ + val requestBody = this.body.readUtf8() - val boundaryLine = requestBody.split("\r\n").first() + val boundaryLine = requestBody.split("\r\n").first() - assertTrue( - "Boundary should start with '--'", - boundaryLine.startsWith("--") - ) + assertTrue( + "Boundary should start with '--'", + boundaryLine.startsWith("--") + ) - val boundary = boundaryLine.substring(startIndex = 2) - val bodyParts = requestBody.split(boundaryLine) + val boundary = boundaryLine.substring(startIndex = 2) + val bodyParts = requestBody.split(boundaryLine) - assertTrue( - "Start and End Boundaries are different", - bodyParts.last().startsWith("--") - ) - assertEquals( - "The last line of the body has to be empty", - "\r\n", - bodyParts.last().substring(startIndex = 2) - ) + assertTrue( + "Start and End Boundaries are different", + bodyParts.last().startsWith("--") + ) + assertEquals( + "The last line of the body has to be empty", + "\r\n", + bodyParts.last().substring(startIndex = 2) + ) - val parts = bodyParts - .drop(1) - .dropLast(1) - .map { processPart(it) } + val parts = bodyParts + .drop(1) + .dropLast(1) + .map { processPart(it) } - return FileApiStats( - boundary = boundary, - parts = parts - ) + return FileApiStats( + boundary = boundary, + parts = parts + ) } diff --git a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/xnullable/XnullableFormatEndpointTest.kt b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/xnullable/XnullableFormatEndpointTest.kt index a88fdb1d..bd69c7eb 100644 --- a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/xnullable/XnullableFormatEndpointTest.kt +++ b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/xnullable/XnullableFormatEndpointTest.kt @@ -9,63 +9,63 @@ import org.junit.Test class XnullableFormatEndpointTest { - @get:Rule - val rule = MockServerApiRule() + @get:Rule + val rule = MockServerApiRule() - @Test - fun formatEndpoint_withEnumFormat() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun formatEndpoint_withEnumFormat() { + rule.server.enqueue( + MockResponse().setBody( + """ { "double_property": null } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullableFormatEndpoint("double").blockingGet() + val returned = rule.getApi().getXnullableFormatEndpoint("double").blockingGet() - assertNull(returned.doubleProperty) - assertNull(returned.datetimeProperty) - assertNull(returned.dateProperty) - } + assertNull(returned.doubleProperty) + assertNull(returned.datetimeProperty) + assertNull(returned.dateProperty) + } - @Test - fun formatEndpoint_withDateFormat() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun formatEndpoint_withDateFormat() { + rule.server.enqueue( + MockResponse().setBody( + """ { "date_property": null } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullableFormatEndpoint("date").blockingGet() + val returned = rule.getApi().getXnullableFormatEndpoint("date").blockingGet() - assertNull(returned.doubleProperty) - assertNull(returned.datetimeProperty) - assertNull(returned.dateProperty) - } + assertNull(returned.doubleProperty) + assertNull(returned.datetimeProperty) + assertNull(returned.dateProperty) + } - @Test - fun formatEndpoint_withDateTimeFormat() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun formatEndpoint_withDateTimeFormat() { + rule.server.enqueue( + MockResponse().setBody( + """ { "datetime_property": null } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullableFormatEndpoint("datetime").blockingGet() + val returned = rule.getApi().getXnullableFormatEndpoint("datetime").blockingGet() - assertNull(returned.doubleProperty) - assertNull(returned.datetimeProperty) - assertNull(returned.dateProperty) - } + assertNull(returned.doubleProperty) + assertNull(returned.datetimeProperty) + assertNull(returned.dateProperty) + } } diff --git a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/xnullable/XnullableNestedAdditionalPropertiesEndpointTest.kt b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/xnullable/XnullableNestedAdditionalPropertiesEndpointTest.kt index 92f984a9..f52323ab 100644 --- a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/xnullable/XnullableNestedAdditionalPropertiesEndpointTest.kt +++ b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/xnullable/XnullableNestedAdditionalPropertiesEndpointTest.kt @@ -13,14 +13,14 @@ import org.junit.Test class XnullableNestedAdditionalPropertiesEndpointTest { - @get:Rule - val rule = MockServerApiRule() - - @Test - fun xNullableNestedAdditionalProperties() { - rule.server.enqueue( - MockResponse().setBody( - """ + @get:Rule + val rule = MockServerApiRule() + + @Test + fun xNullableNestedAdditionalProperties() { + rule.server.enqueue( + MockResponse().setBody( + """ { "key1": { "subkey1": "subvalue1", @@ -32,30 +32,30 @@ class XnullableNestedAdditionalPropertiesEndpointTest { "key3": {}, "key4": null } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullableNestedAdditionalProperties().blockingGet() + val returned = rule.getApi().getXnullableNestedAdditionalProperties().blockingGet() - assertFalse(returned.isEmpty()) + assertFalse(returned.isEmpty()) - // Check that sizes are correct - assertEquals(4, returned.keys.size) - assertEquals(2, returned["key1"]?.keys?.size) - assertEquals(1, returned["key2"]?.keys?.size) - assertEquals(0, returned["key3"]?.keys?.size) + // Check that sizes are correct + assertEquals(4, returned.keys.size) + assertEquals(2, returned["key1"]?.keys?.size) + assertEquals(1, returned["key2"]?.keys?.size) + assertEquals(0, returned["key3"]?.keys?.size) - // Check that sizes are mapped correctly - assertTrue(returned["key1"] is XnullableMap) - assertTrue(returned["key2"] is XnullableMap) - assertTrue(returned["key3"] is XnullableMap) - assertNull(returned["key4"]) + // Check that sizes are mapped correctly + assertTrue(returned["key1"] is XnullableMap) + assertTrue(returned["key2"] is XnullableMap) + assertTrue(returned["key3"] is XnullableMap) + assertNull(returned["key4"]) - // Check that values are correct - assertEquals("subvalue1", returned["key1"]?.get("subkey1")) - assertNull(returned["key1"]?.get("subkey2")) + // Check that values are correct + assertEquals("subvalue1", returned["key1"]?.get("subkey1")) + assertNull(returned["key1"]?.get("subkey2")) - assertNull(returned["key2"]?.get("subkey1")) - } + assertNull(returned["key2"]?.get("subkey1")) + } } diff --git a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/xnullable/XnullablePropertyArrayEndpointTest.kt b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/xnullable/XnullablePropertyArrayEndpointTest.kt index 6ce37976..0dec8d43 100644 --- a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/xnullable/XnullablePropertyArrayEndpointTest.kt +++ b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/xnullable/XnullablePropertyArrayEndpointTest.kt @@ -12,168 +12,168 @@ import org.junit.Test class XnullablePropertyArrayEndpointTest { - @get:Rule - val rule = MockServerApiRule() - - @Test - fun xNullablePropertyArray_withEmptyString() { - rule.server.enqueue( - MockResponse().setBody( - """ + @get:Rule + val rule = MockServerApiRule() + + @Test + fun xNullablePropertyArray_withEmptyString() { + rule.server.enqueue( + MockResponse().setBody( + """ { "string_array": [] } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullablePropertyArray("string", "empty").blockingGet() + val returned = rule.getApi().getXnullablePropertyArray("string", "empty").blockingGet() - assertNull(returned.numberArray) - assertNotNull(returned.stringArray) + assertNull(returned.numberArray) + assertNotNull(returned.stringArray) - assertTrue(returned.stringArray?.isEmpty()!!) - } + assertTrue(returned.stringArray?.isEmpty()!!) + } - @Test - fun xNullablePropertyArray_withEmptyNumber() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun xNullablePropertyArray_withEmptyNumber() { + rule.server.enqueue( + MockResponse().setBody( + """ { "number_array": [] } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullablePropertyArray("number", "empty").blockingGet() + val returned = rule.getApi().getXnullablePropertyArray("number", "empty").blockingGet() - assertNull(returned.stringArray) - assertNotNull(returned.numberArray) + assertNull(returned.stringArray) + assertNotNull(returned.numberArray) - assertTrue(returned.numberArray?.isEmpty()!!) - } + assertTrue(returned.numberArray?.isEmpty()!!) + } - @Test - fun xNullablePropertyArray_withNullString() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun xNullablePropertyArray_withNullString() { + rule.server.enqueue( + MockResponse().setBody( + """ { "string_array": null } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullablePropertyArray("string", "null").blockingGet() + val returned = rule.getApi().getXnullablePropertyArray("string", "null").blockingGet() - assertNull(returned.numberArray) - assertNull(returned.stringArray) - } + assertNull(returned.numberArray) + assertNull(returned.stringArray) + } - @Test - fun xNullablePropertyArray_withNullNumber() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun xNullablePropertyArray_withNullNumber() { + rule.server.enqueue( + MockResponse().setBody( + """ { "number_array": null } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullablePropertyArray("number", "null").blockingGet() + val returned = rule.getApi().getXnullablePropertyArray("number", "null").blockingGet() - assertNull(returned.numberArray) - assertNull(returned.stringArray) - } + assertNull(returned.numberArray) + assertNull(returned.stringArray) + } - @Test - fun xNullablePropertyArray_withOneNullString() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun xNullablePropertyArray_withOneNullString() { + rule.server.enqueue( + MockResponse().setBody( + """ { "string_array": [ null ] } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullablePropertyArray("string", "1null").blockingGet() + val returned = rule.getApi().getXnullablePropertyArray("string", "1null").blockingGet() - assertNull(returned.numberArray) - assertNotNull(returned.stringArray) + assertNull(returned.numberArray) + assertNotNull(returned.stringArray) - assertEquals(1, returned.stringArray?.size) - assertNull(returned.stringArray?.get(0)) - } + assertEquals(1, returned.stringArray?.size) + assertNull(returned.stringArray?.get(0)) + } - @Test - fun xNullablePropertyArray_withOneNullNumber() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun xNullablePropertyArray_withOneNullNumber() { + rule.server.enqueue( + MockResponse().setBody( + """ { "number_array": [ null ] } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullablePropertyArray("number", "1null").blockingGet() + val returned = rule.getApi().getXnullablePropertyArray("number", "1null").blockingGet() - assertNull(returned.stringArray) - assertNotNull(returned.numberArray) + assertNull(returned.stringArray) + assertNotNull(returned.numberArray) - assertEquals(1, returned.numberArray?.size) - assertNull(returned.numberArray?.get(0)) - } + assertEquals(1, returned.numberArray?.size) + assertNull(returned.numberArray?.get(0)) + } - @Test - fun xNullablePropertyArray_withTwoStrings() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun xNullablePropertyArray_withTwoStrings() { + rule.server.enqueue( + MockResponse().setBody( + """ { "string_array": [ "value1", null ] } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullablePropertyArray("string", "2").blockingGet() + val returned = rule.getApi().getXnullablePropertyArray("string", "2").blockingGet() - assertNull(returned.numberArray) - assertNotNull(returned.stringArray) + assertNull(returned.numberArray) + assertNotNull(returned.stringArray) - assertEquals(2, returned.stringArray?.size) - assertEquals("value1", returned.stringArray?.get(0)) - assertNull(returned.stringArray?.get(1)) - } + assertEquals(2, returned.stringArray?.size) + assertEquals("value1", returned.stringArray?.get(0)) + assertNull(returned.stringArray?.get(1)) + } - @Test - fun xNullablePropertyArray_withTwoNumbers() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun xNullablePropertyArray_withTwoNumbers() { + rule.server.enqueue( + MockResponse().setBody( + """ { "number_array": [ 1.1, null ] } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullablePropertyArray("number", "2").blockingGet() + val returned = rule.getApi().getXnullablePropertyArray("number", "2").blockingGet() - assertNull(returned.stringArray) - assertNotNull(returned.numberArray) + assertNull(returned.stringArray) + assertNotNull(returned.numberArray) - assertEquals(2, returned.numberArray?.size) - assertEquals(1.1.toBigDecimal(), returned.numberArray?.get(0)) - assertNull(returned.numberArray?.get(1)) - } + assertEquals(2, returned.numberArray?.size) + assertEquals(1.1.toBigDecimal(), returned.numberArray?.get(0)) + assertNull(returned.numberArray?.get(1)) + } } diff --git a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/xnullable/XnullablePropertyMapEndpointTest.kt b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/xnullable/XnullablePropertyMapEndpointTest.kt index e5eac4ac..97ebf15a 100644 --- a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/xnullable/XnullablePropertyMapEndpointTest.kt +++ b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/xnullable/XnullablePropertyMapEndpointTest.kt @@ -13,284 +13,284 @@ import org.junit.Test class XnullablePropertyMapEndpointTest { - @get:Rule - val rule = MockServerApiRule() - - @Test - fun xNullablePropertyMap_withEmptyString() { - rule.server.enqueue( - MockResponse().setBody( - """ + @get:Rule + val rule = MockServerApiRule() + + @Test + fun xNullablePropertyMap_withEmptyString() { + rule.server.enqueue( + MockResponse().setBody( + """ { "string_map": {} } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullablePropertyMap("string", "empty").blockingGet() + val returned = rule.getApi().getXnullablePropertyMap("string", "empty").blockingGet() - assertNull(returned.numberMap) - assertNull(returned.objectMap) - assertNotNull(returned.stringMap) + assertNull(returned.numberMap) + assertNull(returned.objectMap) + assertNotNull(returned.stringMap) - assertTrue(returned.stringMap?.isEmpty()!!) - } + assertTrue(returned.stringMap?.isEmpty()!!) + } - @Test - fun xNullablePropertyMap_withEmptyNumber() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun xNullablePropertyMap_withEmptyNumber() { + rule.server.enqueue( + MockResponse().setBody( + """ { "number_map": {} } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullablePropertyMap("number", "empty").blockingGet() + val returned = rule.getApi().getXnullablePropertyMap("number", "empty").blockingGet() - assertNull(returned.stringMap) - assertNull(returned.objectMap) - assertNotNull(returned.numberMap) + assertNull(returned.stringMap) + assertNull(returned.objectMap) + assertNotNull(returned.numberMap) - assertTrue(returned.numberMap?.isEmpty()!!) - } + assertTrue(returned.numberMap?.isEmpty()!!) + } - @Test - fun xNullablePropertyMap_withEmptyObject() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun xNullablePropertyMap_withEmptyObject() { + rule.server.enqueue( + MockResponse().setBody( + """ { "object_map": {} } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullablePropertyMap("object", "empty").blockingGet() + val returned = rule.getApi().getXnullablePropertyMap("object", "empty").blockingGet() - assertNull(returned.stringMap) - assertNull(returned.numberMap) - assertNotNull(returned.objectMap) + assertNull(returned.stringMap) + assertNull(returned.numberMap) + assertNotNull(returned.objectMap) - assertTrue(returned.objectMap?.isEmpty()!!) - } + assertTrue(returned.objectMap?.isEmpty()!!) + } - @Test - fun xNullablePropertyMap_withNullString() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun xNullablePropertyMap_withNullString() { + rule.server.enqueue( + MockResponse().setBody( + """ { "string_map": null } - """.trimIndent() - ) - ) - - val returned = rule.getApi().getXnullablePropertyMap("string", "null").blockingGet() - - assertNull(returned.numberMap) - assertNull(returned.objectMap) - assertNull(returned.stringMap) - } - - @Test - fun xNullablePropertyMap_withNullNumber() { - rule.server.enqueue( - MockResponse().setBody( - """ + """.trimIndent() + ) + ) + + val returned = rule.getApi().getXnullablePropertyMap("string", "null").blockingGet() + + assertNull(returned.numberMap) + assertNull(returned.objectMap) + assertNull(returned.stringMap) + } + + @Test + fun xNullablePropertyMap_withNullNumber() { + rule.server.enqueue( + MockResponse().setBody( + """ { "number_map": null } - """.trimIndent() - ) - ) - - val returned = rule.getApi().getXnullablePropertyMap("number", "null").blockingGet() - - assertNull(returned.stringMap) - assertNull(returned.objectMap) - assertNull(returned.numberMap) - } - - @Test - fun xNullablePropertyMap_withNullObject() { - rule.server.enqueue( - MockResponse().setBody( - """ + """.trimIndent() + ) + ) + + val returned = rule.getApi().getXnullablePropertyMap("number", "null").blockingGet() + + assertNull(returned.stringMap) + assertNull(returned.objectMap) + assertNull(returned.numberMap) + } + + @Test + fun xNullablePropertyMap_withNullObject() { + rule.server.enqueue( + MockResponse().setBody( + """ { "object_map": null } - """.trimIndent() - ) - ) - - val returned = rule.getApi().getXnullablePropertyMap("object", "null").blockingGet() - - assertNull(returned.stringMap) - assertNull(returned.numberMap) - assertNull(returned.objectMap) - } - - @Test - fun xNullablePropertyMap_withOneNullString() { - rule.server.enqueue( - MockResponse().setBody( - """ + """.trimIndent() + ) + ) + + val returned = rule.getApi().getXnullablePropertyMap("object", "null").blockingGet() + + assertNull(returned.stringMap) + assertNull(returned.numberMap) + assertNull(returned.objectMap) + } + + @Test + fun xNullablePropertyMap_withOneNullString() { + rule.server.enqueue( + MockResponse().setBody( + """ { "string_map": { "key1": null } } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullablePropertyMap("string", "1null").blockingGet() + val returned = rule.getApi().getXnullablePropertyMap("string", "1null").blockingGet() - assertNull(returned.numberMap) - assertNull(returned.objectMap) - assertNotNull(returned.stringMap) + assertNull(returned.numberMap) + assertNull(returned.objectMap) + assertNotNull(returned.stringMap) - assertEquals(1, returned.stringMap?.size) - assertNull(returned.stringMap?.get("key1")) - } + assertEquals(1, returned.stringMap?.size) + assertNull(returned.stringMap?.get("key1")) + } - @Test - fun xNullablePropertyMap_withOneNullNumber() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun xNullablePropertyMap_withOneNullNumber() { + rule.server.enqueue( + MockResponse().setBody( + """ { "number_map": { "key1": null } } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullablePropertyMap("number", "1null").blockingGet() + val returned = rule.getApi().getXnullablePropertyMap("number", "1null").blockingGet() - assertNull(returned.stringMap) - assertNull(returned.objectMap) - assertNotNull(returned.numberMap) + assertNull(returned.stringMap) + assertNull(returned.objectMap) + assertNotNull(returned.numberMap) - assertEquals(1, returned.numberMap?.size) - assertNull(returned.numberMap?.get("key1")) - } + assertEquals(1, returned.numberMap?.size) + assertNull(returned.numberMap?.get("key1")) + } - @Test - fun xNullablePropertyMap_withOneNullObject() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun xNullablePropertyMap_withOneNullObject() { + rule.server.enqueue( + MockResponse().setBody( + """ { "object_map": { "key1": null } } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullablePropertyMap("object", "1null").blockingGet() + val returned = rule.getApi().getXnullablePropertyMap("object", "1null").blockingGet() - assertNull(returned.stringMap) - assertNull(returned.numberMap) - assertNotNull(returned.objectMap) + assertNull(returned.stringMap) + assertNull(returned.numberMap) + assertNotNull(returned.objectMap) - assertEquals(1, returned.objectMap?.size) - assertNull(returned.objectMap?.get("key1")) - } + assertEquals(1, returned.objectMap?.size) + assertNull(returned.objectMap?.get("key1")) + } - @Test - fun xNullablePropertyMap_with2Strings() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun xNullablePropertyMap_with2Strings() { + rule.server.enqueue( + MockResponse().setBody( + """ { "string_map": { "key1": "value1", "key2": null } } - """.trimIndent() - ) - ) - - val returned = rule.getApi().getXnullablePropertyMap("string", "2").blockingGet() - - assertNull(returned.numberMap) - assertNull(returned.objectMap) - assertNotNull(returned.stringMap) - - assertEquals(2, returned.stringMap?.size) - assertEquals("value1", returned.stringMap?.get("key1")) - assertNull(returned.stringMap?.get("key2")) - } - - @Test - fun xNullablePropertyMap_with2Numbers() { - rule.server.enqueue( - MockResponse().setBody( - """ + """.trimIndent() + ) + ) + + val returned = rule.getApi().getXnullablePropertyMap("string", "2").blockingGet() + + assertNull(returned.numberMap) + assertNull(returned.objectMap) + assertNotNull(returned.stringMap) + + assertEquals(2, returned.stringMap?.size) + assertEquals("value1", returned.stringMap?.get("key1")) + assertNull(returned.stringMap?.get("key2")) + } + + @Test + fun xNullablePropertyMap_with2Numbers() { + rule.server.enqueue( + MockResponse().setBody( + """ { "number_map": { "key1": 1.1, "key2": null } } - """.trimIndent() - ) - ) - - val returned = rule.getApi().getXnullablePropertyMap("number", "2").blockingGet() - - assertNull(returned.stringMap) - assertNull(returned.objectMap) - assertNotNull(returned.numberMap) - - assertEquals(2, returned.numberMap?.size) - assertEquals(1.1.toBigDecimal(), returned.numberMap?.get("key1")) - assertNull(returned.numberMap?.get("key2")) - } - - @Test - fun xNullablePropertyMap_with2Objects() { - rule.server.enqueue( - MockResponse().setBody( - """ + """.trimIndent() + ) + ) + + val returned = rule.getApi().getXnullablePropertyMap("number", "2").blockingGet() + + assertNull(returned.stringMap) + assertNull(returned.objectMap) + assertNotNull(returned.numberMap) + + assertEquals(2, returned.numberMap?.size) + assertEquals(1.1.toBigDecimal(), returned.numberMap?.get("key1")) + assertNull(returned.numberMap?.get("key2")) + } + + @Test + fun xNullablePropertyMap_with2Objects() { + rule.server.enqueue( + MockResponse().setBody( + """ { "object_map": { "key1": "1", "key2": null } } - """.trimIndent() - ) - ) - - val returned = rule.getApi().getXnullablePropertyMap("object", "2").blockingGet() - - assertNull(returned.stringMap) - assertNull(returned.numberMap) - assertNotNull(returned.objectMap) - - assertEquals(2, returned.objectMap?.size) - assertEquals("1", returned.objectMap?.get("key1") as String) - assertNull(returned.objectMap?.get("key2")) - } - - @Test - fun xNullablePropertyMap_withEtherogeneousObject() { - rule.server.enqueue( - MockResponse().setBody( - """ + """.trimIndent() + ) + ) + + val returned = rule.getApi().getXnullablePropertyMap("object", "2").blockingGet() + + assertNull(returned.stringMap) + assertNull(returned.numberMap) + assertNotNull(returned.objectMap) + + assertEquals(2, returned.objectMap?.size) + assertEquals("1", returned.objectMap?.get("key1") as String) + assertNull(returned.objectMap?.get("key2")) + } + + @Test + fun xNullablePropertyMap_withEtherogeneousObject() { + rule.server.enqueue( + MockResponse().setBody( + """ { "object_map": { "key1": "1", @@ -304,32 +304,32 @@ class XnullablePropertyMapEndpointTest { "key5": null } } - """.trimIndent() - ) - ) - - val returned = rule.getApi().getXnullablePropertyMap("object", "heterogeneous").blockingGet() - - assertNull(returned.stringMap) - assertNull(returned.numberMap) - assertNotNull(returned.objectMap) - - assertEquals(5, returned.objectMap?.size) - - assertEquals("1", returned.objectMap?.get("key1") as String) - assertEquals(2.0, returned.objectMap?.get("key2") as Double, 0.0) - - assertFalse((returned.objectMap?.get("key3") as List<*>).isEmpty()) - assertEquals("array_value1", (returned.objectMap?.get("key3") as List<*>)[0]) - - assertFalse((returned.objectMap?.get("key4") as Map<*, *>).isEmpty()) - assertEquals( - "map_value1", - ( - @Suppress("UNCHECKED_CAST") - (returned.objectMap?.get("key4") as Map) - )["map_key1"] - ) - assertNull(returned.objectMap?.get("key5")) - } + """.trimIndent() + ) + ) + + val returned = rule.getApi().getXnullablePropertyMap("object", "heterogeneous").blockingGet() + + assertNull(returned.stringMap) + assertNull(returned.numberMap) + assertNotNull(returned.objectMap) + + assertEquals(5, returned.objectMap?.size) + + assertEquals("1", returned.objectMap?.get("key1") as String) + assertEquals(2.0, returned.objectMap?.get("key2") as Double, 0.0) + + assertFalse((returned.objectMap?.get("key3") as List<*>).isEmpty()) + assertEquals("array_value1", (returned.objectMap?.get("key3") as List<*>)[0]) + + assertFalse((returned.objectMap?.get("key4") as Map<*, *>).isEmpty()) + assertEquals( + "map_value1", + ( + @Suppress("UNCHECKED_CAST") + (returned.objectMap?.get("key4") as Map) + )["map_key1"] + ) + assertNull(returned.objectMap?.get("key5")) + } } diff --git a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/xnullable/XnullableRequiredPropertyArrayEndpointTest.kt b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/xnullable/XnullableRequiredPropertyArrayEndpointTest.kt index 32a3047c..f43884f1 100644 --- a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/xnullable/XnullableRequiredPropertyArrayEndpointTest.kt +++ b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/xnullable/XnullableRequiredPropertyArrayEndpointTest.kt @@ -12,94 +12,94 @@ import org.junit.Test class XnullableRequiredPropertyArrayEndpointTest { - @get:Rule - val rule = MockServerApiRule() - - @Test - fun xNullableRequiredPropertyArray_withAllEmpty() { - rule.server.enqueue( - MockResponse().setBody( - """ + @get:Rule + val rule = MockServerApiRule() + + @Test + fun xNullableRequiredPropertyArray_withAllEmpty() { + rule.server.enqueue( + MockResponse().setBody( + """ { "number_array": [], "string_array": [] } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullableRequiredPropertyArray("empty").blockingGet() + val returned = rule.getApi().getXnullableRequiredPropertyArray("empty").blockingGet() - assertNotNull(returned.numberArray) - assertNotNull(returned.numberArray) + assertNotNull(returned.numberArray) + assertNotNull(returned.numberArray) - assertTrue(returned.numberArray?.isEmpty()!!) - assertTrue(returned.stringArray?.isEmpty()!!) - } + assertTrue(returned.numberArray?.isEmpty()!!) + assertTrue(returned.stringArray?.isEmpty()!!) + } - @Test - fun xNullableRequiredPropertyArray_withAllNull() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun xNullableRequiredPropertyArray_withAllNull() { + rule.server.enqueue( + MockResponse().setBody( + """ { "number_array": null, "string_array": null } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullableRequiredPropertyArray("null").blockingGet() + val returned = rule.getApi().getXnullableRequiredPropertyArray("null").blockingGet() - assertNull(returned.numberArray) - assertNull(returned.stringArray) - } + assertNull(returned.numberArray) + assertNull(returned.stringArray) + } - @Test - fun xNullableRequiredPropertyArray_withAllOneNullElement() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun xNullableRequiredPropertyArray_withAllOneNullElement() { + rule.server.enqueue( + MockResponse().setBody( + """ { "number_array": [ null ], "string_array": [ null ] } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullableRequiredPropertyArray("1null").blockingGet() + val returned = rule.getApi().getXnullableRequiredPropertyArray("1null").blockingGet() - assertEquals(1, returned.numberArray?.size) - assertEquals(1, returned.stringArray?.size) + assertEquals(1, returned.numberArray?.size) + assertEquals(1, returned.stringArray?.size) - assertNull(returned.numberArray?.get(0)) - assertNull(returned.stringArray?.get(0)) - } + assertNull(returned.numberArray?.get(0)) + assertNull(returned.stringArray?.get(0)) + } - @Test - fun xNullableRequiredPropertyArray_withAllTwoElements() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun xNullableRequiredPropertyArray_withAllTwoElements() { + rule.server.enqueue( + MockResponse().setBody( + """ { "number_array": [ 1.1, null ], "string_array": [ "value1", null ] } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullableRequiredPropertyArray("2").blockingGet() + val returned = rule.getApi().getXnullableRequiredPropertyArray("2").blockingGet() - assertEquals(2, returned.numberArray?.size) - assertEquals(2, returned.stringArray?.size) + assertEquals(2, returned.numberArray?.size) + assertEquals(2, returned.stringArray?.size) - assertEquals(1.1.toBigDecimal(), returned.numberArray?.get(0)) - assertEquals("value1", returned.stringArray?.get(0)) + assertEquals(1.1.toBigDecimal(), returned.numberArray?.get(0)) + assertEquals("value1", returned.stringArray?.get(0)) - assertNull(returned.numberArray?.get(1)) - assertNull(returned.stringArray?.get(1)) - } + assertNull(returned.numberArray?.get(1)) + assertNull(returned.stringArray?.get(1)) + } } diff --git a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/xnullable/XnullableRequiredPropertyMapEndpointTest.kt b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/xnullable/XnullableRequiredPropertyMapEndpointTest.kt index 9d11132e..578eeab7 100644 --- a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/xnullable/XnullableRequiredPropertyMapEndpointTest.kt +++ b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/xnullable/XnullableRequiredPropertyMapEndpointTest.kt @@ -12,60 +12,60 @@ import org.junit.Test class XnullableRequiredPropertyMapEndpointTest { - @get:Rule - val rule = MockServerApiRule() - - @Test - fun xNullableRequiredPropertyMap_withAllEmpty() { - rule.server.enqueue( - MockResponse().setBody( - """ + @get:Rule + val rule = MockServerApiRule() + + @Test + fun xNullableRequiredPropertyMap_withAllEmpty() { + rule.server.enqueue( + MockResponse().setBody( + """ { "number_map": {}, "object_map": {}, "string_map": {} } - """.trimIndent() - ) - ) - - val returned = rule.getApi().getXnullableRequiredPropertyMap("empty").blockingGet() - - assertNotNull(returned.numberMap) - assertNotNull(returned.objectMap) - assertNotNull(returned.stringMap) - - assertTrue(returned.numberMap?.isEmpty()!!) - assertTrue(returned.objectMap?.isEmpty()!!) - assertTrue(returned.stringMap?.isEmpty()!!) - } - - @Test - fun xNullableRequiredPropertyMap_withAllNull() { - rule.server.enqueue( - MockResponse().setBody( - """ + """.trimIndent() + ) + ) + + val returned = rule.getApi().getXnullableRequiredPropertyMap("empty").blockingGet() + + assertNotNull(returned.numberMap) + assertNotNull(returned.objectMap) + assertNotNull(returned.stringMap) + + assertTrue(returned.numberMap?.isEmpty()!!) + assertTrue(returned.objectMap?.isEmpty()!!) + assertTrue(returned.stringMap?.isEmpty()!!) + } + + @Test + fun xNullableRequiredPropertyMap_withAllNull() { + rule.server.enqueue( + MockResponse().setBody( + """ { "number_map": null, "object_map": null, "string_map": null } - """.trimIndent() - ) - ) - - val returned = rule.getApi().getXnullableRequiredPropertyMap("null").blockingGet() - - assertNull(returned.numberMap) - assertNull(returned.objectMap) - assertNull(returned.stringMap) - } - - @Test - fun xNullableRequiredPropertyMap_withAllOneNullElement() { - rule.server.enqueue( - MockResponse().setBody( - """ + """.trimIndent() + ) + ) + + val returned = rule.getApi().getXnullableRequiredPropertyMap("null").blockingGet() + + assertNull(returned.numberMap) + assertNull(returned.objectMap) + assertNull(returned.stringMap) + } + + @Test + fun xNullableRequiredPropertyMap_withAllOneNullElement() { + rule.server.enqueue( + MockResponse().setBody( + """ { "number_map": { "key1": null @@ -77,26 +77,26 @@ class XnullableRequiredPropertyMapEndpointTest { "key1": null } } - """.trimIndent() - ) - ) - - val returned = rule.getApi().getXnullableRequiredPropertyMap("1null").blockingGet() - - assertEquals(1, returned.numberMap?.size) - assertEquals(1, returned.objectMap?.size) - assertEquals(1, returned.stringMap?.size) - - assertNull(returned.numberMap?.get("key1")) - assertNull(returned.objectMap?.get("key1")) - assertNull(returned.stringMap?.get("key1")) - } - - @Test - fun xNullableRequiredPropertyMap_withAllTwoElements() { - rule.server.enqueue( - MockResponse().setBody( - """ + """.trimIndent() + ) + ) + + val returned = rule.getApi().getXnullableRequiredPropertyMap("1null").blockingGet() + + assertEquals(1, returned.numberMap?.size) + assertEquals(1, returned.objectMap?.size) + assertEquals(1, returned.stringMap?.size) + + assertNull(returned.numberMap?.get("key1")) + assertNull(returned.objectMap?.get("key1")) + assertNull(returned.stringMap?.get("key1")) + } + + @Test + fun xNullableRequiredPropertyMap_withAllTwoElements() { + rule.server.enqueue( + MockResponse().setBody( + """ { "number_map": { "key1": 1.1, @@ -113,22 +113,22 @@ class XnullableRequiredPropertyMapEndpointTest { "key2": null } } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullableRequiredPropertyMap("2").blockingGet() + val returned = rule.getApi().getXnullableRequiredPropertyMap("2").blockingGet() - assertEquals(2, returned.numberMap?.size) - assertEquals(2, returned.objectMap?.size) - assertEquals(2, returned.stringMap?.size) + assertEquals(2, returned.numberMap?.size) + assertEquals(2, returned.objectMap?.size) + assertEquals(2, returned.stringMap?.size) - assertEquals(1.1.toBigDecimal(), returned.numberMap?.get("key1")) - assertEquals("value1", (returned.objectMap?.get("key1") as List<*>)[0]) - assertEquals("value1", returned.stringMap?.get("key1")) + assertEquals(1.1.toBigDecimal(), returned.numberMap?.get("key1")) + assertEquals("value1", (returned.objectMap?.get("key1") as List<*>)[0]) + assertEquals("value1", returned.stringMap?.get("key1")) - assertNull(returned.numberMap?.get("key2")) - assertNull(returned.objectMap?.get("key2")) - assertNull(returned.stringMap?.get("key2")) - } + assertNull(returned.numberMap?.get("key2")) + assertNull(returned.objectMap?.get("key2")) + assertNull(returned.stringMap?.get("key2")) + } } diff --git a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/xnullable/XnullableRequiredTypeEndpointTest.kt b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/xnullable/XnullableRequiredTypeEndpointTest.kt index 32da59d8..a33b1975 100644 --- a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/xnullable/XnullableRequiredTypeEndpointTest.kt +++ b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/xnullable/XnullableRequiredTypeEndpointTest.kt @@ -10,14 +10,14 @@ import org.junit.Test class XnullableRequiredTypeEndpointTest { - @get:Rule - val rule = MockServerApiRule() + @get:Rule + val rule = MockServerApiRule() - @Test - fun xNullableTypeEndpoint_withStringType() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun xNullableTypeEndpoint_withStringType() { + rule.server.enqueue( + MockResponse().setBody( + """ { "boolean_property": true, "enum_property": "VALUE1", @@ -25,23 +25,23 @@ class XnullableRequiredTypeEndpointTest { "number_property": 1.2, "string_property": null } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullableRequiredTypeEndpoint("string").blockingGet() - assertNotNull(returned.integerProperty) - assertNotNull(returned.booleanProperty) - assertNotNull(returned.enumProperty) - assertNotNull(returned.numberProperty) - assertNull(returned.stringProperty) - } + val returned = rule.getApi().getXnullableRequiredTypeEndpoint("string").blockingGet() + assertNotNull(returned.integerProperty) + assertNotNull(returned.booleanProperty) + assertNotNull(returned.enumProperty) + assertNotNull(returned.numberProperty) + assertNull(returned.stringProperty) + } - @Test - fun xNullableTypeEndpoint_withBooleanType() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun xNullableTypeEndpoint_withBooleanType() { + rule.server.enqueue( + MockResponse().setBody( + """ { "boolean_property": null, "enum_property": "VALUE1", @@ -49,23 +49,23 @@ class XnullableRequiredTypeEndpointTest { "number_property": 1.2, "string_property": "string" } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullableRequiredTypeEndpoint("boolean").blockingGet() - assertNotNull(returned.integerProperty) - assertNull(returned.booleanProperty) - assertNotNull(returned.enumProperty) - assertNotNull(returned.numberProperty) - assertNotNull(returned.stringProperty) - } + val returned = rule.getApi().getXnullableRequiredTypeEndpoint("boolean").blockingGet() + assertNotNull(returned.integerProperty) + assertNull(returned.booleanProperty) + assertNotNull(returned.enumProperty) + assertNotNull(returned.numberProperty) + assertNotNull(returned.stringProperty) + } - @Test - fun xNullableTypeEndpoint_withIntegerType() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun xNullableTypeEndpoint_withIntegerType() { + rule.server.enqueue( + MockResponse().setBody( + """ { "boolean_property": true, "enum_property": "VALUE1", @@ -73,23 +73,23 @@ class XnullableRequiredTypeEndpointTest { "number_property": 1.2, "string_property": "string" } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullableRequiredTypeEndpoint("integer").blockingGet() - assertNull(returned.integerProperty) - assertNotNull(returned.booleanProperty) - assertNotNull(returned.enumProperty) - assertNotNull(returned.numberProperty) - assertNotNull(returned.stringProperty) - } + val returned = rule.getApi().getXnullableRequiredTypeEndpoint("integer").blockingGet() + assertNull(returned.integerProperty) + assertNotNull(returned.booleanProperty) + assertNotNull(returned.enumProperty) + assertNotNull(returned.numberProperty) + assertNotNull(returned.stringProperty) + } - @Test - fun xNullableTypeEndpoint_withNumberType() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun xNullableTypeEndpoint_withNumberType() { + rule.server.enqueue( + MockResponse().setBody( + """ { "boolean_property": true, "enum_property": "VALUE1", @@ -97,23 +97,23 @@ class XnullableRequiredTypeEndpointTest { "number_property": null, "string_property": "string" } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullableRequiredTypeEndpoint("number").blockingGet() - assertNotNull(returned.integerProperty) - assertNotNull(returned.booleanProperty) - assertNotNull(returned.enumProperty) - assertNull(returned.numberProperty) - assertNotNull(returned.stringProperty) - } + val returned = rule.getApi().getXnullableRequiredTypeEndpoint("number").blockingGet() + assertNotNull(returned.integerProperty) + assertNotNull(returned.booleanProperty) + assertNotNull(returned.enumProperty) + assertNull(returned.numberProperty) + assertNotNull(returned.stringProperty) + } - @Test - fun xNullableTypeEndpoint_withEnumType() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun xNullableTypeEndpoint_withEnumType() { + rule.server.enqueue( + MockResponse().setBody( + """ { "boolean_property": true, "enum_property": null, @@ -121,15 +121,15 @@ class XnullableRequiredTypeEndpointTest { "number_property": 1.1, "string_property": "string" } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullableRequiredTypeEndpoint("enum").blockingGet() - assertNotNull(returned.integerProperty) - assertNotNull(returned.booleanProperty) - assertNull(returned.enumProperty) - assertNotNull(returned.numberProperty) - assertNotNull(returned.stringProperty) - } + val returned = rule.getApi().getXnullableRequiredTypeEndpoint("enum").blockingGet() + assertNotNull(returned.integerProperty) + assertNotNull(returned.booleanProperty) + assertNull(returned.enumProperty) + assertNotNull(returned.numberProperty) + assertNotNull(returned.stringProperty) + } } diff --git a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/xnullable/XnullableTypeEndpointTest.kt b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/xnullable/XnullableTypeEndpointTest.kt index 77cf7e27..d55176a8 100644 --- a/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/xnullable/XnullableTypeEndpointTest.kt +++ b/samples/junit-tests/src/test/java/com/yelp/codegen/generatecodesamples/xnullable/XnullableTypeEndpointTest.kt @@ -9,86 +9,86 @@ import org.junit.Test class XnullableTypeEndpointTest { - @get:Rule - val rule = MockServerApiRule() + @get:Rule + val rule = MockServerApiRule() - @Test - fun xNullableTypeEndpoint_withStringType() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun xNullableTypeEndpoint_withStringType() { + rule.server.enqueue( + MockResponse().setBody( + """ { "string_property": null } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullableTypeEndpoint("string").blockingGet() - assertNull(returned.stringProperty) - } + val returned = rule.getApi().getXnullableTypeEndpoint("string").blockingGet() + assertNull(returned.stringProperty) + } - @Test - fun xNullableTypeEndpoint_withBooleanType() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun xNullableTypeEndpoint_withBooleanType() { + rule.server.enqueue( + MockResponse().setBody( + """ { "boolean_property": null } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullableTypeEndpoint("boolean").blockingGet() - assertNull(returned.booleanProperty) - } + val returned = rule.getApi().getXnullableTypeEndpoint("boolean").blockingGet() + assertNull(returned.booleanProperty) + } - @Test - fun xNullableTypeEndpoint_withIntegerType() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun xNullableTypeEndpoint_withIntegerType() { + rule.server.enqueue( + MockResponse().setBody( + """ { "integer_property": null } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullableTypeEndpoint("integer").blockingGet() - assertNull(returned.integerProperty) - } + val returned = rule.getApi().getXnullableTypeEndpoint("integer").blockingGet() + assertNull(returned.integerProperty) + } - @Test - fun xNullableTypeEndpoint_withNumberType() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun xNullableTypeEndpoint_withNumberType() { + rule.server.enqueue( + MockResponse().setBody( + """ { "number_property": null } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullableTypeEndpoint("number").blockingGet() - assertNull(returned.numberProperty) - } + val returned = rule.getApi().getXnullableTypeEndpoint("number").blockingGet() + assertNull(returned.numberProperty) + } - @Test - fun xNullableTypeEndpoint_withEnumType() { - rule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun xNullableTypeEndpoint_withEnumType() { + rule.server.enqueue( + MockResponse().setBody( + """ { "enum_property": null } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - val returned = rule.getApi().getXnullableTypeEndpoint("enum").blockingGet() - assertNull(returned.enumProperty) - } + val returned = rule.getApi().getXnullableTypeEndpoint("enum").blockingGet() + assertNull(returned.enumProperty) + } } diff --git a/samples/kotlin-android/build.gradle.kts b/samples/kotlin-android/build.gradle.kts index a104be21..b45ba40b 100644 --- a/samples/kotlin-android/build.gradle.kts +++ b/samples/kotlin-android/build.gradle.kts @@ -2,6 +2,7 @@ plugins { id("com.android.library") kotlin("android") id("com.yelp.codegen.plugin") + kotlin("plugin.serialization") version "1.3.70" } android { @@ -18,12 +19,10 @@ dependencies { // Kotlin implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.70") - // Moshi + OkHttp + Retrofit - implementation("com.squareup.moshi:moshi:1.9.2") - implementation("com.squareup.moshi:moshi-adapters:1.9.2") + // kotlinx.serialization + OkHttp + Retrofit + implementation("org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.20.0") implementation("com.squareup.okhttp3:okhttp:3.12.3") implementation("com.squareup.retrofit2:retrofit:2.7.1") - implementation("com.squareup.retrofit2:converter-moshi:2.7.1") implementation("com.squareup.retrofit2:adapter-rxjava2:2.7.1") // Date Support diff --git a/samples/kotlin-coroutines/build.gradle b/samples/kotlin-coroutines/build.gradle index 2b0a584f..11323ca9 100644 --- a/samples/kotlin-coroutines/build.gradle +++ b/samples/kotlin-coroutines/build.gradle @@ -3,6 +3,7 @@ plugins { id("kotlin-android") id("com.yelp.codegen.plugin") id("kotlin-kapt") + id 'org.jetbrains.kotlin.plugin.serialization' version '1.3.70' } android { @@ -19,13 +20,11 @@ dependencies { // Kotlin implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.70" - // Moshi + OkHttp + Retrofit - implementation "com.squareup.moshi:moshi:1.9.2" - implementation "com.squareup.moshi:moshi-adapters:1.9.2" + // kotlinx.serialization + OkHttp + Retrofit + implementation("org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.20.0") implementation "com.squareup.okhttp3:okhttp:3.12.3" implementation "com.squareup.retrofit2:retrofit:2.7.1" - implementation "com.squareup.retrofit2:converter-moshi:2.7.1" - kapt "com.squareup.moshi:moshi-kotlin-codegen:1.9.2" + implementation("com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:0.5.0") // Date Support implementation "com.jakewharton.threetenabp:threetenabp:1.2.2" diff --git a/samples/kotlin-coroutines/src/test/java/com/yelp/codegen/samples/kotlincoroutines/CoroutinesEndpointsTest.kt b/samples/kotlin-coroutines/src/test/java/com/yelp/codegen/samples/kotlincoroutines/CoroutinesEndpointsTest.kt index 4a1428d2..3a790c95 100644 --- a/samples/kotlin-coroutines/src/test/java/com/yelp/codegen/samples/kotlincoroutines/CoroutinesEndpointsTest.kt +++ b/samples/kotlin-coroutines/src/test/java/com/yelp/codegen/samples/kotlincoroutines/CoroutinesEndpointsTest.kt @@ -15,68 +15,68 @@ import org.junit.Test @ExperimentalCoroutinesApi class CoroutinesEndpointsTest { - @get:Rule - val mockServerRule = MockServerApiRule() + @get:Rule + val mockServerRule = MockServerApiRule() - @get:Rule - val coroutinesRule = CoroutineDispatcherRule() + @get:Rule + val coroutinesRule = CoroutineDispatcherRule() - @Test - fun emptyEndpointTest() { - mockServerRule.server.enqueue(MockResponse().setBody("{}")) + @Test + fun emptyEndpointTest() { + mockServerRule.server.enqueue(MockResponse().setBody("{}")) - coroutinesRule.runBlockingTest { - val returned = mockServerRule.getApi().getEmptyEndpoint() - assertNotNull(returned) - } + coroutinesRule.runBlockingTest { + val returned = mockServerRule.getApi().getEmptyEndpoint() + assertNotNull(returned) } + } - @Test - fun propertyEndpointTest_withStringProperty() { - mockServerRule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun propertyEndpointTest_withStringProperty() { + mockServerRule.server.enqueue( + MockResponse().setBody( + """ { "string_property": "string" } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - coroutinesRule.runBlockingTest { - val returned = mockServerRule.getApi().getPropertyEndpoint("string") - assertEquals("string", returned.stringProperty) - assertNull(returned.enumProperty) - } + coroutinesRule.runBlockingTest { + val returned = mockServerRule.getApi().getPropertyEndpoint("string") + assertEquals("string", returned.stringProperty) + assertNull(returned.enumProperty) } + } - @Test - fun propertyEndpointTest_withEnumProperty() { - mockServerRule.server.enqueue( - MockResponse().setBody( - """ + @Test + fun propertyEndpointTest_withEnumProperty() { + mockServerRule.server.enqueue( + MockResponse().setBody( + """ { "enum_property": "VALUE1" } - """.trimIndent() - ) - ) + """.trimIndent() + ) + ) - coroutinesRule.runBlockingTest { - val returned = mockServerRule.getApi().getPropertyEndpoint("string") - assertEquals(PropertyModel.EnumPropertyEnum.VALUE1, returned.enumProperty) - assertNull(returned.stringProperty) - } + coroutinesRule.runBlockingTest { + val returned = mockServerRule.getApi().getPropertyEndpoint("string") + assertEquals(PropertyModel.EnumPropertyEnum.VALUE1, returned.enumProperty) + assertNull(returned.stringProperty) } + } - @Test - fun propertyEndpointTest_withEmptyObject() { - mockServerRule.server.enqueue(MockResponse().setBody("{}")) + @Test + fun propertyEndpointTest_withEmptyObject() { + mockServerRule.server.enqueue(MockResponse().setBody("{}")) - coroutinesRule.runBlockingTest { - val returned = mockServerRule.getApi().getPropertyEndpoint("string") - assertNull(returned.stringProperty) - assertNull(returned.enumProperty) - } + coroutinesRule.runBlockingTest { + val returned = mockServerRule.getApi().getPropertyEndpoint("string") + assertNull(returned.stringProperty) + assertNull(returned.enumProperty) } + } } diff --git a/samples/kotlin-coroutines/src/test/java/com/yelp/codegen/samples/kotlincoroutines/tools/CoroutineDispatcherRule.kt b/samples/kotlin-coroutines/src/test/java/com/yelp/codegen/samples/kotlincoroutines/tools/CoroutineDispatcherRule.kt index 346e137d..2c5ae2e4 100644 --- a/samples/kotlin-coroutines/src/test/java/com/yelp/codegen/samples/kotlincoroutines/tools/CoroutineDispatcherRule.kt +++ b/samples/kotlin-coroutines/src/test/java/com/yelp/codegen/samples/kotlincoroutines/tools/CoroutineDispatcherRule.kt @@ -18,20 +18,20 @@ import org.junit.rules.ExternalResource @ExperimentalCoroutinesApi class CoroutineDispatcherRule : ExternalResource() { - private val testCoroutineDispatcher = TestCoroutineDispatcher() - private val testCoroutineScope = TestCoroutineScope(testCoroutineDispatcher) + private val testCoroutineDispatcher = TestCoroutineDispatcher() + private val testCoroutineScope = TestCoroutineScope(testCoroutineDispatcher) - override fun before() { - super.before() - Dispatchers.setMain(testCoroutineDispatcher) - } + override fun before() { + super.before() + Dispatchers.setMain(testCoroutineDispatcher) + } - override fun after() { - Dispatchers.resetMain() - testCoroutineScope.cleanupTestCoroutines() - super.after() - } + override fun after() { + Dispatchers.resetMain() + testCoroutineScope.cleanupTestCoroutines() + super.after() + } - fun runBlockingTest(block: suspend CoroutineScope.() -> Unit) = - runBlocking(Dispatchers.Main, block) + fun runBlockingTest(block: suspend CoroutineScope.() -> Unit) = + runBlocking(Dispatchers.Main, block) } diff --git a/samples/kotlin-coroutines/src/test/java/com/yelp/codegen/samples/kotlincoroutines/tools/MockServerApiRule.kt b/samples/kotlin-coroutines/src/test/java/com/yelp/codegen/samples/kotlincoroutines/tools/MockServerApiRule.kt index e239b19c..4e0491d3 100644 --- a/samples/kotlin-coroutines/src/test/java/com/yelp/codegen/samples/kotlincoroutines/tools/MockServerApiRule.kt +++ b/samples/kotlin-coroutines/src/test/java/com/yelp/codegen/samples/kotlincoroutines/tools/MockServerApiRule.kt @@ -1,5 +1,8 @@ package com.yelp.codegen.samples.kotlincoroutines.tools +import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory +import kotlinx.serialization.json.Json +import okhttp3.MediaType import okhttp3.mockwebserver.MockWebServer import org.junit.rules.ExternalResource import retrofit2.Retrofit @@ -10,25 +13,26 @@ import retrofit2.Retrofit */ class MockServerApiRule : ExternalResource() { - lateinit var retrofit: Retrofit - val server = MockWebServer() + lateinit var retrofit: Retrofit + val server = MockWebServer() - override fun before() { - super.before() - server.start() + override fun before() { + super.before() + server.start() - retrofit = Retrofit.Builder() - .addConverterFactory(GeneratedCodeConverters.converterFactory()) - .baseUrl(server.url("/")) - .build() - } + val contentType = MediaType.get("application/json") + retrofit = Retrofit.Builder() + .addConverterFactory(Json.asConverterFactory(contentType)) + .baseUrl(server.url("/")) + .build() + } - override fun after() { - server.shutdown() - super.after() - } + override fun after() { + server.shutdown() + super.after() + } - inline fun getApi(): T { - return retrofit.create(T::class.java) - } + inline fun getApi(): T { + return retrofit.create(T::class.java) + } }