commonTest.flow.terminal.SingleTest.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of kotlinx-coroutines-core
Show all versions of kotlinx-coroutines-core
Coroutines support libraries for Kotlin
/*
* Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.flow
import kotlinx.coroutines.*
import kotlin.test.*
class SingleTest : TestBase() {
@Test
fun testSingle() = runTest {
val flow = flow {
emit(239L)
}
assertEquals(239L, flow.single())
assertEquals(239L, flow.singleOrNull())
}
@Test
fun testMultipleValues() = runTest {
val flow = flow {
emit(239L)
emit(240L)
}
assertFailsWith { flow.single() }
assertNull(flow.singleOrNull())
}
@Test
fun testNoValues() = runTest {
assertFailsWith { flow {}.single() }
assertNull(flow {}.singleOrNull())
}
@Test
fun testException() = runTest {
val flow = flow {
throw TestException()
}
assertFailsWith { flow.single() }
assertFailsWith { flow.singleOrNull() }
}
@Test
fun testExceptionAfterValue() = runTest {
val flow = flow {
emit(1)
throw TestException()
}
assertFailsWith { flow.single() }
assertFailsWith { flow.singleOrNull() }
}
@Test
fun testNullableSingle() = runTest {
assertEquals(1, flowOf(1).single())
assertNull(flowOf(null).single())
assertFailsWith { flowOf().single() }
assertEquals(1, flowOf(1).singleOrNull())
assertNull(flowOf(null).singleOrNull())
assertNull(flowOf().singleOrNull())
}
@Test
fun testBadClass() = runTest {
val instance = BadClass()
val flow = flowOf(instance)
assertSame(instance, flow.single())
assertSame(instance, flow.singleOrNull())
val flow2 = flow {
emit(BadClass())
emit(BadClass())
}
assertFailsWith { flow2.single() }
}
@Test
fun testSingleNoWait() = runTest {
val flow = flow {
emit(1)
emit(2)
awaitCancellation()
}
assertNull(flow.singleOrNull())
}
}