1 /* 2 * Copyright 2016-2021 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 kotlinx.coroutines.flow.internal.* 9 import kotlin.test.* 10 11 class CancelledParentAttachTest : TestBase() { 12 13 @Test <lambda>null14 fun testAsync() = runTest { 15 CoroutineStart.values().forEach { testAsyncCancelledParent(it) } 16 } 17 testAsyncCancelledParentnull18 private suspend fun testAsyncCancelledParent(start: CoroutineStart) { 19 try { 20 withContext(Job()) { 21 cancel() 22 expect(1) 23 val d = async<Int>(start = start) { 42 } 24 expect(2) 25 d.invokeOnCompletion { 26 finish(3) 27 reset() 28 } 29 } 30 expectUnreached() 31 } catch (e: CancellationException) { 32 // Expected 33 } 34 } 35 36 @Test <lambda>null37 fun testLaunch() = runTest { 38 CoroutineStart.values().forEach { testLaunchCancelledParent(it) } 39 } 40 testLaunchCancelledParentnull41 private suspend fun testLaunchCancelledParent(start: CoroutineStart) { 42 try { 43 withContext(Job()) { 44 cancel() 45 expect(1) 46 val d = launch(start = start) { } 47 expect(2) 48 d.invokeOnCompletion { 49 finish(3) 50 reset() 51 } 52 } 53 expectUnreached() 54 } catch (e: CancellationException) { 55 // Expected 56 } 57 } 58 59 @Test <lambda>null60 fun testProduce() = runTest({ it is CancellationException }) { 61 cancel() 62 expect(1) <lambda>null63 val d = produce<Int> { } 64 expect(2) <lambda>null65 (d as Job).invokeOnCompletion { 66 finish(3) 67 reset() 68 } 69 } 70 71 @Test <lambda>null72 fun testBroadcast() = runTest { 73 CoroutineStart.values().forEach { testBroadcastCancelledParent(it) } 74 } 75 testBroadcastCancelledParentnull76 private suspend fun testBroadcastCancelledParent(start: CoroutineStart) { 77 try { 78 withContext(Job()) { 79 cancel() 80 expect(1) 81 val bc = broadcast<Int>(start = start) {} 82 expect(2) 83 (bc as Job).invokeOnCompletion { 84 finish(3) 85 reset() 86 } 87 } 88 expectUnreached() 89 } catch (e: CancellationException) { 90 // Expected 91 } 92 } 93 94 @Test <lambda>null95 fun testScopes() = runTest { 96 testScope { coroutineScope { } } 97 testScope { supervisorScope { } } 98 testScope { flowScope { } } 99 testScope { withTimeout(Long.MAX_VALUE) { } } 100 testScope { withContext(Job()) { } } 101 testScope { withContext(CoroutineName("")) { } } 102 } 103 testScopenull104 private suspend inline fun testScope(crossinline block: suspend () -> Unit) { 105 try { 106 withContext(Job()) { 107 cancel() 108 block() 109 } 110 expectUnreached() 111 } catch (e: CancellationException) { 112 // Expected 113 } 114 } 115 } 116