aboutsummaryrefslogtreecommitdiffstats
path: root/kotlinx-coroutines-core/jvm/test/FailFastOnStartTest.kt
blob: 8a7878c9a68a799f1e4e6f336188c5dd0651679b (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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*
 * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
 */

@file:Suppress("DeferredResultUnused")

package kotlinx.coroutines

import kotlinx.coroutines.channels.*
import org.junit.*
import org.junit.Test
import org.junit.rules.*
import kotlin.test.*

class FailFastOnStartTest : TestBase() {

    @Rule
    @JvmField
    public val timeout: Timeout = Timeout.seconds(5)

    @Test
    fun testLaunch() = runTest(expected = ::mainException) {
        launch(Dispatchers.Main) {}
    }

    @Test
    fun testLaunchLazy() = runTest(expected = ::mainException) {
        val job = launch(Dispatchers.Main, start = CoroutineStart.LAZY) { fail() }
        job.join()
    }

    @Test
    fun testLaunchUndispatched() = runTest(expected = ::mainException) {
        launch(Dispatchers.Main, start = CoroutineStart.UNDISPATCHED) {
            yield()
            fail()
        }
    }

    @Test
    fun testAsync() = runTest(expected = ::mainException) {
        async(Dispatchers.Main) {}
    }

    @Test
    fun testAsyncLazy() = runTest(expected = ::mainException) {
        val job = async(Dispatchers.Main, start = CoroutineStart.LAZY) { fail() }
        job.await()
    }

    @Test
    fun testWithContext() = runTest(expected = ::mainException) {
        withContext(Dispatchers.Main) {
            fail()
        }
    }

    @Test
    fun testProduce() = runTest(expected = ::mainException) {
        produce<Int>(Dispatchers.Main) { fail() }
    }

    @Test
    fun testActor() = runTest(expected = ::mainException) {
        actor<Int>(Dispatchers.Main) { fail() }
    }

    @Test
    fun testActorLazy() = runTest(expected = ::mainException) {
        val actor = actor<Int>(Dispatchers.Main, start = CoroutineStart.LAZY) { fail() }
        actor.send(1)
    }

    private fun mainException(e: Throwable): Boolean {
        return e is IllegalStateException && e.message?.contains("Module with the Main dispatcher is missing") ?: false
    }

    @Test
    fun testProduceNonChild() = runTest(expected = ::mainException) {
        produce<Int>(Job() + Dispatchers.Main) { fail() }
    }

    @Test
    fun testAsyncNonChild() = runTest(expected = ::mainException) {
        async<Int>(Job() + Dispatchers.Main) { fail() }
    }
}