Best Kotest code snippet using io.kotest.core.spec.AutoCloseable
TestConfiguration.kt
Source:TestConfiguration.kt
...12import io.kotest.core.spec.AfterEach13import io.kotest.core.spec.AfterSpec14import io.kotest.core.spec.AfterTest15import io.kotest.core.spec.AroundTestFn16import io.kotest.core.spec.AutoCloseable17import io.kotest.core.spec.BeforeAny18import io.kotest.core.spec.BeforeContainer19import io.kotest.core.spec.BeforeEach20import io.kotest.core.spec.BeforeSpec21import io.kotest.core.spec.BeforeTest22import io.kotest.core.spec.Spec23import io.kotest.core.spec.TestCaseExtensionFn24import io.kotest.core.test.AssertionMode25import io.kotest.core.test.TestCase26import io.kotest.core.test.TestResult27import io.kotest.core.test.TestType28import io.kotest.core.test.config.TestCaseConfig29import kotlin.js.JsName30/**31 * An abstract base implementation for shared configuration between [Spec] and [TestFactoryConfiguration].32 */33abstract class TestConfiguration {34 @JsName("_tags")35 internal var _tags: Set<Tag> = emptySet()36 @JsName("_extensions")37 internal var _extensions = emptyList<Extension>()38 private var _autoCloseables = emptyList<Lazy<AutoCloseable>>()39 /**40 * Config applied to each test case if not overridden per test case.41 * If null, then defaults to the project level default.42 *43 * Any test case config set a test itself will override any value here.44 */45 @Deprecated("These settings should be specified individually to provide finer grain control. Deprecated since 5.0")46 var defaultTestConfig: TestCaseConfig? = null47 /**48 * Sets an assertion mode which is applied to every test.49 * If null, then the project default is used.50 */51 var assertions: AssertionMode? = null52 var assertSoftly: Boolean? = null53 /**54 * Register a single [TestListener] of type T return that listener.55 */56 @SoftDeprecated("Use register")57 fun <T : TestListener> listener(listener: T): T {58 return register(listener)59 }60 /**61 * Register multiple [TestListener]s.62 */63 @SoftDeprecated("Use register")64 fun listeners(listeners: List<TestListener>) {65 register(listeners)66 }67 /**68 * Register multiple [TestListener]s.69 */70 @SoftDeprecated("Use register")71 fun listeners(vararg listeners: TestListener) = register(listeners.toList())72 /**73 * Register a single [TestListener] of type T return that listener.74 */75 fun <T : TestListener> register(extension: T): T {76 register(listOf(extension))77 return extension78 }79 /**80 * Register a single [TestCaseExtension] of type T return that extension.81 */82 fun <T : Extension> extension(extension: T): T {83 extensions(extension)84 return extension85 }86 fun register(vararg extensions: Extension) {87 register(extensions.toList())88 }89 fun register(extensions: List<Extension>) {90 _extensions = _extensions + extensions91 }92 /**93 * Register multiple [Extension]s.94 */95 fun extensions(vararg extensions: Extension) {96 register(extensions.toList())97 }98 /**99 * Register multiple [Extension]s.100 */101 fun extensions(extensions: List<Extension>) {102 register(extensions)103 }104 /**105 * Adds [Tag]s to this spec or factory, which will be applied to each test case.106 *107 * When applied in a factory, only tests generated from that factory will have the tags applied.108 * When applied to a spec, all tests will have the tags applied.109 */110 fun tags(vararg tags: Tag) {111 _tags = _tags + tags.toSet()112 }113 fun appliedTags() = _tags114 /**115 * Registers an [AutoCloseable] to be closed when the spec is completed.116 */117 @Suppress("PropertyName")118 fun <T : AutoCloseable> autoClose(closeable: T): T =119 autoClose(lazy(LazyThreadSafetyMode.NONE) { closeable }).value120 /**121 * Registers a lazy [AutoCloseable] to be closed when the spec is completed.122 */123 fun <T : AutoCloseable> autoClose(closeable: Lazy<T>): Lazy<T> {124 _autoCloseables = listOf(closeable) + _autoCloseables125 return closeable126 }127 /**128 * Registers a callback to be executed before every [TestCase].129 *130 * The [TestCase] about to be executed is provided as the parameter.131 */132 open fun beforeTest(f: BeforeTest) {133 register(object : TestListener {134 override suspend fun beforeAny(testCase: TestCase) {135 f(testCase)136 }137 })138 }139 /**140 * Registers a callback to be executed after every [TestCase].141 *142 * The callback provides two parameters - the test case that has just completed,143 * and the [TestResult] outcome of that test.144 */145 open fun afterTest(f: AfterTest) {146 register(object : AfterTestListener {147 override suspend fun afterAny(testCase: TestCase, result: TestResult) {148 f(Tuple2(testCase, result))149 }150 })151 }152 /**153 * Registers a callback to be executed before every [TestCase]154 * with type [TestType.Container].155 *156 * The [TestCase] about to be executed is provided as the parameter.157 */158 fun beforeContainer(f: BeforeContainer) {159 register(object : BeforeContainerListener {160 override suspend fun beforeContainer(testCase: TestCase) {161 f(testCase)162 }163 })164 }165 /**166 * Registers a callback to be executed after every [TestCase]167 * with type [TestType.Container].168 *169 * The callback provides two parameters - the test case that has just completed,170 * and the [TestResult] outcome of that test.171 */172 fun afterContainer(f: AfterContainer) {173 register(object : AfterContainerListener {174 override suspend fun afterContainer(testCase: TestCase, result: TestResult) {175 f(Tuple2(testCase, result))176 }177 })178 }179 /**180 * Registers a callback to be executed before every [TestCase]181 * with type [TestType.Test].182 *183 * The [TestCase] about to be executed is provided as the parameter.184 */185 fun beforeEach(f: BeforeEach) {186 register(object : TestListener {187 override suspend fun beforeEach(testCase: TestCase) {188 f(testCase)189 }190 })191 }192 /**193 * Registers a callback to be executed after every [TestCase]194 * with type [TestType.Test].195 *196 * The callback provides two parameters - the test case that has just completed,197 * and the [TestResult] outcome of that test.198 */199 fun afterEach(f: AfterEach) {200 register(object : TestListener {201 override suspend fun afterEach(testCase: TestCase, result: TestResult) {202 f(Tuple2(testCase, result))203 }204 })205 }206 /**207 * Registers a callback to be executed before every [TestCase]208 * with type [TestType.Test] or [TestType.Container].209 *210 * The [TestCase] about to be executed is provided as the parameter.211 */212 fun beforeAny(f: BeforeAny) {213 register(object : TestListener {214 override suspend fun beforeAny(testCase: TestCase) {215 f(testCase)216 }217 })218 }219 /**220 * Registers a callback to be executed after every [TestCase]221 * with type [TestType.Container] or [TestType.Test].222 *223 * The callback provides two parameters - the test case that has just completed,224 * and the [TestResult] outcome of that test.225 */226 fun afterAny(f: AfterAny) {227 register(object : TestListener {228 override suspend fun afterAny(testCase: TestCase, result: TestResult) {229 f(Tuple2(testCase, result))230 }231 })232 }233 /**234 * Registers a callback to be executed before any tests in this spec.235 * The spec instance is provided as a parameter.236 */237 fun beforeSpec(f: BeforeSpec) {238 register(object : TestListener {239 override suspend fun beforeSpec(spec: Spec) {240 f(spec)241 }242 })243 }244 /**245 * Register an extension callback246 */247 fun extension(f: TestCaseExtensionFn) {248 extension(object : TestCaseExtension {249 override suspend fun intercept(testCase: TestCase, execute: suspend (TestCase) -> TestResult): TestResult =250 f(Tuple2(testCase, execute))251 })252 }253 /**254 * Registers a callback to be executed after all tests in this spec.255 * The spec instance is provided as a parameter.256 */257 open fun afterSpec(f: AfterSpec) {258 register(object : TestListener {259 override suspend fun afterSpec(spec: Spec) {260 f(spec)261 }262 })263 }264 fun aroundTest(aroundTestFn: AroundTestFn) {265 extension(object : TestCaseExtension {266 override suspend fun intercept(testCase: TestCase, execute: suspend (TestCase) -> TestResult): TestResult {267 val f: suspend (TestCase) -> TestResult = { execute(it) }268 return aroundTestFn(Tuple2(testCase, f))269 }270 })271 }272 fun registeredAutoCloseables(): List<Lazy<AutoCloseable>> = _autoCloseables.toList()273 /**274 * Returns any [Extension] instances registered directly on this class.275 */276 fun registeredExtensions(): List<Extension> {277 return _extensions.toList()278 }279}...
LoungeControllerTest.kt
Source:LoungeControllerTest.kt
...134 controller.adapter.get(0)135 notified shouldBe 0136 }137 test("Possess tag during build") {138 val tags = mutableListOf<AutoCloseable>()139 val closedKey = mutableListOf<String>()140 var key = "key1"141 val controller = object : LoungeController(owner.lifecycle, dispatcher) {142 override suspend fun buildModels() {143 val k = key144 val tag = possessTagDuringBuilding(k, AutoCloseable::class) {145 AutoCloseable { closedKey += k }146 }147 tags += tag148 }149 }150 owner.lifecycle.currentState = Lifecycle.State.STARTED151 controller.requestModelBuild()152 controller.requestModelBuild()153 tags.size shouldBe 2154 tags.distinct().size shouldBe 1155 closedKey.isEmpty() shouldBe true156 key = "key2"157 controller.requestModelBuild()158 tags.size shouldBe 3159 tags.distinct().size shouldBe 2...
DefaultJobExecutorsSpec.kt
Source:DefaultJobExecutorsSpec.kt
...12 val config = KJob.Configuration().apply {13 blockingMaxJobs = 114 nonBlockingMaxJobs = 115 }16 private fun newTestee(): JobExecutors = autoClose(object : AutoCloseable, JobExecutors by DefaultJobExecutors(config) {17 override fun close() {18 shutdown()19 }20 })21 init {22 should("execute coroutine when resources are available again") {23 forAll(*newTestee().dispatchers.map { row(it.value) }.toTypedArray()) { dispatcher ->24 dispatcher.shouldNotBeNull()25 val latch1 = CountDownLatch(1)26 val latch2 = CountDownLatch(2)27 dispatcher.canExecute() shouldBe true28 CoroutineScope(dispatcher.coroutineDispatcher).launch {29 latch1.await()30 }...
AutoCloseTest.kt
Source:AutoCloseTest.kt
...18 ThirdAutoclose.closed shouldBe 119 }20}21private val closedNumber = AtomicInteger(0)22private object FirstAutoclose : AutoCloseable {23 var closed = -124 override fun close() {25 closed = closedNumber.incrementAndGet()26 }27}28private object SecondAutoclose : AutoCloseable {29 var closed = -130 override fun close() {31 closed = closedNumber.incrementAndGet()32 }33}34private object ThirdAutoclose : AutoCloseable {35 var closed = -136 override fun close() {37 closed = closedNumber.incrementAndGet()38 }39}...
AutoCloseable.kt
Source:AutoCloseable.kt
...11 limitations under the License.12*/13package batect.dockerclient14import io.kotest.core.TestConfiguration15actual fun <T : AutoCloseable> TestConfiguration.closeAfterTest(instance: T): T {16 autoClose(object : io.kotest.core.spec.AutoCloseable {17 override fun close() {18 instance.close()19 }20 })21 return instance22}
MockServerListener.kt
Source:MockServerListener.kt
...8 * will be used (found via [mockServer])9 */10class MockServerListener(11 private vararg val port: Int = intArrayOf()12) : TestListener, AutoCloseable {13 // this has to be a var because MockServer starts the server as soon as you instantiate the instance :(14 lateinit var mockServer: ClientAndServer15 override suspend fun beforeSpec(spec: Spec) {16 super.beforeSpec(spec)17 mockServer = startClientAndServer(*port.toTypedArray())18 }19 override suspend fun afterSpec(spec: Spec) {20 mockServer.stop()21 }22 override fun close() {23 mockServer.stop()24 }25}...
AutoCloseDslTest.kt
Source:AutoCloseDslTest.kt
...4import io.kotest.matchers.booleans.shouldBeTrue5class AutoCloseDslTest : FunSpec({6 var beforeTests = true7 var closed = false8 val closeme = AutoCloseable { closed = true }9 autoClose(closeme)10 val lazyClosed by autoClose(lazy {11 beforeTests = false12 LazyCloseable()13 })14 beforeTests.shouldBeTrue()15 test("auto close with dsl method") {16 closed.shouldBeFalse()17 }18 test("lazy auto close with dsl method") {19 lazyClosed.closed.shouldBeFalse()20 }21 afterSpec {22 closed.shouldBeTrue()23 lazyClosed.closed.shouldBeTrue()24 }25}) {26 class LazyCloseable : AutoCloseable {27 var closed = false28 override fun close() {29 closed = true30 }31 }32}...
LazyAutoCloseTest.kt
Source:LazyAutoCloseTest.kt
...4import io.kotest.matchers.booleans.shouldBeTrue5class LazyAutoCloseTest : StringSpec({6 var fullLazy = true7 var closed = false8 val closeme = AutoCloseable { closed = true }9 autoClose(lazy {10 fullLazy = false11 closeme12 })13 "autoClose lazy should be lazy" {14 fullLazy.shouldBeTrue()15 closed.shouldBeFalse()16 }17 afterProject {18 // If never used in the Spec it should never get initialised, or closed19 fullLazy.shouldBeTrue()20 closed.shouldBeFalse()21 }22})...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!