Skip to content

Commit

Permalink
test: properly close directory handle
Browse files Browse the repository at this point in the history
  • Loading branch information
Vampire committed Feb 2, 2025
1 parent 7084de0 commit af15bc1
Showing 1 changed file with 24 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import io.kotest.matchers.should
import io.kotest.matchers.shouldNot
import io.kotest.mpp.env
import node.buffer.BufferEncoding.Companion.utf8
import node.fs.Dir
import node.fs.exists
import node.fs.existsSync
import node.fs.opendir
Expand All @@ -38,7 +39,7 @@ class AjvSchemaValidationTest : FunSpec({
withClue("catalogDir should be a non-empty directory") {
exists(catalogDir).shouldBeTrue()
stat(catalogDir).isDirectory().shouldBeTrue()
opendir(catalogDir).read().await().shouldNotBeNull()
opendir(catalogDir).use { it.read().await().shouldNotBeNull() }
}

validate = Ajv(AjvOptions(strict = true)).compile(
Expand Down Expand Up @@ -98,3 +99,25 @@ private suspend fun String.shouldNotBeValid(): String {
readFile(path.join(badDir, this), utf8) shouldNot beValid()
return this
}

private inline fun <R> Dir.use(block: (Dir) -> R): R {
var exception: Throwable? = null
try {
return block(this)
} catch (e: Throwable) {
exception = e
throw e
} finally {
this.closeFinally(exception)
}
}

private fun Dir.closeFinally(cause: Throwable?): Unit = when {
cause == null -> closeSync()
else ->
try {
closeSync()
} catch (closeException: Throwable) {
cause.addSuppressed(closeException)
}
}

0 comments on commit af15bc1

Please sign in to comment.