blob: e3a212621eb5647872b086c537afb239d84270a3 [file] [log] [blame]
Vsevolod Tolstopyatov1cbe8f02018-06-05 18:13:51 +03001package kotlinx.coroutines.experimental.future
2
3import kotlinx.coroutines.experimental.*
4import org.junit.Test
5import java.io.*
6import java.util.concurrent.*
7import kotlin.coroutines.experimental.*
8import kotlin.test.*
9
10class FutureExceptionsTest : TestBase() {
11
12 @Test
13 fun testAwait() {
14 testException(IOException(), { it is IOException })
15 }
16
17 @Test
18 fun testAwaitChained() {
19 testException(IOException(), { it is IOException }, { f -> f.thenApply { it + 1 } })
20 }
21
22 @Test
23 fun testAwaitDeepChain() {
24 testException(IOException(), { it is IOException },
25 { f -> f
26 .thenApply { it + 1 }
27 .thenApply { it + 2 } })
28 }
29
30 @Test
31 fun testAwaitCompletionException() {
32 testException(CompletionException("test", IOException()), { it is IOException })
33 }
34
35 @Test
36 fun testAwaitChainedCompletionException() {
37 testException(CompletionException("test", IOException()), { it is IOException }, { f -> f.thenApply { it + 1 } })
38 }
39
40 @Test
41 fun testAwaitTestException() {
42 testException(TestException(), { it is TestException })
43 }
44
45 @Test
46 fun testAwaitChainedTestException() {
47 testException(TestException(), { it is TestException }, { f -> f.thenApply { it + 1 } })
48 }
49
50 class TestException : CompletionException("test2")
51
52 private fun testException(
53 exception: Exception,
54 expected: ((Throwable) -> Boolean),
55 transformer: (CompletableFuture<Int>) -> CompletableFuture<Int> = { it }
56 ) {
57
58 // Fast path
59 runTest {
60 val future = CompletableFuture<Int>()
61 val chained = transformer(future)
62 future.completeExceptionally(exception)
63 try {
64 chained.await()
65 } catch (e: Exception) {
66 assertTrue(expected(e))
67 }
68 }
69
70 // Slow path
71 runTest {
72 val future = CompletableFuture<Int>()
73 val chained = transformer(future)
74
75 launch(coroutineContext) {
76 future.completeExceptionally(exception)
77 }
78
79 try {
80 chained.await()
81 } catch (e: Exception) {
82 assertTrue(expected(e))
83 }
84 }
85 }
86}