|
| 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 kotlin.coroutines.ContinuationInterceptor |
| 8 | +import kotlin.coroutines.CoroutineContext |
| 9 | +import kotlin.test.* |
| 10 | + |
| 11 | +class CoroutineDispatcherOperatorFunInvokeTest : TestBase() { |
| 12 | + |
| 13 | + /** |
| 14 | + * Copy pasted from [WithContextTest.testThrowException], |
| 15 | + * then edited to use operator. |
| 16 | + */ |
| 17 | + @Test |
| 18 | + fun testThrowException() = runTest { |
| 19 | + expect(1) |
| 20 | + try { |
| 21 | + (wrappedCurrentDispatcher()) { |
| 22 | + expect(2) |
| 23 | + throw AssertionError() |
| 24 | + } |
| 25 | + } catch (e: AssertionError) { |
| 26 | + expect(3) |
| 27 | + } |
| 28 | + |
| 29 | + yield() |
| 30 | + finish(4) |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * Copy pasted from [WithContextTest.testWithContextChildWaitSameContext], |
| 35 | + * then edited to use operator fun invoke for [CoroutineDispatcher]. |
| 36 | + */ |
| 37 | + @Test |
| 38 | + fun testWithContextChildWaitSameContext() = runTest { |
| 39 | + expect(1) |
| 40 | + (wrappedCurrentDispatcher()) { |
| 41 | + expect(2) |
| 42 | + launch { |
| 43 | + // ^^^ schedules to main thread |
| 44 | + expect(4) // waits before return |
| 45 | + } |
| 46 | + expect(3) |
| 47 | + "OK".wrap() |
| 48 | + }.unwrap() |
| 49 | + finish(5) |
| 50 | + } |
| 51 | + |
| 52 | + private class Wrapper(val value: String) : Incomplete { |
| 53 | + override val isActive: Boolean |
| 54 | + get() = error("") |
| 55 | + override val list: NodeList? |
| 56 | + get() = error("") |
| 57 | + } |
| 58 | + |
| 59 | + private fun String.wrap() = Wrapper(this) |
| 60 | + private fun Wrapper.unwrap() = value |
| 61 | + |
| 62 | + private fun CoroutineScope.wrappedCurrentDispatcher() = object : CoroutineDispatcher() { |
| 63 | + val dispatcher = coroutineContext[ContinuationInterceptor] as CoroutineDispatcher |
| 64 | + override fun dispatch(context: CoroutineContext, block: Runnable) { |
| 65 | + dispatcher.dispatch(context, block) |
| 66 | + } |
| 67 | + |
| 68 | + @ExperimentalCoroutinesApi |
| 69 | + override fun isDispatchNeeded(context: CoroutineContext): Boolean { |
| 70 | + return dispatcher.isDispatchNeeded(context) |
| 71 | + } |
| 72 | + |
| 73 | + @InternalCoroutinesApi |
| 74 | + override fun dispatchYield(context: CoroutineContext, block: Runnable) { |
| 75 | + dispatcher.dispatchYield(context, block) |
| 76 | + } |
| 77 | + } |
| 78 | +} |
0 commit comments