Skip to content

Commit 5a0865d

Browse files
committed
cleanup test stuff
1 parent a0408f8 commit 5a0865d

File tree

9 files changed

+113
-142
lines changed

9 files changed

+113
-142
lines changed

nob.kt

Lines changed: 68 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -36,43 +36,30 @@ fun main(args: Array<String>) {
3636
mods = listOf(klib)
3737
}
3838
when {
39-
// args.getOrNull(0) == "doc" -> nob.run_doc(klib, args.drop(1).toTypedArray())
39+
args.getOrNull(0) == "doc" -> {
40+
nob.compile(klib)
41+
nob.run(klib, "doc.DocGenKt", arrayOf("src/doc/DocGen.kt", "src/doc/KotlinParser.kt"))
42+
}
4043
args.getOrNull(0) == "test" -> {
4144
nob.compile(test)
4245
nob.run(test, "test.TesterKt", arrayOf("-f", test.src_target().toAbsolutePath().normalize().toString()))
4346
}
44-
args.getOrNull(0) == "klib" -> nob.compile(klib)
47+
args.getOrNull(0) == "klib" -> nob.compile(klib)
4548
args.getOrNull(0) == "examples" -> nob.compile(examples)
46-
args.getOrNull(0) == "release" -> nob.release(klib)
49+
args.getOrNull(0) == "release" -> nob.release(klib)
4750
else -> nob.mods.filter { it.name != "nob" }.forEach { nob.compile(it) }
4851
}
4952
nob.exit()
5053
}
5154

52-
// fun Nob.run_doc(module: Module, doc_args: Array<String>) {
53-
// if (opts.verbose) info("Generating docs $doc_args")
54-
// val cmd = buildList {
55-
// add("java")
56-
// add("-Dfile.encoding=UTF-8")
57-
// add("-Dsun.stdout.encoding=UTF-8")
58-
// add("-Dsun.stderr.encoding=UTF-8")
59-
// if (opts.debug) add("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005")
60-
// add("-cp")
61-
// add(module.test_compile_cp())
62-
// add("doc.DocGenKt")
63-
// doc_args.forEach { add(it) }
64-
// }
65-
// exec(*cmd.toTypedArray())
66-
// }
67-
6855
class Nob(val opts: Opts) {
6956
private var exit_code = 0
7057
var mods = mutableListOf<Module>()
7158
var compiled = mutableSetOf<Module>()
7259

7360
fun module(block: Module.() -> Unit): Module {
7461
val module = Module().apply(block)
75-
module.libs = solve_libs(opts, module)
62+
module.libs = resolve_libs(opts, module)
7663
mods.add(module)
7764
return module
7865
}
@@ -94,14 +81,13 @@ class Nob(val opts: Opts) {
9481
}
9582
}
9683

97-
// fun exit(): Unit = kotlin.system.exitProcess(exit_code)
9884
fun exit(code: Int = exit_code): Unit = System.exit(code)
9985

10086
fun clean() {
10187
val target = path(mods.first().target)
10288
if (!Files.exists(target)) System.exit(0)
10389
Files.walk(target).forEach { f ->
104-
if (f.fileName.toString() !in listOf(".alive", "libs.cache", mods.first().target)) {
90+
if (f.fileName.toString() !in listOf(".alive", mods.first().target)) {
10591
Files.walk(f).sorted(Comparator.reverseOrder()).forEach { Files.delete(it) }
10692
}
10793
}
@@ -123,10 +109,6 @@ class Nob(val opts: Opts) {
123109

124110
val any_compiled_target_file = get_any_compiled_file(target.toFile())
125111
val has_changes = sources.any { file ->
126-
// println("src: $src")
127-
// println("target: $target")
128-
// println("file: $file")
129-
// println("any_compiled_target_file: $any_compiled_target_file")
130112
file.lastModified() > any_compiled_target_file?.lastModified() ?: 0
131113
}
132114

@@ -234,14 +216,19 @@ class Nob(val opts: Opts) {
234216

235217
fun exec(vararg cmd: String) {
236218
if (opts.verbose) info(cmd.joinToString(" "))
237-
info(cmd.joinToString(" "))
219+
// info(cmd.joinToString(" "))
238220
exit_code = java.lang.ProcessBuilder(*cmd).inheritIO().start().waitFor()
239221
}
240222

241-
private val kotlin_home = Paths.get(System.getenv("KOTLIN_HOME"), "libexec", "lib")
242-
private val kotlin_libs = listOf("kotlin-stdlib.jar", "kotlin-compiler.jar", "kotlin-daemon.jar", "kotlin-daemon-client.jar").joinToString(File.pathSeparator) { kotlin_home.resolve(it).toAbsolutePath().normalize().toString() }
243-
244223
private fun compile_with_daemon(src: File, target: Path, classpath: String, name: String, retries: Int = 3) {
224+
val kotlin_libs = listOf(
225+
"kotlin-stdlib.jar",
226+
"kotlin-compiler.jar",
227+
"kotlin-daemon.jar",
228+
"kotlin-daemon-client.jar",
229+
).joinToString(File.pathSeparator) {
230+
opts.kotlin_home.resolve(it).toAbsolutePath().normalize().toString()
231+
}
245232
val args = buildList {
246233
add("-d")
247234
add(target.toString())
@@ -265,7 +252,7 @@ class Nob(val opts: Opts) {
265252
// info("kotlinc ${args.joinToString(" ")}")
266253
val client_alive_file = target.resolve(".alive").toFile().apply { if (!exists()) createNewFile() }
267254
val daemon_reports = arrayListOf<DaemonReportMessage>()
268-
val compiler_id = Files.list(kotlin_home).filter { it.toString().endsWith(".jar") }.map { it.toFile() }.toList()
255+
val compiler_id = Files.list(opts.kotlin_home).filter { it.toString().endsWith(".jar") }.map { it.toFile() }.toList()
269256
val daemon = KotlinCompilerClient.connectToCompileService(
270257
compilerId = CompilerId.makeCompilerId(compiler_id),
271258
clientAliveFlagFile = client_alive_file,
@@ -322,6 +309,7 @@ class Nob(val opts: Opts) {
322309
data class Opts(
323310
var jvm_version: Int = 21,
324311
var kotlin_version: String = "2.2.0",
312+
var kotlin_home: Path = Paths.get(System.getenv("KOTLIN_HOME"), "libexec", "lib"),
325313
var backend_threads: Int = 0, // run codegen with N thread per processor (Default 1)
326314
var verbose: Boolean = false,
327315
var error: Boolean = true,
@@ -355,7 +343,7 @@ data class Module(
355343
return when {
356344
src_target.isFile -> path("$target/$name")
357345
src_target.isDirectory -> path("$target/$src")
358-
else -> error("file is not file or directory $src_target")
346+
else -> error("'$src_target' is not a file nor a directory. Exists: ${src_target.exists()}")
359347
}
360348
}
361349

@@ -369,9 +357,9 @@ data class Module(
369357
fun runtime_cp(): String {
370358
val libs = libs.filter { it.scope in listOf("runtime", "compile") }.map { it.jar_path }.into_cp()
371359
val mods = mods.map { it.src_target().toAbsolutePath().normalize().toString() }.joinToString(File.pathSeparator)
360+
val res = path(res).toAbsolutePath().normalize().toString()
372361
val target = path(target).toAbsolutePath().normalize().toString()
373362
val src_target = src_target().toAbsolutePath().normalize().toString()
374-
val res = path(res).toAbsolutePath().normalize().toString()
375363
return listOf(libs, mods, res, target, src_target).filter { it.isNotBlank() }.joinToString(File.pathSeparator)
376364
}
377365

@@ -397,6 +385,7 @@ data class Lib(
397385
val jar_file get() = File("${jar_cache_dir}/${group_id}/${artifact_id}-${version}.jar").also { it.parentFile.mkdirs() }
398386
val pom_file get() = File("${jar_cache_dir}/${group_id}/${artifact_id}-${version}.pom").also { it.parentFile.mkdirs() }
399387
val module_file get() = File("${jar_cache_dir}/${group_id}/${artifact_id}-${version}.module").also { it.parentFile.mkdirs() }
388+
val is_local get() = repo == "local"
400389
override fun toString() = "$group_id:$artifact_id:$version"
401390
override fun hashCode(): Int = "${toString()}:$scope".hashCode()
402391
override fun equals(other: Any?): Boolean {
@@ -406,6 +395,7 @@ data class Lib(
406395
}
407396
companion object {
408397
fun of(str: String) = str.split(':').let { Lib(it[0], it[1], it[2], it.getOrElse(3) { "compile" }) }
398+
fun local(str: String) = Lib("", str, "", repo = "local", jar_path = Paths.get(System.getProperty("user.dir"), str))
409399
}
410400
}
411401

@@ -434,7 +424,7 @@ private fun download_jar(lib: Lib) {
434424
data class ResolvedLib(val lib: Lib, val resolved_from: String)
435425
data class LibKey(val group: String, val artifact: String)
436426

437-
private fun solve_libs(opts: Opts, module: Module): List<Lib> {
427+
private fun resolve_libs(opts: Opts, module: Module): List<Lib> {
438428
val start_time = System.nanoTime()
439429
val cache_file = path(module.target).resolve("libs.cache").toFile()
440430
val resolved = mutableListOf<ResolvedLib>()
@@ -450,8 +440,10 @@ private fun solve_libs(opts: Opts, module: Module): List<Lib> {
450440
if (key !in keys) {
451441
resolved.add(ResolvedLib(lib, "local"))
452442
keys.add(key)
453-
queue.add(lib)
454-
download_jar(lib)
443+
if (lib.repo != "local") {
444+
queue.add(lib)
445+
download_jar(lib)
446+
}
455447
}
456448
}
457449
while(queue.isNotEmpty()) {
@@ -469,6 +461,7 @@ private fun solve_libs(opts: Opts, module: Module): List<Lib> {
469461
}
470462
}
471463
}
464+
info("resolve_kotlin_libs")
472465
return resolved.resolve_kotlin_libs(opts).also {
473466
save_cache(cache_file, it)
474467
info("Resolved ${resolved.size} libs ${stop(start_time)}")
@@ -478,27 +471,24 @@ private fun solve_libs(opts: Opts, module: Module): List<Lib> {
478471
}
479472

480473
private fun List<ResolvedLib>.resolve_kotlin_libs(opts: Opts): List<ResolvedLib> {
481-
val kotlin_home = Paths.get(System.getenv("KOTLIN_HOME"), "libexec", "lib")
482-
return this
483-
// .filterNot { it.group_id == "org.jetbrains.kotlin" && it.artifact_id == "kotlin-stdlib-common" }
484-
.map { resolved ->
485-
val lib = resolved.lib
486-
when (lib.group_id) {
487-
"org.jetbrains.kotlin" -> {
488-
val local = kotlin_home.resolve("${lib.artifact_id}.jar")
489-
when (local.toFile().exists()) {
490-
true -> {
491-
info("found local kotlin substitute: $local")
492-
ResolvedLib(lib.copy(version = opts.kotlin_version, jar_path = local), resolved.resolved_from)
493-
}
494-
false -> {
495-
info("found no kotlin subsistute, fallback to $resolved")
496-
resolved
497-
}
474+
return this.map { resolved ->
475+
val lib = resolved.lib
476+
when (lib.group_id) {
477+
"org.jetbrains.kotlin" -> {
478+
val local = opts.kotlin_home.resolve("${lib.artifact_id}.jar")
479+
when (local.toFile().exists()) {
480+
true -> {
481+
info("found local kotlin substitute: $local")
482+
ResolvedLib(lib.copy(version = opts.kotlin_version, jar_path = local, repo = "local"), resolved.resolved_from)
483+
}
484+
false -> {
485+
info("found no kotlin subsistute, fallback to $resolved")
486+
resolved
498487
}
499488
}
500-
else -> resolved
501489
}
490+
else -> resolved
491+
}
502492
}
503493
}
504494

@@ -507,22 +497,36 @@ private fun read_cache(file: File, resolved: MutableList<ResolvedLib>) {
507497
file.readLines()
508498
.mapNotNull { line ->
509499
val parts = line.split(":")
510-
if (parts.size != 6) null
511-
// restore jar_path for local libs
512-
when (val jar_path = parts.getOrNull(6)) {
513-
null -> ResolvedLib(resolved_from = parts[5], lib = Lib(parts[0], parts[1], parts[2], parts[3], parts[4]))
514-
else -> ResolvedLib(resolved_from = parts[5], lib = Lib(parts[0], parts[1], parts[2], parts[3], parts[4], jar_path = Paths.get(jar_path)))
500+
val repo = parts.getOrNull(6)
501+
val jar_path = parts.getOrNull(7)?.let(Paths::get)
502+
val lib = if (repo != null && jar_path != null) {
503+
Lib(
504+
group_id = parts[0],
505+
artifact_id = parts[1],
506+
version = parts[2],
507+
scope = parts[3],
508+
type = parts[4],
509+
repo = repo,
510+
jar_path = jar_path,
511+
)
512+
} else {
513+
Lib(
514+
group_id = parts[0],
515+
artifact_id = parts[1],
516+
version = parts[2],
517+
scope = parts[3],
518+
type = parts[4]
519+
)
515520
}
521+
ResolvedLib(lib = lib, resolved_from = parts[5])
516522
}.forEach(resolved::add)
517523
}
518524

519525
private fun save_cache(file: File, resolved: List<ResolvedLib>) {
520526
file.writeText(resolved.joinToString("\n") {
521-
// save jar_path for local libs
522-
if (it.lib.jar_path.parent.parent.fileName.toString() != ".nob_cache") {
523-
"${it.lib}:${it.lib.scope}:${it.lib.type}:${it.resolved_from}:${it.lib.jar_path.toAbsolutePath().normalize().toString()}"
524-
} else {
525-
"${it.lib}:${it.lib.scope}:${it.lib.type}:${it.resolved_from}"
527+
when (it.lib.is_local) {
528+
true -> "${it.lib}:${it.lib.scope}:${it.lib.type}:${it.resolved_from}:${it.lib.repo}:${it.lib.jar_path.toAbsolutePath().normalize().toString()}"
529+
false -> "${it.lib}:${it.lib.scope}:${it.lib.type}:${it.resolved_from}"
526530
}
527531
})
528532
}

src/test/Assertions.kt

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,20 @@
11
package test
22

3-
class AssertionError(message: String) : Exception(message)
3+
class AssertionError(
4+
message: String,
5+
val left: Any? = null,
6+
val right: Any? = null,
7+
) : Exception(message)
48

5-
fun eq(left: Any, right: Any) = assertEq(left, right)
6-
7-
fun assertEq(left: Any, right: Any) {
9+
fun eq(left: Any?, right: Any?) {
810
if (left != right) {
9-
throw AssertionError("$left != $right")
11+
throw AssertionError("should be equal", left, right)
12+
}
13+
}
14+
15+
fun neq(left: Any?, right: Any?) {
16+
if (left == right) {
17+
throw AssertionError("should not be equal", left, right)
1018
}
1119
}
1220

@@ -20,7 +28,6 @@ fun fail(msg: String = "Assertion failed") {
2028
throw AssertionError(msg)
2129
}
2230

23-
// todo: this only fails with "assertion failed". Make it fail with a message that includes the expected and actual values
2431
inline fun <reified T: Any> assert(it: Any, predicate: (T) -> Boolean) {
2532
assert(predicate(it as T))
2633
}

src/test/Tester.kt

Lines changed: 15 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -35,14 +35,6 @@ fun main(args: Array<String>) {
3535
System.exit(1)
3636
}
3737
ClassLoader.runAllTests(test_dir)
38-
// val className = path.split("/")
39-
// .dropWhile { it != "test" }.drop(1)
40-
// .joinToString(".")
41-
// .removeSuffix(".kt")
42-
//
43-
// if(!ClassLoader.runTests(className)) {
44-
// System.exit(1)
45-
// }
4638
}
4739

4840
cmds.getFlagValue("-p")?.let { path ->
@@ -76,21 +68,32 @@ data class TestResult(
7668
private val time: Long,
7769
private val msg: String? = null,
7870
private val loc: String? = null,
71+
private val err: AssertionError? = null,
7972
) {
8073
private fun status(): String = when (success) {
8174
true -> "".text(Color.GREEN) + "PASS".bg(Color.GREEN).text(Color.GRAY) + "".text(Color.GREEN)
8275
false -> "".text(Color.RED) + "FAIL".bg(Color.RED).text(Color.GRAY) + "".text(Color.RED)
8376
}
8477

85-
private fun time(): String = "${time/1_000_000} ms".padEnd(9, ' ').text(Color.DARK_YELLOW)
8678
private fun name(): String = "$name ".text(Color.YELLOW)
79+
private fun time(): String {
80+
return when(time) {
81+
in 0 .. 999 -> "$time ns".padEnd(9, ' ').text(Color.DARK_YELLOW)
82+
in 1000 .. 999_999 -> "${time/1_000} µs".padEnd(9, ' ').text(Color.DARK_YELLOW)
83+
else -> "${time/1_000_000} ms".padEnd(9, ' ').text(Color.DARK_YELLOW)
84+
}
85+
}
8786

8887
override fun toString(): String {
8988
return buildString {
9089
append(" ${time()} ${status()} ${name()}")
9190
if (!success) {
92-
if (msg != null) append("\n".padEnd(12, ' ') + msg.text(Color.LIGHT_GRAY))
9391
if (loc != null) append("\n".padEnd(12, ' ') + loc.text(Color.LIGHT_GRAY))
92+
if (msg != null && err?.left == null && err?.right == null) append("\n".padEnd(12, ' ') + msg.text(Color.LIGHT_GRAY))
93+
if (err?.left != null || err?.right != null) {
94+
append("\n".padEnd(12, ' ') + "left: " + err.left.toString().text(Color.LIGHT_GRAY))
95+
append("\n".padEnd(12, ' ') + "right: " + err.right.toString().text(Color.LIGHT_GRAY))
96+
}
9497
}
9598
}
9699
}
@@ -142,16 +145,8 @@ object ClassLoader {
142145
.mapNotNull { file ->
143146
val relative_path = file.toRelativeString(root_dir)
144147
val class_name = relative_path
145-
// .removePrefix("test" + File.separator)
146148
.replace(File.separator, ".")
147149
.removeSuffix(".class")
148-
// val class_name = file.canonicalPath
149-
// .removePrefix(root_dir.canonicalPath)
150-
// .removePrefix(File.separator)
151-
// .removePrefix(root_dir.canonicalPath)
152-
// .removePrefix(File.separator)
153-
// .replace(File.separator, ".")
154-
// .removeSuffix(".class")
155150
try {
156151
when (class_name.isBlank()) {
157152
true -> null
@@ -182,9 +177,9 @@ object ClassLoader {
182177
if (cause is AssertionError) {
183178
val trace = cause.stackTrace.firstOrNull { !it.className.startsWith("test.AssertionsKt") && !it.className.startsWith("test.ClassLoader") }
184179
val loc = trace?.let { "${it.fileName}:${it.lineNumber}" }
185-
Result.Ok(TestResult(method.name, false, start.stop(), cause.message, loc))
180+
Result.Ok(TestResult(method.name, false, start.stop(), cause.message, loc, cause))
186181
} else {
187-
Result.Err(e)
182+
Result.Err(cause ?: e)
188183
}
189184
}
190185
}

test/NoPkgTest.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ class NoPkgTest {
66

77
@Test
88
fun `can test classes without package`() {
9-
assertEq(left, right)
9+
eq(left, right)
1010
}
1111

1212
@Before

0 commit comments

Comments
 (0)