-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathSwingTest.kt
100 lines (90 loc) · 2.75 KB
/
SwingTest.kt
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
88
89
90
91
92
93
94
95
96
97
98
99
100
/*
* Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.swing
import kotlinx.coroutines.*
import org.junit.*
import org.junit.Test
import javax.swing.*
import kotlin.coroutines.*
import kotlin.test.*
class SwingTest : TestBase() {
@Before
fun setup() {
ignoreLostThreads("AWT-EventQueue-")
}
@Test
fun testDelay() = runBlocking {
expect(1)
SwingUtilities.invokeLater { expect(2) }
val job = launch(Dispatchers.Swing) {
check(SwingUtilities.isEventDispatchThread())
expect(3)
SwingUtilities.invokeLater { expect(4) }
delay(100)
check(SwingUtilities.isEventDispatchThread())
expect(5)
}
job.join()
finish(6)
}
private class SwingComponent(coroutineContext: CoroutineContext = EmptyCoroutineContext) :
CoroutineScope by MainScope() + coroutineContext
{
public var executed = false
fun testLaunch(): Job = launch {
check(SwingUtilities.isEventDispatchThread())
executed = true
}
fun testFailure(): Job = launch {
check(SwingUtilities.isEventDispatchThread())
throw TestException()
}
fun testCancellation() : Job = launch(start = CoroutineStart.ATOMIC) {
check(SwingUtilities.isEventDispatchThread())
delay(Long.MAX_VALUE)
}
}
@Test
fun testLaunchInMainScope() = runTest {
val component = SwingComponent()
val job = component.testLaunch()
job.join()
assertTrue(component.executed)
component.cancel()
component.coroutineContext[Job]!!.join()
}
@Test
fun testFailureInMainScope() = runTest {
var exception: Throwable? = null
val component = SwingComponent(CoroutineExceptionHandler { ctx, e -> exception = e})
val job = component.testFailure()
job.join()
assertTrue(exception!! is TestException)
component.cancel()
join(component)
}
@Test
fun testCancellationInMainScope() = runTest {
val component = SwingComponent()
component.cancel()
component.testCancellation().join()
join(component)
}
private suspend fun join(component: SwingComponent) {
component.coroutineContext[Job]!!.join()
}
@Test
fun testImmediateDispatcherYield() = runBlocking(Dispatchers.Swing) {
expect(1)
// launch in the immediate dispatcher
launch(Dispatchers.Swing.immediate) {
expect(2)
yield()
expect(4)
}
expect(3) // after yield
yield() // yield back
finish(5)
}
}