blob: 860bffad0a2c2d5cec32f0acb63961bd32fad3dc [file] [log] [blame]
Roman Elizarov3e342e32018-01-13 20:05:51 +03001/*
2 * Copyright 2016-2017 JetBrains s.r.o.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package kotlinx.coroutines.experimental.reactive
18
19import kotlinx.coroutines.experimental.*
20import kotlinx.coroutines.experimental.selects.*
21import org.junit.*
22import org.junit.Assert.*
23import org.junit.runner.*
24import org.junit.runners.*
Roman Elizarov9fe5f462018-02-21 19:05:52 +030025import kotlin.coroutines.experimental.*
Roman Elizarov3e342e32018-01-13 20:05:51 +030026
27@RunWith(Parameterized::class)
28class PublisherSubscriptionSelectTest(val request: Int) : TestBase() {
29 companion object {
30 @Parameterized.Parameters(name = "request = {0}")
31 @JvmStatic
32 fun params(): Collection<Array<Any>> = listOf(0, 1, 10).map { arrayOf<Any>(it) }
33 }
34
35 @Test
36 fun testSelect() = runTest {
37 // source with n ints
38 val n = 1000 * stressTestMultiplier
39 val source = publish(coroutineContext) { repeat(n) { send(it) } }
40 var a = 0
41 var b = 0
42 // open two subs
Marko Devcic1d6230a2018-04-04 20:13:08 +020043 val channelA = source.openSubscription(request)
44 val channelB = source.openSubscription(request)
45 loop@ while (true) {
46 val done: Int = select {
47 channelA.onReceiveOrNull {
48 if (it != null) assertEquals(a++, it)
49 if (it == null) 0 else 1
50 }
51 channelB.onReceiveOrNull {
52 if (it != null) assertEquals(b++, it)
53 if (it == null) 0 else 2
54 }
55 }
56 when (done) {
57 0 -> break@loop
58 1 -> {
59 val r = channelB.receiveOrNull()
60 if (r != null) assertEquals(b++, r)
61 }
62 2 -> {
63 val r = channelA.receiveOrNull()
64 if (r != null) assertEquals(a++, r)
Roman Elizarov3e342e32018-01-13 20:05:51 +030065 }
66 }
67 }
Marko Devcic1d6230a2018-04-04 20:13:08 +020068
69 channelA.cancel()
70 channelB.cancel()
Roman Elizarov3e342e32018-01-13 20:05:51 +030071 // should receive one of them fully
72 assertTrue(a == n || b == n)
73 }
74}