Skip to content

Commit

Permalink
Fix bug where autoClose initialises itself when closing (#2691)
Browse files Browse the repository at this point in the history
* AutoClose should be fully lazy

* Don't close uninitialised lazy autoClose

* Fix eager autoClose, needs an eager lazy instance
  • Loading branch information
nomisRev committed Nov 29, 2021
1 parent f8c4a3a commit 3fd716b
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 5 deletions.
Expand Up @@ -133,10 +133,8 @@ abstract class TestConfiguration {
* Registers an [AutoCloseable] to be closed when the spec is completed.
*/
@Suppress("PropertyName")
fun <T : AutoCloseable> autoClose(closeable: T): T {
autoClose(lazy { closeable })
return closeable
}
fun <T : AutoCloseable> autoClose(closeable: T): T =
autoClose(lazy(LazyThreadSafetyMode.NONE) { closeable }).value

/**
* Registers a lazy [AutoCloseable] to be closed when the spec is completed.
Expand Down
Expand Up @@ -66,7 +66,9 @@ internal class SpecExtensions(private val registry: ExtensionRegistry) {

spec.registeredAutoCloseables().let { closeables ->
logger.log { Pair(spec::class.bestName(), "Closing ${closeables.size} autocloseables [$closeables]") }
closeables.forEach { it.value.close() }
closeables.forEach {
if(it.isInitialized()) it.value.close() else Unit
}
}

val errors = extensions(spec).filterIsInstance<AfterSpecListener>().mapNotNull { ext ->
Expand Down
@@ -0,0 +1,28 @@
package com.sksamuel.kotest.engine.autoclose

import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.booleans.shouldBeFalse
import io.kotest.matchers.booleans.shouldBeTrue

class LazyAutoCloseTest : StringSpec({

var fullLazy = true
var closed = false
val closeme = AutoCloseable { closed = true }

autoClose(lazy {
fullLazy = false
closeme
})

"autoClose lazy should be lazy" {
fullLazy.shouldBeTrue()
closed.shouldBeFalse()
}

afterProject {
// If never used in the Spec it should never get initialised, or closed
fullLazy.shouldBeTrue()
closed.shouldBeFalse()
}
})

0 comments on commit 3fd716b

Please sign in to comment.