package kotlinx.coroutines.flow import kotlinx.coroutines.testing.* 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()) } }