summaryrefslogtreecommitdiffstats
path: root/tokio-test/src/clock.rs
blob: d2f29249182cd64e0394794567411440b30ea464 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
//! A mocked clock for use with `tokio::time` based futures.
//!
//! # Example
//!
//! ```
//! use tokio::time::{clock, delay};
//! use tokio_test::{assert_ready, assert_pending, task};
//!
//! use std::time::Duration;
//!
//! tokio_test::clock::mock(|handle| {
//!     let mut task = task::spawn(async {
//!         delay(clock::now() + Duration::from_secs(1)).await
//!     });
//!
//!     assert_pending!(task.poll());
//!
//!     handle.advance(Duration::from_secs(1));
//!
//!     assert_ready!(task.poll());
//! });
//! ```

use tokio::runtime::{Park, Unpark};
use tokio::time::clock::{Clock, Now};
use tokio::time::Timer;

use std::marker::PhantomData;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

/// Run the provided closure with a `MockClock` that starts at the current time.
pub fn mock<F, R>(f: F) -> R
where
    F: FnOnce(&mut Handle) -> R,
{
    let mut mock = MockClock::new();
    mock.enter(f)
}

/// Run the provided closure with a `MockClock` that starts at the provided `Instant`.
pub fn mock_at<F, R>(instant: Instant, f: F) -> R
where
    F: FnOnce(&mut Handle) -> R,
{
    let mut mock = MockClock::with_instant(instant);
    mock.enter(f)
}

/// Mock clock for use with `tokio-timer` futures.
///
/// A mock timer that is able to advance and wake after a
/// certain duration.
#[derive(Debug)]
pub struct MockClock {
    time: MockTime,
    clock: Clock,
}

/// A handle to the `MockClock`.
#[derive(Debug)]
pub struct Handle {
    timer: Timer<MockPark>,
    time: MockTime,
}

type Inner = Arc<Mutex<State>>;

#[derive(Debug, Clone)]
struct MockTime {
    inner: Inner,
    _pd: PhantomData<Rc<()>>,
}

#[derive(Debug)]
struct MockNow {
    inner: Inner,
}

#[derive(Debug)]
struct MockPark {
    inner: Inner,
    _pd: PhantomData<Rc<()>>,
}

#[derive(Debug)]
struct MockUnpark {
    inner: Inner,
}

#[derive(Debug)]
struct State {
    base: Instant,
    advance: Duration,
    unparked: bool,
    park_for: Option<Duration>,
}

impl MockClock {
    /// Create a new `MockClock` with the current time.
    pub fn new() -> Self {
        MockClock::with_instant(Instant::now())
    }

    /// Create a `MockClock` with its current time at a duration from now
    ///
    /// This will create a clock with `Instant::now() + duration` as the current time.
    pub fn with_duration(duration: Duration) -> Self {
        let instant = Instant::now() + duration;
        MockClock::with_instant(instant)
    }

    /// Create a `MockClock` that sets its current time as the `Instant` provided.
    pub fn with_instant(instant: Instant) -> Self {
        let time = MockTime::new(instant);
        let clock = Clock::new_with_now(time.mock_now());

        MockClock { time, clock }
    }

    /// Enter the `MockClock` context.
    pub fn enter<F, R>(&mut self, f: F) -> R
    where
        F: FnOnce(&mut Handle) -> R,
    {
        tokio::time::clock::with_default(&self.clock, || {
            let park = self.time.mock_park();
            let timer = Timer::new(park);
            let handle = timer.handle();
            let time = self.time.clone();

            let _timer = tokio::time::set_default(&handle);
            let mut handle = Handle::new(timer, time);
            f(&mut handle)
            // lazy(|| Ok::<_, ()>(f(&mut handle))).wait().unwrap()
        })
    }
}

impl Default for MockClock {
    fn default() -> Self {
        Self::new()
    }
}

impl Handle {
    pub(self) fn new(timer: Timer<MockPark>, time: MockTime) -> Self {
        Handle { timer, time }
    }

    /// Turn the internal timer and mock park for the provided duration.
    pub fn turn(&mut self) {
        self.timer.turn(None).unwrap();
    }

    /// Turn the internal timer and mock park for the provided duration.
    pub fn turn_for(&mut self, duration: Duration) {
        self.timer.turn(Some(duration)).unwrap();
    }

    /// Advance the `MockClock` by the provided duration.
    pub fn advance(&mut self, duration: Duration) {
        let inner = self.timer.get_park().inner.clone();
        let deadline = inner.lock().unwrap().now() + duration;

        while inner.lock().unwrap().now() < deadline {
            let dur = deadline - inner.lock().unwrap().now();
            self.turn_for(dur);
        }
    }

    /// Returns the total amount of time the time has been advanced.
    pub fn advanced(&self) -> Duration {
        self.time.inner.lock().unwrap().advance
    }

    /// Get the currently mocked time
    pub fn now(&mut self) -> Instant {
        self.time.now()
    }

    /// Turn the internal timer once, but force "parking" for `duration` regardless of any pending
    /// timeouts
    pub fn park_for(&mut self, duration: Duration) {
        self.time.inner.lock().unwrap().park_for = Some(duration);
        self.turn()
    }
}

impl MockTime {
    pub(crate) fn new(now: Instant) -> MockTime {
        let state = State {
            base: now,
            advance: Duration::default(),
            unparked: false,
            park_for: None,
        };

        MockTime {
            inner: Arc::new(Mutex::new(state)),
            _pd: PhantomData,
        }
    }

    pub(crate) fn mock_now(&self) -> MockNow {
        let inner = self.inner.clone();
        MockNow { inner }
    }

    pub(crate) fn mock_park(&self) -> MockPark {
        let inner = self.inner.clone();
        MockPark {
            inner,
            _pd: PhantomData,
        }
    }

    pub(crate) fn now(&self) -> Instant {
        self.inner.lock().unwrap().now()
    }
}

impl State {
    fn now(&self) -> Instant {
        self.base + self.advance
    }

    fn advance(&mut self, duration: Duration) {
        self.advance += duration;
    }
}

impl Park for MockPark {
    type Unpark = MockUnpark;
    type Error = ();

    fn unpark(&self) -> Self::Unpark {
        let inner = self.inner.clone();
        MockUnpark { inner }
    }

    fn park(&mut self) -> Result<(), Self::Error> {
        let mut inner = self.inner.lock().map_err(|_| ())?;

        let duration = inner.park_for.take().expect("call park_for first");

        inner.advance(duration);
        Ok(())
    }

    fn park_timeout(&mut self, duration: Duration) -> Result<(), Self::Error> {
        let mut inner = self.inner.lock().unwrap();

        if let Some(duration) = inner.park_for.take() {
            inner.advance(duration);
        } else {
            inner.advance(duration);
        }

        Ok(())
    }
}

impl Unpark for MockUnpark {
    fn unpark(&self) {
        if let Ok(mut inner) = self.inner.lock() {
            inner.unparked = true;
        }
    }
}

impl Now for MockNow {
    fn now(&self) -> Instant {
        self.inner.lock().unwrap().now()
    }
}