How to use Interval class of io.kotest.assertions.until package

Best Kotest code snippet using io.kotest.assertions.until.Interval

InventoryConsumerTest.kt

Source:InventoryConsumerTest.kt Github

copy

Full Screen

1package org.learning.demo.app.consumer2import io.kotest.assertions.timing.EventuallyConfig3import io.kotest.assertions.timing.continually4import io.kotest.assertions.timing.eventually5import io.kotest.assertions.until.FixedInterval6import io.kotest.assertions.until.fixed7import io.kotest.matchers.shouldBe8import kotlinx.coroutines.runBlocking9import org.junit.jupiter.api.BeforeEach10import org.junit.jupiter.api.Test11import org.learning.demo.IntegrationTest12import org.learning.demo.app.repository.InventoryProduct13import org.learning.demo.app.repository.ProductRepository14import org.learning.demo.lib.kafka.KafkaMessage15import org.learning.demo.lib.kafka.producer.KafkaProducer16import org.learning.demo.lib.kafka.repository.ProcessedMessageAudit17import org.learning.demo.lib.kafka.repository.ProcessedMessageAuditRepository18import org.learning.demo.util.assertNextWith19import org.springframework.beans.factory.annotation.Autowired20import java.time.LocalDateTime21import kotlin.time.Duration.Companion.seconds22import kotlin.time.DurationUnit23import kotlin.time.toDuration24@IntegrationTest25class InventoryConsumerTest(26    @Autowired private val kafkaProducer: KafkaProducer,27    @Autowired private val productRepository: ProductRepository,28    @Autowired private val processedMessageAuditRepository: ProcessedMessageAuditRepository,29) {30    @BeforeEach31    fun setUp() {32        processedMessageAuditRepository.deleteAll().block()33    }34    @Test35    fun `should update count of remain products on consuming order created event`() {36        productRepository.saveAll(37            listOf(38                InventoryProduct("P-001", 20),39                InventoryProduct("P-002", 12),40                InventoryProduct("P-003", 12),41            )42        ).blockLast()43        kafkaProducer.produce(44            "order",45            KafkaMessage(46                eventId = "ev-00-11",47                eventName = "order-created",48                createdTime = "2020-01-01",49                partitionKey = "123",50                identifiers = mapOf(),51                payload = mapOf(52                    "orderId" to "001",53                    "totalPrice" to 234.56,54                    "products" to setOf(55                        mapOf(56                            "productCode" to "P-001",57                            "quantity" to 12,58                            "price" to 345.3259                        ),60                        mapOf(61                            "productCode" to "P-002",62                            "quantity" to 12,63                            "price" to 345.3264                        ),65                    )66                )67            )68        ).block()69        runBlocking {70            eventually(71                EventuallyConfig(72                    duration = 5.toDuration(DurationUnit.SECONDS),73                    interval = FixedInterval(100.toDuration(DurationUnit.MILLISECONDS))74                )75            ) {76                assertNextWith(productRepository.findByProductCode("P-001")) {77                    it.remainingQuantity shouldBe 878                }79                assertNextWith(productRepository.findByProductCode("P-002")) {80                    it.remainingQuantity shouldBe 081                }82                assertNextWith(productRepository.findByProductCode("P-003")) {83                    it.remainingQuantity shouldBe 1284                }85            }86        }87    }...

Full Screen

Full Screen

KafkaConsumerTest.kt

Source:KafkaConsumerTest.kt Github

copy

Full Screen

1package org.learning.demo.lib.kafka.consumer2import io.kotest.assertions.timing.EventuallyConfig3import io.kotest.assertions.timing.eventually4import io.kotest.assertions.until.FixedInterval5import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder6import io.kotest.matchers.collections.shouldHaveSize7import kotlinx.coroutines.runBlocking8import org.junit.jupiter.api.BeforeEach9import org.junit.jupiter.api.Test10import org.learning.demo.IntegrationTest11import org.learning.demo.lib.kafka.KafkaMessage12import org.learning.demo.lib.kafka.producer.KafkaProducer13import org.learning.demo.lib.kafka.repository.ProcessedMessageAudit14import org.learning.demo.lib.kafka.repository.ProcessedMessageAuditRepository15import org.learning.demo.util.assertNextWith16import org.springframework.beans.factory.annotation.Autowired17import java.time.LocalDateTime18import kotlin.time.DurationUnit19import kotlin.time.toDuration20@IntegrationTest21class KafkaConsumerTest(22    @Autowired private val kafkaProducer: KafkaProducer,23    @Autowired private val dummyKafkaConsumer: DummyKafkaConsumer,24    @Autowired private val processedMessageAuditRepository: ProcessedMessageAuditRepository,25) {26    @BeforeEach27    fun setUp() {28        processedMessageAuditRepository.deleteAll().block()29    }30    private val message = KafkaMessage(31        eventId = "EB-001",32        eventName = "consumer-event",33        createdTime = "2020-01-01",34        partitionKey = "12",35        identifiers = mapOf(36            "key1" to "val1"37        ),38        payload = mapOf(39            "message" to "hello"40        )41    )42    @Test43    fun `should consume new message only`() {44        processedMessageAuditRepository.save(45            ProcessedMessageAudit(46                eventId = "EB-000",47                processedAt = LocalDateTime.now(),48                consumerGroupId = "kafka-tryout-consumer-group"49            )50        ).block()51        kafkaProducer52            .produce(topic = "integration-test", message = message)53            .flatMap {54                kafkaProducer.produce(topic = "integration-test-v2", message.copy(eventId = "EB-000"))55            }56            .flatMap {57                kafkaProducer.produce(topic = "integration-test-v2", message.copy(eventId = "EB-002"))58            }59            .block()60        runBlocking {61            eventually(62                EventuallyConfig(63                    duration = 10.toDuration(DurationUnit.SECONDS),64                    interval = FixedInterval(1.toDuration(DurationUnit.SECONDS))65                )66            ) {67                val messages = dummyKafkaConsumer.getAllMessages()68                messages shouldHaveSize 269                messages shouldContainExactlyInAnyOrder listOf(70                    Triple("integration-test", emptyMap(), message),71                    Triple("integration-test-v2", emptyMap(), message.copy(eventId = "EB-002")),72                )73            }74        }75    }76    @Test77    fun `should save audit of processed message`() {78        processedMessageAuditRepository.save(79            ProcessedMessageAudit(80                eventId = "EB-000",81                processedAt = LocalDateTime.now(),82                consumerGroupId = "kafka-tryout-consumer-group"83            )84        ).block()85        kafkaProducer86            .produce(topic = "integration-test", message = message)87            .flatMap {88                kafkaProducer.produce(topic = "integration-test-v2", message.copy(eventId = "EB-002"))89            }90            .block()91        runBlocking {92            eventually(93                EventuallyConfig(94                    duration = 10.toDuration(DurationUnit.SECONDS),95                    interval = FixedInterval(1.toDuration(DurationUnit.SECONDS))96                )97            ) {98                assertNextWith(processedMessageAuditRepository.findAll().collectList()) {99                    it.map { r -> r.eventId } shouldContainExactlyInAnyOrder listOf("EB-000", "EB-001", "EB-002")100                }101            }102        }103    }104}...

Full Screen

Full Screen

TimedCoroutinesTests.kt

Source:TimedCoroutinesTests.kt Github

copy

Full Screen

1package io.alienhead.kronik.core2import io.kotest.assertions.fail3import io.kotest.assertions.until.fixed4import io.kotest.assertions.until.until5import io.kotest.assertions.withClue6import io.kotest.core.spec.style.DescribeSpec7import io.kotest.matchers.shouldBe8import kotlinx.coroutines.delay9import kotlinx.coroutines.launch10import kotlin.time.Duration11import kotlin.time.ExperimentalTime12@ExperimentalTime13class TimedCoroutinesTests : DescribeSpec({14  describe("TimedCoroutines") {15    describe("delayedLaunch()") {16      it("delays the launch of a coroutine") {17        var toTest = 118        launch {19          delayedLaunch(500) {20            toTest++21          }22        }23        withClue("delays for 500 ms") {24          until(Duration.Companion.milliseconds(300), Duration.milliseconds(100).fixed()) {25            toTest == 126          }27        }28        withClue("updates toTest after 500 ms") {29          until(Duration.Companion.milliseconds(600), Duration.milliseconds(100).fixed()) {30            toTest == 231          }32        }33      }34      it("cancels if max time value") {35        var toTest = 136        val testJob = launch {37          delayedLaunch(Long.MAX_VALUE) {38            toTest++39          }40        }41        delay(100)42        if (!testJob.isCompleted) {43          testJob.cancel()44          testJob.join()45          fail("The coroutine should have cancelled.")46        }47        toTest shouldBe 148      }49    }50    describe("intervalLaunchUntil()") {51      it("delays the launch of a coroutine") {52        var toTest = 153        launch {54          intervalLaunchUntil(500, intervalMillis = 500, 2) {55            toTest++56          }57        }58        withClue("delays for 500 ms") {59          until(Duration.Companion.milliseconds(300), Duration.milliseconds(100).fixed()) {60            toTest == 161          }62        }63        withClue("updates toTest after 500 ms") {64          until(Duration.Companion.milliseconds(600), Duration.milliseconds(100).fixed()) {65            toTest == 266          }67        }68        withClue("runs block again after another 150 ms") {69          until(Duration.Companion.milliseconds(1100), Duration.milliseconds(100).fixed()) {70            toTest == 371          }72        }73      }74      it("cancels if initial delay is the max value") {75        var toTest = 176        val testJob = launch {77          intervalLaunchUntil(Long.MAX_VALUE, intervalMillis = 500, 1) {78            toTest++79          }80        }81        delay(100)82        if (!testJob.isCompleted) {83          testJob.cancel()84          testJob.join()85          fail("The coroutine should have cancelled.")86        }87        toTest shouldBe 188      }89      it("cancels if interval delay is the max value") {90        var toTest = 191        val testJob = launch {92          intervalLaunchUntil(500, intervalMillis = Long.MAX_VALUE, 1) {93            toTest++94          }95        }96        delay(100)97        if (!testJob.isCompleted) {98          testJob.cancel()99          testJob.join()100          fail("The coroutine should have cancelled.")101        }102        toTest shouldBe 1103      }104    }105  }106})...

Full Screen

Full Screen

UntilTest.kt

Source:UntilTest.kt Github

copy

Full Screen

1package com.sksamuel.kotest.assertions.until2import io.kotest.assertions.throwables.shouldThrow3import io.kotest.assertions.until.PatienceConfig4import io.kotest.assertions.until.fibonacci5import io.kotest.assertions.until.fixed6import io.kotest.assertions.until.until7import io.kotest.core.spec.style.FunSpec8import io.kotest.matchers.comparables.shouldBeGreaterThan9import io.kotest.matchers.comparables.shouldBeLessThan10import io.kotest.matchers.shouldBe11import java.util.concurrent.CountDownLatch12import java.util.concurrent.TimeUnit13import kotlin.time.Duration.Companion.milliseconds14import kotlin.time.Duration.Companion.seconds15import kotlin.time.TimeSource16class UntilTest : FunSpec({17   test("until with immediate boolean predicate") {18      var attempts = 019       until(1.seconds) {20           attempts++21           System.currentTimeMillis() > 022       }23      attempts shouldBe 124   }25   test("until with boolean predicate that resolves before time duration") {26      var attempts = 027       until(3.seconds) {28           attempts++29           attempts == 230       }31      attempts shouldBe 232   }33   test("until with boolean predicate and interval") {34      var attempts = 035       until(2.seconds, 10.milliseconds.fixed()) {36           attempts++37           attempts == 10038       }39      attempts shouldBe 10040   }41   test("until with patience config") {42      var attempts = 043      until(PatienceConfig(2.seconds, 10.milliseconds.fixed())) {44         attempts++45         attempts == 10046      }47      attempts shouldBe 10048   }49   test("until with predicate") {50      var attempts = 051      var t = ""52       until(5.seconds, { t == "xxx" }) {53           attempts++54           t += "x"55       }56      attempts shouldBe 357   }58   test("until with predicate and interval") {59      val start = TimeSource.Monotonic.markNow()60      var attempts = 061      var t = ""62       until(1.seconds, 10.milliseconds.fixed(), { t == "xxxx" }) {63           attempts++64           t += "x"65       }66      attempts shouldBe 467      start.elapsedNow().shouldBeLessThan(100.milliseconds)68   }69   test("until with predicate, interval, and listener") {70      var t = ""71      val latch = CountDownLatch(5)72      val result =73          until(1.seconds, 10.milliseconds.fixed(), { t == "xxxxx" }, { latch.countDown() }) {74              t += "x"75              t76          }77      latch.await(15, TimeUnit.SECONDS) shouldBe true78      result shouldBe "xxxxx"79   }80   test("until should throw when the predicate doesn't equal true in the time period") {81      shouldThrow<AssertionError> {82          until(1.seconds, { it == 2 }) {83              184          }85      }86   }87   test("until should support fibonacci intervals") {88      val start = TimeSource.Monotonic.markNow()89      var t = ""90      var attempts = 091      val result = until(10.seconds, 10.milliseconds.fibonacci(), { t == "xxxxxx" }) {92          attempts++93          t += "x"94          t95      }96      attempts shouldBe 697      result shouldBe "xxxxxx"98      start.elapsedNow().inWholeMilliseconds.shouldBeGreaterThan(100)99   }100})...

Full Screen

Full Screen

ExponentialIntervalTest.kt

Source:ExponentialIntervalTest.kt Github

copy

Full Screen

1package com.sksamuel.kotest.assertions.until2import io.kotest.assertions.assertSoftly3import io.kotest.assertions.until.ExponentialInterval4import io.kotest.assertions.until.exponential5import io.kotest.core.spec.style.FunSpec6import io.kotest.matchers.comparables.shouldBeGreaterThan7import io.kotest.matchers.comparables.shouldBeGreaterThanOrEqualTo8import io.kotest.matchers.comparables.shouldBeLessThan9import io.kotest.matchers.shouldBe10import kotlin.math.pow11import kotlin.time.Duration12import kotlin.time.Duration.Companion.milliseconds13import kotlin.time.Duration.Companion.seconds14class ExponentialIntervalTest : FunSpec() {15   init {16      test("exponential interval should have a reasonable default next") {17         val identity = 2.seconds18         assertSoftly(identity.exponential()) {19            next(0) shouldBe identity * 120            next(1) shouldBe identity * 221            next(2) shouldBe identity * 422         }23         assertSoftly(identity.exponential(factor = 3.0)) {24            next(0) shouldBe identity * 125            next(1) shouldBe identity * 326            next(2) shouldBe identity * 927         }28      }29      test("exponential interval should have a reasonable default max") {30          val max = ExponentialInterval.defaultMax31          val default = 25.milliseconds.exponential()32          val unbounded = 25.milliseconds.exponential(max = null)33          val first = 034          val last = 2035          unbounded.next(first) shouldBeLessThan max36          unbounded.next(last) shouldBeGreaterThan max37          for (i in first..last) {38              val u = unbounded.next(i)39              val d = default.next(i)40              if (u < max) {41                  d shouldBe u42              } else {43                  d shouldBe max44                  u shouldBeGreaterThan max45              }46          }47      }48      test("exponential interval should respect user specified max") {49          val base = 25.milliseconds50          val n = 551          val max = base * ExponentialInterval.defaultFactor.pow(n)52          val bounded = base.exponential(max = max)53          val unbounded = base.exponential(max = null)54          val first = 055          val last = 2056          unbounded.next(first) shouldBeLessThan max57          unbounded.next(last) shouldBeGreaterThan max58          for (i in first..last) {59              val u = unbounded.next(i)60              val b = bounded.next(i)61              if (u < max) {62                  b shouldBe u63                  i shouldBeLessThan n64              } else {65                  i shouldBeGreaterThanOrEqualTo n...

Full Screen

Full Screen

continually.kt

Source:continually.kt Github

copy

Full Screen

1package io.kotest.assertions.timing2import io.kotest.assertions.SuspendingProducer3import io.kotest.assertions.failure4import io.kotest.assertions.until.Interval5import io.kotest.assertions.until.fixed6import kotlinx.coroutines.delay7import kotlin.time.Duration8import kotlin.time.TimeMark9import kotlin.time.TimeSource10data class ContinuallyState(val start: TimeMark, val end: TimeMark, val times: Int)11fun interface ContinuallyListener<in T> {12   fun onEval(t: T, state: ContinuallyState)13   companion object {14      val noop = ContinuallyListener<Any?> { _, _ -> }15   }16}17data class Continually<T> (18   val duration: Duration = Duration.INFINITE,19   val interval: Interval = Duration.milliseconds(25).fixed(),20   val listener: ContinuallyListener<T> = ContinuallyListener.noop,21   ) {22   suspend operator fun invoke(f: SuspendingProducer<T>): T? {23      val start = TimeSource.Monotonic.markNow()24      val end = start.plus(duration)25      var times = 026      var result: T? = null27      while (end.hasNotPassedNow()) {28         try {29            result = f()30            listener.onEval(result, ContinuallyState(start, end, times))31         } catch (e: AssertionError) {32            // if this is the first time the check was executed then just rethrow the underlying error33            if (times == 0)34               throw e35            // if not the first attempt then include how many times/for how long the test passed36            throw failure(37               "Test failed after ${start.elapsedNow()}; expected to pass for ${duration.inWholeMilliseconds}ms; attempted $times times\nUnderlying failure was: ${e.message}",38               e39            )40         }41         times++42         delay(interval.next(times))43      }44      return result45   }46}47@Deprecated("Use continually with an interval, using Duration based poll is deprecated",48   ReplaceWith("continually(duration, poll.fixed(), f = f)", "io.kotest.assertions.until.fixed")49)50suspend fun <T> continually(duration: Duration, poll: Duration, f: suspend () -> T) =51   continually(duration, poll.fixed(), f = f)52suspend fun <T> continually(duration: Duration, interval: Interval = Duration.milliseconds(10).fixed(), f: suspend () -> T) =53   Continually<T>(duration, interval).invoke(f)...

Full Screen

Full Screen

OrderServiceIntegrationTest.kt

Source:OrderServiceIntegrationTest.kt Github

copy

Full Screen

1package org.learning.demo.app.service2import io.kotest.assertions.timing.EventuallyConfig3import io.kotest.assertions.timing.eventually4import io.kotest.assertions.until.FixedInterval5import io.kotest.matchers.collections.shouldHaveSize6import io.kotest.matchers.maps.shouldContainAll7import kotlinx.coroutines.runBlocking8import org.junit.jupiter.api.BeforeEach9import org.junit.jupiter.api.Test10import org.learning.demo.IntegrationTest11import org.learning.demo.app.domain.Product12import org.learning.demo.app.view.CartView13import org.learning.demo.util.EmbeddedKafkaConsumer14import org.springframework.beans.factory.annotation.Autowired15import java.math.BigDecimal16import kotlin.time.DurationUnit17import kotlin.time.toDuration18@IntegrationTest19class OrderServiceIntegrationTest(20    @Autowired private val orderService: OrderService,21    @Autowired private val embeddedKafkaConsumer: EmbeddedKafkaConsumer22) {23    @BeforeEach24    fun setUp() {25        embeddedKafkaConsumer.clearTopic("order")26    }27    @Test28    fun `should raise order created event on order creation`() {29        val product = Product(productCode = "P-0022", quantity = 3, price = BigDecimal("20.34"))30        orderService.createOrderFrom(CartView(id = "C-002", products = setOf(product))).block()31        runBlocking {32            eventually(33                EventuallyConfig(34                    duration = 5.toDuration(DurationUnit.SECONDS),35                    interval = FixedInterval(1.toDuration(DurationUnit.SECONDS))36                )37            ) {38                val messages = embeddedKafkaConsumer.readNextMessage("order", "order-created")39                messages shouldHaveSize 140                messages.first().payload shouldContainAll mapOf(41                    "products" to listOf(42                        mapOf(43                            "productCode" to "P-0022",44                            "quantity" to 3,45                            "price" to 20.34,46                        )47                    ),48                    "totalPrice" to 61.02,49                    "eventName" to "order-created"...

Full Screen

Full Screen

Assertions.kt

Source:Assertions.kt Github

copy

Full Screen

1package dev.akkinoc.spring.boot.logback.access.test.assertion2import io.kotest.assertions.timing.continually3import io.kotest.assertions.timing.eventually4import io.kotest.assertions.until.fixed5import kotlinx.coroutines.runBlocking6import kotlin.time.Duration.Companion.milliseconds7import kotlin.time.Duration.Companion.seconds8/**9 * The utility methods to support test assertions.10 */11object Assertions {12    /**13     * Asserts that the assertion function will eventually pass within a short time.14     * Used to assert Logback-access events that may be appended late.15     *16     * @param T The return value type of the assertion function.17     * @param assert The assertion function that is called repeatedly.18     * @return The return value of the assertion function.19     */20    fun <T> assertLogbackAccessEventsEventually(assert: () -> T): T {21        return runBlocking {22            eventually<T>(duration = seconds(1), interval = milliseconds(100).fixed()) { assert() }23        }24    }25    /**26     * Asserts that the assertion function will continually pass within a short time.27     * Used to assert Logback-access events that may be appended late.28     *29     * @param T The return value type of the assertion function.30     * @param assert The assertion function that is called repeatedly.31     * @return The return value of the assertion function.32     */33    fun <T> assertLogbackAccessEventsContinually(assert: () -> T): T? {34        return runBlocking {35            continually(duration = seconds(1), interval = milliseconds(100).fixed()) { assert() }36        }37    }38}...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Kotest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used methods in Interval

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful