Roman Elizarov | 3e342e3 | 2018-01-13 20:05:51 +0300 | [diff] [blame] | 1 | /* |
Roman Elizarov | 1f74a2d | 2018-06-29 19:19:45 +0300 | [diff] [blame^] | 2 | * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. |
Roman Elizarov | 3e342e3 | 2018-01-13 20:05:51 +0300 | [diff] [blame] | 3 | */ |
| 4 | |
| 5 | package kotlinx.coroutines.experimental.reactive |
| 6 | |
| 7 | import kotlinx.coroutines.experimental.* |
| 8 | import kotlinx.coroutines.experimental.selects.* |
| 9 | import org.junit.* |
| 10 | import org.junit.Assert.* |
| 11 | import org.junit.runner.* |
| 12 | import org.junit.runners.* |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 13 | import kotlin.coroutines.experimental.* |
Roman Elizarov | 3e342e3 | 2018-01-13 20:05:51 +0300 | [diff] [blame] | 14 | |
| 15 | @RunWith(Parameterized::class) |
| 16 | class 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 Devcic | 1d6230a | 2018-04-04 20:13:08 +0200 | [diff] [blame] | 31 | 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 Elizarov | 3e342e3 | 2018-01-13 20:05:51 +0300 | [diff] [blame] | 53 | } |
| 54 | } |
| 55 | } |
Marko Devcic | 1d6230a | 2018-04-04 20:13:08 +0200 | [diff] [blame] | 56 | |
| 57 | channelA.cancel() |
| 58 | channelB.cancel() |
Roman Elizarov | 3e342e3 | 2018-01-13 20:05:51 +0300 | [diff] [blame] | 59 | // should receive one of them fully |
| 60 | assertTrue(a == n || b == n) |
| 61 | } |
| 62 | } |