All Downloads are FREE. Search and download functionalities are using the official Maven repository.

jvmMain.io.kotest.matchers.channels.ChannelMatchers.kt Maven / Gradle / Ivy

package io.kotest.matchers.channels

import io.kotest.matchers.Matcher
import io.kotest.matchers.MatcherResult
import io.kotest.matchers.should
import io.kotest.matchers.shouldNot
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay

/**
 * Asserts that this [Channel] is closed
 *
 * Opposite of [Channel.shouldBeOpen]
 *
 */
@ExperimentalCoroutinesApi
fun  Channel.shouldBeClosed() = this should beClosed()

@ExperimentalCoroutinesApi
fun  beClosed() = object : Matcher> {
   override fun test(value: Channel) = MatcherResult(
      value.isClosedForSend && value.isClosedForReceive,
      { "Channel should be closed" },
      { "Channel should not be closed" }
   )
}

/**
 * Asserts that this [Channel] is open
 *
 * Opposite of [Channel.shouldBeClosed]
 *
 */
@ExperimentalCoroutinesApi
fun  Channel.shouldBeOpen() = this shouldNot beClosed()

/**
 * Asserts that this [Channel] is empty
 *
 */
@ExperimentalCoroutinesApi
fun  Channel.shouldBeEmpty() = this should beEmpty()

@ExperimentalCoroutinesApi
fun  beEmpty() = object : Matcher> {
   override fun test(value: Channel) = MatcherResult(
      value.isEmpty,
      { "Channel should be empty" },
      { "Channel should not be empty" }
   )
}

/**
 * Asserts that this [Channel] should receive [n] elements, then is closed.
 *
 */
@ExperimentalCoroutinesApi
suspend fun  Channel.shouldHaveSize(n: Int) {
   repeat(n) {
      [email protected]()
   }
   [email protected]()
}

/**
 * Asserts that this [Channel] should receive at least [n] elements
 *
 */
suspend fun  Channel.shouldReceiveAtLeast(n: Int) {
   repeat(n) { [email protected]() }
}

/**
 * Asserts that this [Channel] should receive at most [n] elements, then close
 *
 */
@ExperimentalCoroutinesApi
suspend fun  Channel.shouldReceiveAtMost(n: Int) {
   var count = 0
   for (value in this@shouldReceiveAtMost) {
      count++
      if (count == n) break
   }
   delay(100)
   [email protected]()
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy