Best Kotest code snippet using io.kotest.framework.concurrency.EventuallySpec.Int.seconds
EventuallySpec.kt
Source:EventuallySpec.kt  
1@file:Suppress("BlockingMethodInNonBlockingContext")2package io.kotest.framework.concurrency3import io.kotest.assertions.all4import io.kotest.assertions.fail5import io.kotest.assertions.throwables.shouldThrow6import io.kotest.assertions.withClue7import io.kotest.common.ExperimentalKotest8import io.kotest.core.spec.style.FunSpec9import io.kotest.matchers.ints.shouldBeLessThan10import io.kotest.matchers.longs.shouldBeGreaterThan11import io.kotest.matchers.longs.shouldBeGreaterThanOrEqual12import io.kotest.matchers.nulls.shouldNotBeNull13import io.kotest.matchers.shouldBe14import io.kotest.matchers.string.shouldContain15import kotlinx.coroutines.asCoroutineDispatcher16import kotlinx.coroutines.delay17import kotlinx.coroutines.launch18import kotlinx.coroutines.withContext19import java.io.FileNotFoundException20import java.io.IOException21import java.time.Duration22import java.util.concurrent.CountDownLatch23import java.util.concurrent.Executors24import java.util.concurrent.TimeUnit25import java.util.concurrent.atomic.AtomicInteger26import kotlin.system.measureTimeMillis27private fun Int.seconds(): Long = Duration.ofSeconds(this.toLong()).toMillis()28private fun Int.milliseconds(): Long = this.toLong()29@ExperimentalKotest30class EventuallySpec : FunSpec({31   test("eventually should immediately pass working tests") {32      eventually(5.seconds()) {33         System.currentTimeMillis()34      }35   }36   test("eventually passes tests that complete within the time allowed") {37      val end = System.currentTimeMillis() + 250L38      eventually(5.seconds()) {39         if (System.currentTimeMillis() < end)40            1 shouldBe 241      }42   }43   test("eventually fails tests that do not complete within the time allowed") {44      shouldThrow<RuntimeException> {45         eventually(150L) {46            throw RuntimeException("foo")47         }48      }49   }50   test("eventually returns the result computed inside") {51      val result = eventually(2.seconds()) {52         153      }54      result shouldBe 155   }56   test("eventually passes tests that completed within the time allowed, AssertionError") {57      val end = System.currentTimeMillis() + 25058      eventually(5.seconds()) {59         if (System.currentTimeMillis() < end)60            assert(false)61      }62   }63   test("eventually fails tests that throw unexpected exception type") {64      shouldThrow<NullPointerException> {65         eventually({66            duration = 2.seconds()67            suppressExceptions = setOf(IOException::class)68         }) {69            (null as String?)!!.length70         }71      }72   }73   test("eventually passes tests that throws FileNotFoundException for some time") {74      val end = System.currentTimeMillis() + 25075      eventually({76         duration = 5.seconds()77         suppressExceptions = setOf(FileNotFoundException::class)78      }) {79         if (System.currentTimeMillis() < end)80            throw FileNotFoundException("foo")81      }82   }83   test("eventually handles kotlin assertion errors") {84      var thrown = false85      eventually(100.milliseconds()) {86         if (!thrown) {87            thrown = true88            throw AssertionError("boom")89         }90      }91   }92   test("eventually handles java assertion errors") {93      var thrown = false94      eventually(100.milliseconds()) {95         if (!thrown) {96            thrown = true97            throw java.lang.AssertionError("boom")98         }99      }100   }101   test("eventually displays the first and last underlying failures") {102      var count = 0103      val message = shouldThrow<AssertionError> {104         eventually(100.milliseconds()) {105            if (count == 0) {106               count = 1107               fail("first")108            } else {109               fail("last")110            }111         }112      }.message113      // TODO: add this assertion when we can use kotlin.time again114//         message.shouldContain("Eventually block failed after 100ms; attempted \\d+ time\\(s\\); FixedInterval\\(duration=25.0ms\\) delay between attempts".toRegex())115      message.shouldContain("The first error was caused by: first")116      message.shouldContain("The last error was caused by: last")117   }118   test("eventually allows suspendable functions") {119      eventually(100.milliseconds()) {120         delay(25)121         System.currentTimeMillis()122      }123   }124   test("eventually allows configuring interval delay") {125      var count = 0126      eventually({127         duration = 200.milliseconds()128         interval = 40.milliseconds().fixed()129      }) {130         count += 1131      }132      count.shouldBeLessThan(6)133   }134   test("eventually does one final iteration if we never executed before interval expired") {135      val dispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher()136      launch(dispatcher) {137         Thread.sleep(2000)138      }139      val counter = AtomicInteger(0)140      withContext(dispatcher) {141         // we won't be able to run in here142         eventually({143            duration = 1.seconds()144            interval = 100.milliseconds().fixed()145         }) {146            counter.incrementAndGet()147         }148      }149      counter.get().shouldBe(1)150   }151   test("eventually does one final iteration if we only executed once and the last delay > interval") {152      val dispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher()153      // this will start immediately, free the dispatcher to allow eventually to run once, then block the thread154      launch(dispatcher) {155         delay(100.milliseconds())156         Thread.sleep(500)157      }158      val counter = AtomicInteger(0)159      withContext(dispatcher) {160         // this will execute once immediately, then the earlier async will steal the thread161         // and then since the delay has been > interval and times == 1, we will execute once more162         eventually({163            duration = 250.milliseconds()164            interval = 25.milliseconds().fixed()165         }) {166            counter.incrementAndGet() shouldBe 2167         }168      }169      counter.get().shouldBe(2)170   }171   test("eventually handles shouldNotBeNull") {172      measureTimeMillis {173         shouldThrow<java.lang.AssertionError> {174            eventually(50.milliseconds()) {175               val str: String? = null176               str.shouldNotBeNull()177            }178         }179      }.shouldBeGreaterThanOrEqual(50)180   }181   test("eventually with boolean predicate") {182      eventually(5.seconds()) {183         System.currentTimeMillis() > 0184      }185   }186   test("eventually with boolean predicate and interval") {187      eventually({188         duration = 5.seconds()189         interval = 1.seconds().fixed()190         predicate = { System.currentTimeMillis() > 0 }191      }) {}192   }193   test("eventually with T predicate") {194      var t = ""195      eventually<String>({196         duration = 5.seconds()197         predicate = { it.result == "xxxxxxxxxxx" }198      }) {199         t += "x"200         t201      }202   }203   test("eventually with T predicate and interval") {204      var t = ""205      val result = eventually({206         duration = 5.seconds()207         interval = 250.milliseconds().fixed()208         predicate = { it.result == "xxxxxxxxxxx" }209      }) {210         t += "x"211         t212      }213      result shouldBe "xxxxxxxxxxx"214   }215   test("eventually with T predicate, interval, and listener") {216      var t = ""217      val latch = CountDownLatch(5)218      val result = eventually({219         duration = 5.seconds()220         interval = 250.milliseconds().fixed()221         listener = { latch.countDown() }222         predicate = { it.result == "xxxxxxxxxxx" }223      }) {224         t += "x"225         t226      }227      latch.await(15, TimeUnit.SECONDS) shouldBe true228      result shouldBe "xxxxxxxxxxx"229   }230   test("eventually with T predicate, listener, and shortCircuit") {231      var t = ""232      val message = shouldThrow<EventuallyShortCircuitException> {233         eventually({234            duration = 5.seconds()235            interval = 250.milliseconds().fixed()236            shortCircuit = { it.result == "xx" }237            predicate = { it.result == "xxxxxxxxxxx" }238         }) {239            t += "x"240            t241         }242      }.message243      all(message) {244         this.shouldContain("The provided shortCircuit function caused eventually to exit early")245         this.shouldContain("EventuallyState(result=xx")246      }247   }248   test("eventually fails tests that fail a predicate") {249      shouldThrow<AssertionError> {250         eventually({251            duration = 1.seconds()252            predicate = { it.result == 2 }253         }) {254            1255         }256      }257   }258   test("eventually supports fibonacci intervals") {259      var t = ""260      val latch = CountDownLatch(5)261      val result = eventually({262         duration = 10.seconds()263         interval = 200.milliseconds().fibonacci()264         predicate = { it.result == "xxxxxx" }265         listener = { latch.countDown() }266      }) {267         t += "x"268         t269      }270      latch.await(10, TimeUnit.SECONDS) shouldBe true271      result shouldBe "xxxxxx"272   }273   fun <T> slow() = EventuallyConfig<T>(interval = 250.seconds().fixed())274   test("eventually can accept shareable configuration with Unit as the type and overrides") {275      val a = eventually(slow()) {276         5277      }278      a shouldBe 5279      val b = eventually(slow(), {280         predicate = { it.result == "hi" }281      }) {282         "hi"283      }284      b shouldBe "hi"285   }286   test("eventually throws if retry limit is exceeded") {287      val message = shouldThrow<AssertionError> {288         eventually({289            duration = 100000290            retries = 2291         }) {292            1 shouldBe 2293         }294      }.message295      // TODO: re-enable this when we have kotlin.time again296//         message.shouldContain("Eventually block failed after Infinity")297      message.shouldContain("attempted 2 time(s)")298   }299   test("eventually overrides assertion to hard assertion before executing assertion and reset it after executing") {300      val target = System.currentTimeMillis() + 1000301      val message = shouldThrow<AssertionError> {302         all {303            withClue("Eventually that should pass") {304               eventually(2.seconds()) {305                  System.currentTimeMillis() shouldBeGreaterThan target306               }307            }308            withClue("1 should never be 2") {309               1 shouldBe 2310            }311            withClue("2 should never be 3") {312               2 shouldBe 3313            }314         }315      }.message316      message shouldContain "1) 1 should never be 2"317      message shouldContain "2) 2 should never be 3"318   }319   test("eventually calls the listener when an exception is thrown in the producer function") {320      var state: EventuallyState<Unit>? = null321      shouldThrow<Throwable> {322         eventually({323            duration = 250.milliseconds()324            retries = 1325            listener = { if (state == null) { state = it } }326         }) {327            withClue("1 should never be 2") {328               1 shouldBe 2329            }330         }331      }332      state.shouldNotBeNull()333      state?.firstError?.message shouldContain "1 should never be 2"334   }335   test("allows exception if predicate is satisfied") {336      var i = 0337      eventually({338         duration = 2.seconds()339         suppressExceptionIf = { it.message == "foo" }340      }) {341         if (i++ < 3) {342            throw AssertionError("foo")343         }344      }345   }346   test("does not allow an exception if predicate is not satisfied") {347      shouldThrow<AssertionError> {348         var i = 0349         eventually({350            duration = 2.seconds()351            suppressExceptionIf = { it.message == "bar" }352         }) {353            if (i++ < 3) {354               throw AssertionError("foo")355            }356         }357      }.message shouldBe "foo"358   }359   test("allows a set of exceptions") {360      val exceptions = setOf(361         Pair(FileNotFoundException::class, FileNotFoundException()),362         Pair(AssertionError::class, AssertionError()),363         Pair(java.lang.RuntimeException::class, java.lang.RuntimeException())364      )365      var i = 0366      eventually({367         duration = 5.seconds()368         suppressExceptions = exceptions.map { it.first }.toSet()369      }) {370         exceptions.elementAtOrNull(i++)?.run {371            throw this.second372         }373      }374      i shouldBe exceptions.size + 1375   }376   test("short circuit exception cannot be suppressed") {377      shouldThrow<EventuallyShortCircuitException> {378         eventually({379            duration = 5.seconds()380            suppressExceptions = setOf(EventuallyShortCircuitException::class)381            shortCircuit = { true }382         }) {383            1 shouldBe 1384         }385      }386   }387})...Int.seconds
Using AI Code Generation
1val value = eventually(interval, timeout) {2}3val value = eventually(interval, timeout) {4}5val value = eventually(interval, timeout) {6}7val value = eventually(interval, timeout) {8}9val value = eventually(interval, timeout) {10}11val value = eventually(interval, timeout) {12}13val value = eventually(interval, timeout) {14}15val value = eventually(interval, timeout) {16}17val value = eventually(interval, timeout) {18}19val value = eventually(interval, timeout) {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!!
