blob: a111a739d8103540a957536228142936eda06526 [file] [log] [blame]
Roman Elizarov3e342e32018-01-13 20:05:51 +03001/*
Roman Elizarov1f74a2d2018-06-29 19:19:45 +03002 * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
Roman Elizarov3e342e32018-01-13 20:05:51 +03003 */
4
5package kotlinx.coroutines.experimental.reactive
6
7import kotlinx.coroutines.experimental.*
8import kotlinx.coroutines.experimental.selects.*
9import org.junit.*
10import org.junit.Assert.*
11import org.junit.runner.*
12import org.junit.runners.*
Roman Elizarov9fe5f462018-02-21 19:05:52 +030013import kotlin.coroutines.experimental.*
Roman Elizarov3e342e32018-01-13 20:05:51 +030014
15@RunWith(Parameterized::class)
16class PublisherSubscriptionSelectTest(val request: Int) : TestBase() {
17 companion object {
18 @Parameterized.Parameters(name = "request = {0}")
19 @JvmStatic
20 fun params(): Collection<Array<Any>> = listOf(0, 1, 10).map { arrayOf<Any>(it) }
21 }
22
23 @Test
24 fun testSelect() = runTest {
25 // source with n ints
26 val n = 1000 * stressTestMultiplier
27 val source = publish(coroutineContext) { repeat(n) { send(it) } }
28 var a = 0
29 var b = 0
30 // open two subs
Marko Devcic1d6230a2018-04-04 20:13:08 +020031 val channelA = source.openSubscription(request)
32 val channelB = source.openSubscription(request)
33 loop@ while (true) {
34 val done: Int = select {
35 channelA.onReceiveOrNull {
36 if (it != null) assertEquals(a++, it)
37 if (it == null) 0 else 1
38 }
39 channelB.onReceiveOrNull {
40 if (it != null) assertEquals(b++, it)
41 if (it == null) 0 else 2
42 }
43 }
44 when (done) {
45 0 -> break@loop
46 1 -> {
47 val r = channelB.receiveOrNull()
48 if (r != null) assertEquals(b++, r)
49 }
50 2 -> {
51 val r = channelA.receiveOrNull()
52 if (r != null) assertEquals(a++, r)
Roman Elizarov3e342e32018-01-13 20:05:51 +030053 }
54 }
55 }
Marko Devcic1d6230a2018-04-04 20:13:08 +020056
57 channelA.cancel()
58 channelB.cancel()
Roman Elizarov3e342e32018-01-13 20:05:51 +030059 // should receive one of them fully
60 assertTrue(a == n || b == n)
61 }
62}