Roman Elizarov | 1f74a2d | 2018-06-29 19:19:45 +0300 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. |
| 3 | */ |
| 4 | |
Vsevolod Tolstopyatov | 1cbe8f0 | 2018-06-05 18:13:51 +0300 | [diff] [blame] | 5 | package kotlinx.coroutines.experimental.guava |
| 6 | |
| 7 | import com.google.common.util.concurrent.* |
| 8 | import kotlinx.coroutines.experimental.* |
| 9 | import org.junit.Test |
| 10 | import java.io.* |
| 11 | import java.util.concurrent.* |
| 12 | import kotlin.coroutines.experimental.* |
| 13 | import kotlin.test.* |
| 14 | |
| 15 | class ListenableFutureExceptionsTest : TestBase() { |
| 16 | |
| 17 | @Test |
| 18 | fun testAwait() { |
| 19 | testException(IOException(), { it is IOException }) |
| 20 | } |
| 21 | |
| 22 | @Test |
| 23 | fun testAwaitChained() { |
| 24 | testException(IOException(), { it is IOException }, { i -> i!! + 1 }) |
| 25 | } |
| 26 | |
| 27 | @Test |
| 28 | fun testAwaitCompletionException() { |
| 29 | testException(CompletionException("test", IOException()), { it is CompletionException }) |
| 30 | } |
| 31 | |
| 32 | @Test |
| 33 | fun testAwaitChainedCompletionException() { |
| 34 | testException( |
| 35 | CompletionException("test", IOException()), |
| 36 | { it is CompletionException }, |
| 37 | { i -> i!! + 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 }, { i -> i!! + 1 }) |
| 48 | } |
| 49 | |
| 50 | class TestException : CompletionException("test2") |
| 51 | |
| 52 | private fun testException( |
| 53 | exception: Exception, |
| 54 | expected: ((Throwable) -> Boolean), |
| 55 | transformer: ((Int?) -> Int?)? = null |
| 56 | ) { |
| 57 | |
| 58 | // Fast path |
| 59 | runTest { |
| 60 | val future = SettableFuture.create<Int>() |
| 61 | val chained = if (transformer == null) future else Futures.transform(future, transformer) |
| 62 | future.setException(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 = SettableFuture.create<Int>() |
| 73 | val chained = if (transformer == null) future else Futures.transform(future, transformer) |
| 74 | launch(coroutineContext) { |
| 75 | future.setException(exception) |
| 76 | } |
| 77 | |
| 78 | try { |
| 79 | chained.await() |
| 80 | } catch (e: Exception) { |
| 81 | assertTrue(expected(e)) |
| 82 | } |
| 83 | } |
| 84 | } |
| 85 | } |