1 /*
2  * Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
3  */
4 
5 package kotlinx.coroutines.test
6 
7 import kotlinx.coroutines.CoroutineDispatcher
8 import kotlinx.coroutines.ExperimentalCoroutinesApi
9 
10 /**
11  * Control the virtual clock time of a [CoroutineDispatcher].
12  *
13  * Testing libraries may expose this interface to tests instead of [TestCoroutineDispatcher].
14  */
15 @ExperimentalCoroutinesApi // Since 1.2.1, tentatively till 1.3.0
16 public interface DelayController {
17     /**
18      * Returns the current virtual clock-time as it is known to this Dispatcher.
19      *
20      * @return The virtual clock-time
21      */
22     @ExperimentalCoroutinesApi // Since 1.2.1, tentatively till 1.3.0
23     public val currentTime: Long
24 
25     /**
26      * Moves the Dispatcher's virtual clock forward by a specified amount of time.
27      *
28      * The amount the clock is progressed may be larger than the requested `delayTimeMillis` if the code under test uses
29      * blocking coroutines.
30      *
31      * The virtual clock time will advance once for each delay resumed until the next delay exceeds the requested
32      * `delayTimeMills`. In the following test, the virtual time will progress by 2_000 then 1 to resume three different
33      * calls to delay.
34      *
35      * ```
36      * @Test
37      * fun advanceTimeTest() = runBlockingTest {
38      *     foo()
39      *     advanceTimeBy(2_000)  // advanceTimeBy(2_000) will progress through the first two delays
40      *     // virtual time is 2_000, next resume is at 2_001
41      *     advanceTimeBy(2)      // progress through the last delay of 501 (note 500ms were already advanced)
42      *     // virtual time is 2_0002
43      * }
44      *
45      * fun CoroutineScope.foo() {
46      *     launch {
47      *         delay(1_000)    // advanceTimeBy(2_000) will progress through this delay (resume @ virtual time 1_000)
48      *         // virtual time is 1_000
49      *         delay(500)      // advanceTimeBy(2_000) will progress through this delay (resume @ virtual time 1_500)
50      *         // virtual time is 1_500
51      *         delay(501)      // advanceTimeBy(2_000) will not progress through this delay (resume @ virtual time 2_001)
52      *         // virtual time is 2_001
53      *     }
54      * }
55      * ```
56      *
57      * @param delayTimeMillis The amount of time to move the CoroutineContext's clock forward.
58      * @return The amount of delay-time that this Dispatcher's clock has been forwarded.
59      */
60     @ExperimentalCoroutinesApi // Since 1.2.1, tentatively till 1.3.0
advanceTimeBynull61     public fun advanceTimeBy(delayTimeMillis: Long): Long
62 
63     /**
64      * Immediately execute all pending tasks and advance the virtual clock-time to the last delay.
65      *
66      * If new tasks are scheduled due to advancing virtual time, they will be executed before `advanceUntilIdle`
67      * returns.
68      *
69      * @return the amount of delay-time that this Dispatcher's clock has been forwarded in milliseconds.
70      */
71     @ExperimentalCoroutinesApi // Since 1.2.1, tentatively till 1.3.0
72     public fun advanceUntilIdle(): Long
73 
74     /**
75      * Run any tasks that are pending at or before the current virtual clock-time.
76      *
77      * Calling this function will never advance the clock.
78      */
79     @ExperimentalCoroutinesApi // Since 1.2.1, tentatively till 1.3.0
80     public fun runCurrent()
81 
82     /**
83      * Call after test code completes to ensure that the dispatcher is properly cleaned up.
84      *
85      * @throws UncompletedCoroutinesError if any pending tasks are active, however it will not throw for suspended
86      * coroutines.
87      */
88     @ExperimentalCoroutinesApi // Since 1.2.1, tentatively till 1.3.0
89     @Throws(UncompletedCoroutinesError::class)
90     public fun cleanupTestCoroutines()
91 
92     /**
93      * Run a block of code in a paused dispatcher.
94      *
95      * By pausing the dispatcher any new coroutines will not execute immediately. After block executes, the dispatcher
96      * will resume auto-advancing.
97      *
98      * This is useful when testing functions that start a coroutine. By pausing the dispatcher assertions or
99      * setup may be done between the time the coroutine is created and started.
100      */
101     @ExperimentalCoroutinesApi // Since 1.2.1, tentatively till 1.3.0
102     public suspend fun pauseDispatcher(block: suspend () -> Unit)
103 
104     /**
105      * Pause the dispatcher.
106      *
107      * When paused, the dispatcher will not execute any coroutines automatically, and you must call [runCurrent] or
108      * [advanceTimeBy], or [advanceUntilIdle] to execute coroutines.
109      */
110     @ExperimentalCoroutinesApi // Since 1.2.1, tentatively till 1.3.0
111     public fun pauseDispatcher()
112 
113     /**
114      * Resume the dispatcher from a paused state.
115      *
116      * Resumed dispatchers will automatically progress through all coroutines scheduled at the current time. To advance
117      * time and execute coroutines scheduled in the future use, one of [advanceTimeBy],
118      * or [advanceUntilIdle].
119      */
120     @ExperimentalCoroutinesApi // Since 1.2.1, tentatively till 1.3.0
121     public fun resumeDispatcher()
122 }
123 
124 /**
125  * Thrown when a test has completed and there are tasks that are not completed or cancelled.
126  */
127 // todo: maybe convert into non-public class in 1.3.0 (need use-cases for a public exception type)
128 @ExperimentalCoroutinesApi // Since 1.2.1, tentatively till 1.3.0
129 public class UncompletedCoroutinesError(message: String, cause: Throwable? = null): AssertionError(message, cause)
130