blob: 20322cde1f984d579c805c22085f87b92bb4387a [file] [log] [blame]
Roman Elizarov04d11ca2017-02-27 12:47:32 +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.selects
18
Roman Elizarov9fe5f462018-02-21 19:05:52 +030019import kotlinx.coroutines.experimental.*
Roman Elizarov9fe5f462018-02-21 19:05:52 +030020import kotlin.coroutines.experimental.*
Vsevolod Tolstopyatov2cdbfd72018-04-22 18:26:14 +030021import kotlin.test.*
Roman Elizarov04d11ca2017-02-27 12:47:32 +030022
Vsevolod Tolstopyatov2cdbfd72018-04-22 18:26:14 +030023class SelectBiasTest : TestBase() {
Roman Elizarov04d11ca2017-02-27 12:47:32 +030024 val n = 10_000
25
26 @Test
Vsevolod Tolstopyatov2cdbfd72018-04-22 18:26:14 +030027 fun testBiased() = runTest {
Roman Elizarov43e3af72017-07-21 16:01:31 +030028 val d0 = async(coroutineContext) { 0 }
29 val d1 = async(coroutineContext) { 1 }
Roman Elizarov04d11ca2017-02-27 12:47:32 +030030 val counter = IntArray(2)
31 repeat(n) {
32 val selected = select<Int> {
33 d0.onAwait { 0 }
34 d1.onAwait { 1 }
35 }
36 counter[selected]++
37 }
38 assertEquals(n, counter[0])
39 assertEquals(0, counter[1])
40 }
41
42 @Test
Vsevolod Tolstopyatov2cdbfd72018-04-22 18:26:14 +030043 fun testUnbiased() = runTest {
Roman Elizarov43e3af72017-07-21 16:01:31 +030044 val d0 = async(coroutineContext) { 0 }
45 val d1 = async(coroutineContext) { 1 }
Roman Elizarov04d11ca2017-02-27 12:47:32 +030046 val counter = IntArray(2)
47 repeat(n) {
48 val selected = selectUnbiased<Int> {
49 d0.onAwait { 0 }
50 d1.onAwait { 1 }
51 }
52 counter[selected]++
53 }
54 assertTrue(counter[0] >= n / 4)
55 assertTrue(counter[1] >= n / 4)
56 }
57}