1 /* <lambda>null2 * Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. 3 */ 4 5 package kotlinx.coroutines.swing 6 7 import kotlinx.coroutines.* 8 import org.junit.* 9 import org.junit.Test 10 import javax.swing.* 11 import kotlin.coroutines.* 12 import kotlin.test.* 13 14 class SwingTest : TestBase() { 15 @Before 16 fun setup() { 17 ignoreLostThreads("AWT-EventQueue-") 18 } 19 20 @Test 21 fun testDelay() = runBlocking { 22 expect(1) 23 SwingUtilities.invokeLater { expect(2) } 24 val job = launch(Dispatchers.Swing) { 25 check(SwingUtilities.isEventDispatchThread()) 26 expect(3) 27 SwingUtilities.invokeLater { expect(4) } 28 delay(100) 29 check(SwingUtilities.isEventDispatchThread()) 30 expect(5) 31 } 32 job.join() 33 finish(6) 34 } 35 36 private class SwingComponent(coroutineContext: CoroutineContext = EmptyCoroutineContext) : 37 CoroutineScope by MainScope() + coroutineContext 38 { 39 public var executed = false 40 fun testLaunch(): Job = launch { 41 check(SwingUtilities.isEventDispatchThread()) 42 executed = true 43 } 44 fun testFailure(): Job = launch { 45 check(SwingUtilities.isEventDispatchThread()) 46 throw TestException() 47 } 48 fun testCancellation() : Job = launch(start = CoroutineStart.ATOMIC) { 49 check(SwingUtilities.isEventDispatchThread()) 50 delay(Long.MAX_VALUE) 51 } 52 } 53 54 @Test 55 fun testLaunchInMainScope() = runTest { 56 val component = SwingComponent() 57 val job = component.testLaunch() 58 job.join() 59 assertTrue(component.executed) 60 component.cancel() 61 component.coroutineContext[Job]!!.join() 62 } 63 64 @Test 65 fun testFailureInMainScope() = runTest { 66 var exception: Throwable? = null 67 val component = SwingComponent(CoroutineExceptionHandler { ctx, e -> exception = e}) 68 val job = component.testFailure() 69 job.join() 70 assertTrue(exception!! is TestException) 71 component.cancel() 72 join(component) 73 } 74 75 @Test 76 fun testCancellationInMainScope() = runTest { 77 val component = SwingComponent() 78 component.cancel() 79 component.testCancellation().join() 80 join(component) 81 } 82 83 private suspend fun join(component: SwingComponent) { 84 component.coroutineContext[Job]!!.join() 85 } 86 87 @Test 88 fun testImmediateDispatcherYield() = runBlocking(Dispatchers.Swing) { 89 expect(1) 90 // launch in the immediate dispatcher 91 launch(Dispatchers.Swing.immediate) { 92 expect(2) 93 yield() 94 expect(4) 95 } 96 expect(3) // after yield 97 yield() // yield back 98 finish(5) 99 } 100 101 @Test 102 fun testMainDispatcherToString() { 103 assertEquals("Dispatchers.Main", Dispatchers.Main.toString()) 104 assertEquals("Dispatchers.Main.immediate", Dispatchers.Main.immediate.toString()) 105 } 106 }