• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
3  */
4 
5 package kotlinx.coroutines
6 
7 import kotlinx.coroutines.channels.*
8 import java.io.*
9 import java.util.concurrent.*
10 import java.util.concurrent.atomic.*
11 import kotlin.test.*
12 
13 class RunInterruptibleTest : TestBase() {
14 
15     @Test
<lambda>null16     fun testNormalRun() = runTest {
17         val result = runInterruptible {
18             val x = 1
19             val y = 2
20             Thread.sleep(1)
21             x + y
22         }
23         assertEquals(3, result)
24     }
25 
26     @Test
<lambda>null27     fun testExceptionalRun() = runTest {
28         try {
29             runInterruptible {
30                 expect(1)
31                 throw TestException()
32             }
33         } catch (e: TestException) {
34             finish(2)
35         }
36     }
37 
38     @Test
<lambda>null39     fun testInterrupt() = runTest {
40         val latch = Channel<Unit>(1)
41         val job = launch {
42             runInterruptible(Dispatchers.IO) {
43                 expect(2)
44                 latch.offer(Unit)
45                 try {
46                     Thread.sleep(10_000L)
47                     expectUnreached()
48                 } catch (e: InterruptedException) {
49                     expect(4)
50                     assertFalse { Thread.currentThread().isInterrupted }
51                 }
52             }
53         }
54 
55         launch(start = CoroutineStart.UNDISPATCHED) {
56             expect(1)
57             latch.receive()
58             expect(3)
59             job.cancelAndJoin()
60         }.join()
61         finish(5)
62     }
63 }
64