From 2e2684779ae87930127724c523eafa37bde80861 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Brage=20Skj=C3=B8nborg?= Date: Sun, 12 Jul 2026 03:04:29 +0200 Subject: [PATCH] Tests + splitt --- build.gradle.kts | 48 ++-- src/main/kotlin/no/iktdev/ts/ClassScanner.kt | 41 ++++ src/main/kotlin/no/iktdev/ts/TsGenerator.kt | 225 +----------------- .../kotlin/no/iktdev/ts/TsModelRenderer.kt | 85 +++++++ src/main/kotlin/no/iktdev/ts/TsTypeMapper.kt | 86 +++++++ src/main/kotlin/no/iktdev/ts/Util.kt | 23 ++ .../no/iktdev/tsgen/TSGeneratorPlugin.kt | 24 +- .../kotlin/no/iktdev/ts/ClassScannerTest.kt | 16 ++ .../no/iktdev/ts/TsModelRendererTest.kt | 51 ++++ .../kotlin/no/iktdev/ts/TsTypeMapperTest.kt | 54 +++++ src/test/kotlin/no/iktdev/ts/models/Parent.kt | 20 ++ 11 files changed, 429 insertions(+), 244 deletions(-) create mode 100644 src/main/kotlin/no/iktdev/ts/ClassScanner.kt create mode 100644 src/main/kotlin/no/iktdev/ts/TsModelRenderer.kt create mode 100644 src/main/kotlin/no/iktdev/ts/TsTypeMapper.kt create mode 100644 src/main/kotlin/no/iktdev/ts/Util.kt create mode 100644 src/test/kotlin/no/iktdev/ts/ClassScannerTest.kt create mode 100644 src/test/kotlin/no/iktdev/ts/TsModelRendererTest.kt create mode 100644 src/test/kotlin/no/iktdev/ts/TsTypeMapperTest.kt create mode 100644 src/test/kotlin/no/iktdev/ts/models/Parent.kt diff --git a/build.gradle.kts b/build.gradle.kts index 2b4fb37..6c44820 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -13,6 +13,17 @@ repositories { mavenCentral() } +gradlePlugin { + plugins { + create("tsGenerator") { + id = "no.iktdev.ts-gen" + implementationClass = "no.iktdev.tsgen.TsGeneratorPlugin" + // Denne er viktig for Gradle-menyen: + displayName = "TS Generator" + description = "Genererer TypeScript definisjoner fra Kotlin DTO-er" + } + } +} dependencies { @@ -20,6 +31,19 @@ dependencies { implementation("com.google.code.gson:gson:2.8.9") implementation(kotlin("reflect")) implementation(kotlin("stdlib")) + + testImplementation("org.assertj:assertj-core:3.27.7") + testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.2") + + // Bruk BOM for å styre alle JUnit-versjoner automatisk + testImplementation(platform("org.junit:junit-bom:5.10.2")) + testImplementation("org.junit.jupiter:junit-jupiter") + testRuntimeOnly("org.junit.platform:junit-platform-launcher") + +} + +tasks.test { + useJUnitPlatform() } kotlin { @@ -34,28 +58,18 @@ val reposiliteUrl = if (version.toString().endsWith("SNAPSHOT")) { publishing { publications { - create("reposilite") { - artifactId = named - versionMapping { - usage("java-api") { - fromResolutionOf("runtimeClasspath") - } - usage("java-runtime") { - fromResolutionResult() - } - } - pom { - name.set(named) - version = project.version.toString() - url.set(reposiliteUrl) - } - from(components["kotlin"]) + // 'pluginMaven' er den magiske tingen du trenger når du bruker java-gradle-plugin + create("plugin") { + from(components["java"]) + groupId = "no.iktdev" + artifactId = "ts-gen" // Dette er navnet du refererer til + version = project.version.toString() } } repositories { mavenLocal() maven { - name = named + name = "reposilite" url = uri(reposiliteUrl) credentials { username = System.getenv("reposiliteUsername") diff --git a/src/main/kotlin/no/iktdev/ts/ClassScanner.kt b/src/main/kotlin/no/iktdev/ts/ClassScanner.kt new file mode 100644 index 0000000..e1e8b97 --- /dev/null +++ b/src/main/kotlin/no/iktdev/ts/ClassScanner.kt @@ -0,0 +1,41 @@ +package no.iktdev.ts + +import java.io.File +import kotlin.reflect.KClass + +class ClassScanner { + fun scan(packageName: String, classLoader: ClassLoader): List> { + val path = packageName.replace('.', '/') + println("TsGenerator: looking for resources at path: $path") + + val resources = classLoader.getResources(path) + + val classes = mutableListOf>() + + if (!resources.hasMoreElements()) { + println("TsGenerator: NO RESOURCES FOUND for path: $path") + } + + while (resources.hasMoreElements()) { + val url = resources.nextElement() + println("TsGenerator: resource URL = $url") + + val file = File(url.toURI()) + println("TsGenerator: resolved file = ${file.absolutePath}, exists=${file.exists()}, isDir=${file.isDirectory}") + + if (file.exists() && file.isDirectory) { + file.walkTopDown().forEach { f -> + if (f.extension == "class") { + val className = f.toClassName(path) + try { + val cls = Class.forName(className, false, classLoader).kotlin + classes.add(cls) + } catch (_: Throwable) {} + } + } + } + } + + return classes + } +} \ No newline at end of file diff --git a/src/main/kotlin/no/iktdev/ts/TsGenerator.kt b/src/main/kotlin/no/iktdev/ts/TsGenerator.kt index 2624f61..504774e 100644 --- a/src/main/kotlin/no/iktdev/ts/TsGenerator.kt +++ b/src/main/kotlin/no/iktdev/ts/TsGenerator.kt @@ -1,16 +1,15 @@ package no.iktdev.ts import java.io.File -import kotlin.reflect.KClass -import kotlin.reflect.full.memberProperties -import kotlin.reflect.full.primaryConstructor object TsGenerator { + val ttm = TsTypeMapper() + val tmr = TsModelRenderer() fun generate(packageName: String, output: File, classLoader: ClassLoader = Thread.currentThread().contextClassLoader) { println("TsGenerator: scanning package: $packageName") - val classes = scanClasses(packageName, classLoader) + val classes = ClassScanner().scan(packageName, classLoader) println("TsGenerator: found ${classes.size} classes total") classes.forEach { println(" - ${it.qualifiedName}") } @@ -51,7 +50,7 @@ object TsGenerator { // ---------------------------------------------------- cls.isSealedSubtype() -> { println("Generating sealed subtype interface: ${cls.simpleName}") - append(sealedSubtypeToTs(cls)) + append(tmr.sealedSubtypeToTs(cls)) } // ---------------------------------------------------- @@ -59,7 +58,7 @@ object TsGenerator { // ---------------------------------------------------- cls.java.isEnum -> { println("Generating enum: ${cls.simpleName}") - append(enumToTs(cls)) + append(tmr.enumToTs(cls)) } // ---------------------------------------------------- @@ -67,7 +66,7 @@ object TsGenerator { // ---------------------------------------------------- cls.hasProperties() && !cls.isSealed -> { println("Generating interface: ${cls.simpleName}") - append(dataClassToTs(cls)) + append(tmr.dataClassToTs(cls, ttm)) } else -> { @@ -84,216 +83,4 @@ object TsGenerator { println("TsGenerator: wrote file to ${output.absolutePath}") } - private fun File.toClassName(rootPath: String): String { - val full = this.path.replace(File.separatorChar, '/') - val idx = full.indexOf(rootPath) - val relative = full.substring(idx) - return relative - .removeSuffix(".class") - .replace('/', '.') - } - - private fun KClass<*>.hasProperties(): Boolean = - this.memberProperties.isNotEmpty() - - // sealed subtype = har en sealed supertype - private fun KClass<*>.isSealedSubtype(): Boolean = - this.supertypes - .mapNotNull { it.classifier as? KClass<*> } - .any { it.isSealed } - - // ------------------------------------------------------------ - // Kotlin → TS mapping - // ------------------------------------------------------------ - - private fun enumToTs(cls: KClass<*>): String { - val values = cls.java.enumConstants - .joinToString(" | ") { "\"$it\"" } - - return "export type ${cls.simpleName} = $values\n" - } - - private fun sealedSubtypeToTs(cls: KClass<*>): String { - val props = cls.memberProperties - .filter { it.name != "type" } // ← FIX: unngå duplisering - .joinToString("\n") { prop -> - val tsType = kotlinToTsType(prop.returnType.toString()) - " ${prop.name}: $tsType;" - } - - val propsBlock = if (props.isBlank()) "" else "\n$props" - - return buildString { - appendLine("export interface ${cls.simpleName} {") - appendLine(" type: \"${cls.simpleName}\";$propsBlock") - appendLine("}") - } - } - - - // NEW: extract default value for "type" discriminator - private fun getDefaultTypeLiteral(cls: KClass<*>): String? { - val ctor = cls.primaryConstructor ?: return null - val param = ctor.parameters.find { it.name == "type" } ?: return null - - return try { - val instance = ctor.callBy(emptyMap()) - val prop = cls.memberProperties.find { it.name == "type" } - prop?.getter?.call(instance)?.toString() - } catch (_: Throwable) { - null - } - } - - private fun dataClassToTs(cls: KClass<*>): String { - val typeParams = cls.typeParameters.map { it.name } - val generic = if (typeParams.isNotEmpty()) { - "<" + typeParams.joinToString(", ") + ">" - } else "" - - val defaultTypeLiteral = getDefaultTypeLiteral(cls) - - val props = cls.memberProperties.joinToString("\n") { prop -> - val tsType = - if (prop.name == "type" && defaultTypeLiteral != null) { - "\"$defaultTypeLiteral\"" // literal type - } else { - kotlinToTsType(prop.returnType.toString(), typeParams) - } - - " ${prop.name}: $tsType;" - } - - return buildString { - appendLine("export interface ${cls.simpleName}$generic {") - appendLine(props) - appendLine("}") - } - } - - // ------------------------------------------------------------ - // Type mapping - // ------------------------------------------------------------ - - private fun kotlinToTsType(kotlinType: String, genericParams: List = emptyList()): String { - val isNullable = kotlinType.endsWith("?") - val clean = kotlinType.removeSuffix("?") - - // UUID → string - if (clean == "java.util.UUID") { - return if (isNullable) "string | null" else "string" - } - - // Instant → string - if (clean == "java.time.Instant") { - return if (isNullable) "string | null" else "string" - } - - // Duration → string - if (clean in listOf("kotlin.time.Duration", "java.time.Duration")) { - return if (isNullable) "string | null" else "string" - } - - // Map → Record - if (clean.startsWith("kotlin.collections.Map") || - clean.startsWith("kotlin.collections.MutableMap")) { - - val inner = clean.substringAfter("<").substringBeforeLast(">") - val (key, value) = inner.split(",").map { it.trim() } - - val tsKey = kotlinToTsType(key, genericParams) - val tsValue = kotlinToTsType(value, genericParams) - - val base = "Record<$tsKey, $tsValue>" - return if (isNullable) "$base | null" else base - } - - // Set → T[] - if (clean.startsWith("kotlin.collections.Set") || - clean.startsWith("kotlin.collections.MutableSet")) { - - val inner = clean.substringAfter("<").substringBeforeLast(">") - - if (genericParams.contains(inner)) { - val base = "${inner}[]" - return if (isNullable) "$base | null" else base - } - - val tsInner = kotlinToTsType(inner, genericParams) - val base = "$tsInner[]" - return if (isNullable) "$base | null" else base - } - - // List → T[] - if (clean.startsWith("kotlin.collections.List") || - clean.startsWith("kotlin.collections.MutableList")) { - - val inner = clean.substringAfter("<").substringBeforeLast(">") - - if (genericParams.contains(inner)) { - val base = "${inner}[]" - return if (isNullable) "$base | null" else base - } - - val tsInner = kotlinToTsType(inner, genericParams) - val base = "$tsInner[]" - return if (isNullable) "$base | null" else base - } - - // Primitive mappings - val base = when (clean) { - "kotlin.String" -> "string" - "kotlin.Int", - "kotlin.Long", - "kotlin.Float", - "kotlin.Double" -> "number" - "kotlin.Boolean" -> "boolean" - "kotlin.Any" -> "any" - else -> { - if (clean.contains(".")) clean.substringAfterLast(".") - else "any" - } - } - - return if (isNullable) "$base | null" else base - } - - // ------------------------------------------------------------ - // Class scanning - // ------------------------------------------------------------ - - private fun scanClasses(packageName: String, classLoader: ClassLoader): List> { - val path = packageName.replace('.', '/') - println("TsGenerator: looking for resources at path: $path") - - val resources = classLoader.getResources(path) - - val classes = mutableListOf>() - - if (!resources.hasMoreElements()) { - println("TsGenerator: NO RESOURCES FOUND for path: $path") - } - - while (resources.hasMoreElements()) { - val url = resources.nextElement() - println("TsGenerator: resource URL = $url") - - val file = File(url.toURI()) - println("TsGenerator: resolved file = ${file.absolutePath}, exists=${file.exists()}, isDir=${file.isDirectory}") - - if (file.exists() && file.isDirectory) { - file.walkTopDown().forEach { f -> - if (f.extension == "class") { - val className = f.toClassName(path) - try { - val cls = Class.forName(className, false, classLoader).kotlin - classes.add(cls) - } catch (_: Throwable) {} - } - } - } - } - - return classes - } } diff --git a/src/main/kotlin/no/iktdev/ts/TsModelRenderer.kt b/src/main/kotlin/no/iktdev/ts/TsModelRenderer.kt new file mode 100644 index 0000000..f087836 --- /dev/null +++ b/src/main/kotlin/no/iktdev/ts/TsModelRenderer.kt @@ -0,0 +1,85 @@ +package no.iktdev.ts + +import no.iktdev.ts.TsGenerator.ttm +import kotlin.reflect.KClass +import kotlin.reflect.full.memberProperties +import kotlin.reflect.full.primaryConstructor + +class TsModelRenderer { + fun enumToTs(cls: KClass<*>): String { + val values = cls.java.enumConstants + .joinToString(" | ") { "\"$it\"" } + + return "export type ${cls.simpleName} = $values\n" + } + + fun sealedSubtypeToTs(cls: KClass<*>): String { + val props = cls.memberProperties + .filter { it.name != "type" } // ← FIX: unngå duplisering + .joinToString("\n") { prop -> + val tsType = ttm.kotlinToTsType(prop.returnType.toString()) + " ${prop.name}: $tsType;" + } + + val propsBlock = if (props.isBlank()) "" else "\n$props" + + return buildString { + appendLine("export interface ${cls.simpleName} {") + appendLine(" type: \"${cls.simpleName}\";$propsBlock") + appendLine("}") + } + } + + + // NEW: extract default value for "type" discriminator + fun getDefaultTypeLiteral(cls: KClass<*>): String? { + val ctor = cls.primaryConstructor ?: return null + val param = ctor.parameters.find { it.name == "type" } ?: return null + + return try { + val instance = ctor.callBy(emptyMap()) + val prop = cls.memberProperties.find { it.name == "type" } + prop?.getter?.call(instance)?.toString() + } catch (_: Throwable) { + null + } + } + + fun dataClassToTs(cls: KClass<*>, ttm: TsTypeMapper): String { + val typeParams = cls.typeParameters.map { it.name } + val generic = if (typeParams.isNotEmpty()) "<" + typeParams.joinToString(", ") + ">" else "" + + // 1. Finn alle super-interfacer (ekskluder Any/Object) + val superInterfaces = cls.supertypes + .mapNotNull { it.classifier as? KClass<*> } + .filter { it.java.isInterface && it.simpleName != "Any" } + + // 2. Lag "extends"-biten + val extendsClause = if (superInterfaces.isNotEmpty()) { + " extends ${superInterfaces.joinToString(", ") { it.simpleName!! }}" + } else "" + + // 3. Finn navn på egenskaper som finnes i super-interfacer, så vi unngår duplikater + val inheritedPropNames = superInterfaces.flatMap { it.memberProperties }.map { it.name }.toSet() + + val defaultTypeLiteral = getDefaultTypeLiteral(cls) + + // 4. Generer kun props som IKKE er arvet + val props = cls.memberProperties + .filter { it.name !in inheritedPropNames } + .joinToString("\n") { prop -> + val tsType = if (prop.name == "type" && defaultTypeLiteral != null) { + "\"$defaultTypeLiteral\"" + } else { + ttm.kotlinToTsType(prop.returnType.toString(), typeParams) + } + " ${prop.name}: $tsType;" + } + + return buildString { + appendLine("export interface ${cls.simpleName}$generic$extendsClause {") + if (props.isNotBlank()) appendLine(props) + appendLine("}") + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/no/iktdev/ts/TsTypeMapper.kt b/src/main/kotlin/no/iktdev/ts/TsTypeMapper.kt new file mode 100644 index 0000000..e7ab41e --- /dev/null +++ b/src/main/kotlin/no/iktdev/ts/TsTypeMapper.kt @@ -0,0 +1,86 @@ +package no.iktdev.ts + +class TsTypeMapper { + fun kotlinToTsType(kotlinType: String, genericParams: List = emptyList()): String { + val isNullable = kotlinType.endsWith("?") + val clean = kotlinType.removeSuffix("?") + + // UUID → string + if (clean == "java.util.UUID") { + return if (isNullable) "string | null" else "string" + } + + // Instant → string + if (clean == "java.time.Instant") { + return if (isNullable) "string | null" else "string" + } + + // Duration → string + if (clean in listOf("kotlin.time.Duration", "java.time.Duration")) { + return if (isNullable) "string | null" else "string" + } + + // Map → Record + if (clean.startsWith("kotlin.collections.Map") || + clean.startsWith("kotlin.collections.MutableMap")) { + + val inner = clean.substringAfter("<").substringBeforeLast(">") + val (key, value) = inner.split(",").map { it.trim() } + + val tsKey = kotlinToTsType(key, genericParams) + val tsValue = kotlinToTsType(value, genericParams) + + val base = "Record<$tsKey, $tsValue>" + return if (isNullable) "$base | null" else base + } + + // Set → T[] + if (clean.startsWith("kotlin.collections.Set") || + clean.startsWith("kotlin.collections.MutableSet")) { + + val inner = clean.substringAfter("<").substringBeforeLast(">") + + if (genericParams.contains(inner)) { + val base = "${inner}[]" + return if (isNullable) "$base | null" else base + } + + val tsInner = kotlinToTsType(inner, genericParams) + val base = "$tsInner[]" + return if (isNullable) "$base | null" else base + } + + // List → T[] + if (clean.startsWith("kotlin.collections.List") || + clean.startsWith("kotlin.collections.MutableList")) { + + val inner = clean.substringAfter("<").substringBeforeLast(">") + + if (genericParams.contains(inner)) { + val base = "${inner}[]" + return if (isNullable) "$base | null" else base + } + + val tsInner = kotlinToTsType(inner, genericParams) + val base = "$tsInner[]" + return if (isNullable) "$base | null" else base + } + + // Primitive mappings + val base = when (clean) { + "kotlin.String" -> "string" + "kotlin.Int", + "kotlin.Long", + "kotlin.Float", + "kotlin.Double" -> "number" + "kotlin.Boolean" -> "boolean" + "kotlin.Any" -> "any" + else -> { + if (clean.contains(".")) clean.substringAfterLast(".") + else "any" + } + } + + return if (isNullable) "$base | null" else base + } +} \ No newline at end of file diff --git a/src/main/kotlin/no/iktdev/ts/Util.kt b/src/main/kotlin/no/iktdev/ts/Util.kt new file mode 100644 index 0000000..f56cc2b --- /dev/null +++ b/src/main/kotlin/no/iktdev/ts/Util.kt @@ -0,0 +1,23 @@ +package no.iktdev.ts + +import java.io.File +import kotlin.reflect.KClass +import kotlin.reflect.full.memberProperties + +fun File.toClassName(rootPath: String): String { + val full = this.path.replace(File.separatorChar, '/') + val idx = full.indexOf(rootPath) + val relative = full.substring(idx) + return relative + .removeSuffix(".class") + .replace('/', '.') +} + +fun KClass<*>.hasProperties(): Boolean = + this.memberProperties.isNotEmpty() + +// sealed subtype = har en sealed supertype +fun KClass<*>.isSealedSubtype(): Boolean = + this.supertypes + .mapNotNull { it.classifier as? KClass<*> } + .any { it.isSealed } \ No newline at end of file diff --git a/src/main/kotlin/no/iktdev/tsgen/TSGeneratorPlugin.kt b/src/main/kotlin/no/iktdev/tsgen/TSGeneratorPlugin.kt index 44e1da5..37f7759 100644 --- a/src/main/kotlin/no/iktdev/tsgen/TSGeneratorPlugin.kt +++ b/src/main/kotlin/no/iktdev/tsgen/TSGeneratorPlugin.kt @@ -1,32 +1,40 @@ package no.iktdev.tsgen -import no.iktdev.ts.TsGenerator // Importer generatoren din +import no.iktdev.ts.TsGenerator import org.gradle.api.Plugin import org.gradle.api.Project +import org.gradle.api.plugins.JavaPluginExtension import org.gradle.api.provider.Property import java.io.File +import java.net.URLClassLoader -// Interface for brukerkonfigurasjon interface TsGeneratorExtension { val packageName: Property - val outputDir: Property + val outputFile: Property } class TsGeneratorPlugin : Plugin { override fun apply(project: Project) { - // Lag en extension så brukeren kan sette config val extension = project.extensions.create("tsGenerator", TsGeneratorExtension::class.java) project.tasks.register("generateTs") { - // Sett avhengighet (valgfritt: gjør at den alltid kjører før compile) + group = "typescript" dependsOn("compileKotlin") doLast { val pkg = extension.packageName.get() - val out = extension.outputDir.get() + val out = extension.outputFile.get() // Henter File direkte - // Kall din generator-logikk - TsGenerator.generate(pkg, out) + // Hent classpath for å lage ClassLoaderen + val mainSourceSet = project.extensions.getByType(JavaPluginExtension::class.java) + .sourceSets.getByName("main") + + val urls = mainSourceSet.runtimeClasspath.map { it.toURI().toURL() }.toTypedArray() + val cl = URLClassLoader(urls, TsGenerator::class.java.classLoader) + + + // Kall din signatur: generate(packageName, output, classLoader) + TsGenerator.generate(pkg, out, cl) } } } diff --git a/src/test/kotlin/no/iktdev/ts/ClassScannerTest.kt b/src/test/kotlin/no/iktdev/ts/ClassScannerTest.kt new file mode 100644 index 0000000..eb107e2 --- /dev/null +++ b/src/test/kotlin/no/iktdev/ts/ClassScannerTest.kt @@ -0,0 +1,16 @@ +package no.iktdev.ts + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class ClassScannerTest { + + @Test + fun `should scan package and find this class`() { + val scanner = ClassScanner() + val classes = scanner.scan("no.iktdev.ts", this.javaClass.classLoader) + + // Sjekk at vi fant minst oss selv + assertThat(classes).anyMatch { it.simpleName == "ClassScanner" } + } +} \ No newline at end of file diff --git a/src/test/kotlin/no/iktdev/ts/TsModelRendererTest.kt b/src/test/kotlin/no/iktdev/ts/TsModelRendererTest.kt new file mode 100644 index 0000000..7fd078c --- /dev/null +++ b/src/test/kotlin/no/iktdev/ts/TsModelRendererTest.kt @@ -0,0 +1,51 @@ +package no.iktdev.ts + +import no.iktdev.ts.models.Camera +import no.iktdev.ts.models.DeviceStatus +import no.iktdev.ts.models.Fancy +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Assertions.* +import org.junit.jupiter.api.Test + +class TsModelRendererTest { + + private val renderer = TsModelRenderer() + private val ttm = TsTypeMapper() + + @Test + fun `should maintain exact property names without renaming`() { + val result = renderer.dataClassToTs(Fancy::class, ttm) + + // Sjekk at "isFancy" ikke ble endret til "fancy" + assertThat(result).contains("isFancy: boolean;") + // Sjekk at arv er med + assertThat(result).contains("extends Parent") + // Sjekk at arvet felt (id) ikke dupliseres hvis du har filtrert det bort + assertThat(result).doesNotContain("id: string;") + } + + @Test + fun `full test - verifiser arv, typer og union`() { + // 1. Test Interface Arv + val cameraTs = renderer.dataClassToTs(Camera::class, ttm) + + assertThat(cameraTs).contains("interface Camera extends BaseDevice") + assertThat(cameraTs).contains("resolution: number;") + assertThat(cameraTs).doesNotContain("id: string;") // Skal være arvet, ikke duplisert + + // 2. Test Enum til Union Type + val enumTs = renderer.enumToTs(DeviceStatus::class) + assertThat(enumTs).isEqualTo("export type DeviceStatus = \"ONLINE\" | \"OFFLINE\"\n") + } + + @Test + fun `sealed subtype test - verifiser type discriminator`() { + // La oss si vi har en klasse som bruker sealed-logikken din + data class Sensor(val type: String = "TEMP_SENSOR", val value: Double) + + val sensorTs = renderer.sealedSubtypeToTs(Sensor::class) + + assertThat(sensorTs).contains("type: \"Sensor\";") + assertThat(sensorTs).contains("value: number;") + } +} \ No newline at end of file diff --git a/src/test/kotlin/no/iktdev/ts/TsTypeMapperTest.kt b/src/test/kotlin/no/iktdev/ts/TsTypeMapperTest.kt new file mode 100644 index 0000000..ce7c452 --- /dev/null +++ b/src/test/kotlin/no/iktdev/ts/TsTypeMapperTest.kt @@ -0,0 +1,54 @@ +package no.iktdev.ts + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test + + +class TsTypeMapperTest { + + private val mapper = TsTypeMapper() + + @Test + fun `should map primitives correctly`() { + assertEquals("string", mapper.kotlinToTsType("kotlin.String")) + assertEquals("number", mapper.kotlinToTsType("kotlin.Int")) + assertEquals("number", mapper.kotlinToTsType("kotlin.Double")) + assertEquals("boolean", mapper.kotlinToTsType("kotlin.Boolean")) + } + + @Test + fun `should map java types to string`() { + assertEquals("string", mapper.kotlinToTsType("java.util.UUID")) + assertEquals("string", mapper.kotlinToTsType("java.time.Instant")) + } + + @Test + fun `should handle nullability`() { + assertEquals("string | null", mapper.kotlinToTsType("kotlin.String?")) + assertEquals("number | null", mapper.kotlinToTsType("kotlin.Int?")) + } + + @Test + fun `should map List and Set to arrays`() { + assertEquals("string[]", mapper.kotlinToTsType("kotlin.collections.List")) + assertEquals("number[]", mapper.kotlinToTsType("kotlin.collections.MutableSet")) + } + + @Test + fun `should handle nested Map`() { + val input = "kotlin.collections.Map" + assertEquals("Record", mapper.kotlinToTsType(input)) + } + + @Test + fun `should handle generic parameters`() { + // Antar at "T" er definert i genericParams + val generics = listOf("T") + assertEquals("T[]", mapper.kotlinToTsType("kotlin.collections.List", generics)) + } + + @Test + fun `should handle unknown types by taking simple name`() { + assertEquals("MyCustomClass", mapper.kotlinToTsType("no.iktdev.models.MyCustomClass")) + } +} \ No newline at end of file diff --git a/src/test/kotlin/no/iktdev/ts/models/Parent.kt b/src/test/kotlin/no/iktdev/ts/models/Parent.kt new file mode 100644 index 0000000..ad050e6 --- /dev/null +++ b/src/test/kotlin/no/iktdev/ts/models/Parent.kt @@ -0,0 +1,20 @@ +package no.iktdev.ts.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +// Dummy-klasser for testing +interface Parent { + val id: String +} +data class Fancy(val isFancy: Boolean) : Parent { + override val id: String = "123" +} + +interface BaseDevice { + val id: String +} + +data class Camera(override val id: String, val resolution: Int) : BaseDevice + +enum class DeviceStatus { ONLINE, OFFLINE } \ No newline at end of file