aboutsummaryrefslogtreecommitdiffstats
path: root/reactive/kotlinx-coroutines-reactive/test/PublisherSubscriptionSelectTest.kt
blob: 110718ac55c01ae555c82f011803abb179e81454 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
 * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
 */

package kotlinx.coroutines.reactive

import kotlinx.coroutines.*
import kotlinx.coroutines.selects.*
import org.junit.Test
import org.junit.runner.*
import org.junit.runners.*
import kotlin.test.*

@RunWith(Parameterized::class)
class PublisherSubscriptionSelectTest(private val request: Int) : TestBase() {
    companion object {
        @Parameterized.Parameters(name = "request = {0}")
        @JvmStatic
        fun params(): Collection<Array<Any>> = listOf(0, 1, 10).map { arrayOf<Any>(it) }
    }

    @Test
    fun testSelect() = runTest {
        // source with n ints
        val n = 1000 * stressTestMultiplier
        val source = publish { repeat(n) { send(it) } }
        var a = 0
        var b = 0
        // open two subs
        val channelA = source.openSubscription(request)
        val channelB = source.openSubscription(request)
        loop@ while (true) {
            val done: Int = select {
                channelA.onReceiveOrNull {
                    if (it != null) assertEquals(a++, it)
                    if (it == null) 0 else 1
                }
                channelB.onReceiveOrNull {
                    if (it != null) assertEquals(b++, it)
                    if (it == null) 0 else 2
                }
            }
            when (done) {
                0 -> break@loop
                1 -> {
                    val r = channelB.receiveOrNull()
                    if (r != null) assertEquals(b++, r)
                }
                2 -> {
                    val r = channelA.receiveOrNull()
                    if (r != null) assertEquals(a++, r)
                }
            }
        }

        channelA.cancel()
        channelB.cancel()
        // should receive one of them fully
        assertTrue(a == n || b == n)
    }
}