Skip to content

Instantly share code, notes, and snippets.

@dellisd
Last active December 28, 2023 11:33
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dellisd/a1df42787d42b41cd3ce16f573984674 to your computer and use it in GitHub Desktop.
Save dellisd/a1df42787d42b41cd3ce16f573984674 to your computer and use it in GitHub Desktop.
Kotlin Multiplatform test resources
// Part of a multi-module project, hence the rootProject everywhere
task copyTestResourcesForJs(type: Copy) {
from "$projectDir/src/commonTest/resources"
into "${rootProject.buildDir}/js/packages/${rootProject.name}-${project.name}-test/src/commonTest/resources"
}
jsNodeTest.dependsOn copyTestResourcesForJs
// Common
const val RESOURCE_PATH = "./src/commonTest/resources"
expect class Resource(name: String) {
val name: String
fun exists(): Boolean
fun readText(): String
}
// JVM
import java.io.File
actual class Resource actual constructor(actual val name: String) {
private val file = File("$RESOURCE_PATH/$name")
actual fun exists(): Boolean = file.exists()
actual fun readText(): String = file.readText()
}
// Native
import kotlinx.cinterop.*
import platform.posix.*
actual class Resource actual constructor(actual val name: String) {
private val file: CPointer<FILE>? = fopen("$RESOURCE_PATH/$name", "r")
actual fun exists(): Boolean = file != null
actual fun readText(): String {
fseek(file, 0, SEEK_END)
val size = ftell(file)
rewind(file)
return memScoped {
val tmp = allocArray<ByteVar>(size)
fread(tmp, sizeOf<ByteVar>().convert(), size.convert(), file)
tmp.toKString()
}
}
}
// JS (Node)
private external fun require(module: String): dynamic
private val fs = require("fs")
actual class Resource actual constructor(actual val name: String) {
private val path = "$RESOURCE_PATH/$name"
actual fun exists(): Boolean = fs.existsSync(path) as Boolean
actual fun readText(): String = fs.readFileSync(path, "utf8") as String
}
@Test
fun testLength2() {
// Located at /src/commonTest/resources/test.json
val resource = Resource("test.json")
val geometry = resource.readText().toGeometry<LineString>()
assertEquals(42.560767589197006, length(geometry, Units.Kilometers))
}
@YSakhno
Copy link

YSakhno commented Oct 9, 2023

Cannot you simply specify

private val path = "kotlin/$name"

in the JS implementation of the Resource class's constructor (i.e. without the need for the copyTestResourcesForJs Gradle task)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment