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.test.* 8 9 class WithTimeoutOrNullJvmTest : TestBase() { 10 @Test <lambda>null11 fun testOuterTimeoutFiredBeforeInner() = runTest { 12 val result = withTimeoutOrNull(100) { 13 Thread.sleep(200) // wait enough for outer timeout to fire 14 withContext(NonCancellable) { yield() } // give an event loop a chance to run and process that cancellation 15 withTimeoutOrNull(100) { 16 yield() // will cancel because of outer timeout 17 expectUnreached() 18 } 19 expectUnreached() // should not be reached, because it is outer timeout 20 } 21 // outer timeout results in null 22 assertNull(result) 23 } 24 25 @Test <lambda>null26 fun testIgnoredTimeout() = runTest { 27 val value = withTimeout(1) { 28 Thread.sleep(10) 29 42 30 } 31 32 assertEquals(42, value) 33 } 34 35 @Test <lambda>null36 fun testIgnoredTimeoutOnNull() = runTest { 37 val value = withTimeoutOrNull(1) { 38 Thread.sleep(10) 39 42 40 } 41 42 assertEquals(42, value) 43 } 44 45 @Test <lambda>null46 fun testIgnoredTimeoutOnNullThrowsCancellation() = runTest { 47 try { 48 withTimeoutOrNull(1) { 49 expect(1) 50 Thread.sleep(10) 51 throw CancellationException() 52 } 53 expectUnreached() 54 } catch (e: CancellationException) { 55 finish(2) 56 } 57 } 58 59 @Test <lambda>null60 fun testIgnoredTimeoutOnNullThrowsOnYield() = runTest { 61 val value = withTimeoutOrNull(1) { 62 Thread.sleep(10) 63 yield() 64 } 65 assertNull(value) 66 } 67 } 68