icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
//! Virtual time: the instants the harness hands out, how redraws are scheduled on them, and the
//! one place real time is used, the hang detector.

use std::sync::Arc;
use std::time::{Duration, Instant};

use iced_core::window;

pub use icedwright_types::{VirtualDuration, VirtualInstant};

use crate::config::{HangAfter, RealClock};
use crate::effects::UntypedTaskId;
use crate::error::{HangCause, HarnessError};

/// How far ahead of the real clock the virtual clock starts. Any instant before the virtual
/// epoch came from the real clock.
pub(crate) const EPOCH_OFFSET: Duration = Duration::from_secs(24 * 60 * 60);

/// Which clock an `iced::time::Instant` from app state came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Clock {
    /// The harness's virtual clock, at this instant.
    Virtual(VirtualInstant),
    /// The real clock, which a test cannot control.
    Real,
}

/// What the harness will do next on its own, if nothing else happens first.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WakeUp {
    /// When.
    pub at: VirtualInstant,
    /// What.
    pub kind: WakeKind,
}

/// The kind of a [`WakeUp`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum WakeKind {
    /// A frame on the frame boundary, for a window that asked for the next frame.
    Frame,
    /// A widget's redraw at a virtual instant, such as an animation step.
    WidgetTimer(window::Id),
}

/// A redraw a window asked for on the real clock, which the harness draws on the next frame
/// instead, and the pointer moves it made to keep a delayed tooltip shut.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct RealDeadline {
    /// Real-clock redraw requests seen, such as a caret blink.
    pub redraws: u32,
    /// Times the pointer was moved off a delayed tooltip's trigger.
    pub tooltip_leaves: u32,
}

pub use icedwright_check::Waited;

/// The virtual clock of one harness: tokio's paused clock, measured from the boot epoch.
#[derive(Debug, Clone, Copy)]
pub(crate) struct VirtualClock {
    epoch: tokio::time::Instant,
}

impl VirtualClock {
    pub(crate) fn new(epoch: tokio::time::Instant) -> Self {
        Self { epoch }
    }

    pub(crate) fn epoch(&self) -> tokio::time::Instant {
        self.epoch
    }

    /// The instant tokio's clock reads, which must be read inside the harness runtime.
    pub(crate) fn of(&self, instant: tokio::time::Instant) -> VirtualInstant {
        VirtualInstant::__from_offset(VirtualDuration::from(
            instant.saturating_duration_since(self.epoch),
        ))
    }

    pub(crate) fn to_tokio(self, instant: VirtualInstant) -> tokio::time::Instant {
        self.epoch + instant.since_boot().as_std()
    }

    pub(crate) fn to_iced(self, instant: VirtualInstant) -> Instant {
        self.to_tokio(instant).into_std()
    }

    pub(crate) fn classify(&self, instant: Instant) -> Clock {
        classify(self.epoch.into_std(), instant)
    }
}

/// Instants before the epoch are real; the rest are offsets into virtual time.
pub(crate) fn classify(epoch: Instant, instant: Instant) -> Clock {
    match instant.checked_duration_since(epoch) {
        Some(offset) => Clock::Virtual(VirtualInstant::__from_offset(offset.into())),
        None => Clock::Real,
    }
}

/// The first frame boundary, `epoch + n * interval`, strictly after `now`.
pub(crate) fn next_frame_boundary(
    now: VirtualInstant,
    interval: VirtualDuration,
) -> VirtualInstant {
    let step = interval.as_std().as_nanos().max(1);
    let elapsed = now.since_boot().as_std().as_nanos();
    let next = (elapsed / step + 1).saturating_mul(step);
    let nanos = u64::try_from(next).unwrap_or(u64::MAX);
    VirtualInstant::__from_offset(VirtualDuration::from_nanos(nanos))
}

/// What one window wants from the scheduler.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) struct WindowRedraw {
    /// It asked for the next frame, or a frame at the current instant was already drawn.
    pub(crate) frame: bool,
    /// It asked for a redraw at a virtual instant while handling its last redraw. Widgets ask
    /// again on every redraw for as long as they want one, so the next redraw replaces it.
    pub(crate) timer: Option<VirtualInstant>,
    /// It asked for a redraw at a virtual instant while handling input, kept until it falls
    /// due.
    pub(crate) input_timer: Option<VirtualInstant>,
    /// It asked for a redraw at a real-clock instant, which waits for the next frame.
    pub(crate) real: bool,
}

impl WindowRedraw {
    /// The earliest widget timer.
    pub(crate) fn next_timer(&self) -> Option<VirtualInstant> {
        match (self.timer, self.input_timer) {
            (Some(a), Some(b)) => Some(a.min(b)),
            (a, b) => a.or(b),
        }
    }

    /// What is left before the widgets handle a redraw at `now`: only input timers still to
    /// come. A redraw's own timer is dropped even if it has not fallen due, because a widget
    /// that stopped asking, such as a field that lost focus with its caret blink pending,
    /// would otherwise leave a timer whose instant came from iced's real clock.
    pub(crate) fn before_redraw(self, now: VirtualInstant) -> Self {
        Self {
            input_timer: self.input_timer.filter(|t| *t > now),
            ..Self::default()
        }
    }
}

/// The earliest thing the harness must do itself. A real-clock request never makes a wake-up
/// of its own: it rides on the next frame that something else asks for, and so does a widget
/// timer of a window that is waiting for a frame.
pub(crate) fn next_wake_up(
    now: VirtualInstant,
    interval: VirtualDuration,
    windows: &[(window::Id, WindowRedraw)],
) -> Option<WakeUp> {
    let frame = windows
        .iter()
        .any(|(_, redraw)| redraw.frame)
        .then(|| WakeUp {
            at: next_frame_boundary(now, interval),
            kind: WakeKind::Frame,
        });
    // A window waiting for a frame gets its widget timers on that frame: a timer between
    // frames, such as a caret blink whose phase comes from the real clock, would otherwise
    // split a step of anything that advances on every redraw, such as autoscroll.
    let timer = windows
        .iter()
        .filter(|(_, redraw)| !redraw.frame)
        .filter_map(|(id, redraw)| {
            redraw.next_timer().map(|at| WakeUp {
                at: at.max(now),
                kind: WakeKind::WidgetTimer(*id),
            })
        })
        .min_by_key(|wake| wake.at);
    match (frame, timer) {
        (Some(frame), Some(timer)) if timer.at < frame.at => Some(timer),
        (Some(frame), _) => Some(frame),
        (None, timer) => timer,
    }
}

/// Tells a hung process from a slow one: it fails only when nothing has progressed for the
/// whole window, measured on the injected real clock.
#[derive(Clone)]
pub(crate) struct HangDetector {
    after: HangAfter,
    clock: Arc<dyn RealClock>,
    last_progress: Instant,
}

impl std::fmt::Debug for HangDetector {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HangDetector")
            .field("after", &self.after)
            .finish_non_exhaustive()
    }
}

impl HangDetector {
    pub(crate) fn new(after: HangAfter, clock: Arc<dyn RealClock>) -> Self {
        let last_progress = clock.now();
        Self {
            after,
            clock,
            last_progress,
        }
    }

    pub(crate) fn window(&self) -> Option<Duration> {
        match self.after {
            HangAfter::After(window) => Some(window),
            HangAfter::Off => None,
        }
    }

    pub(crate) fn now(&self) -> Instant {
        self.clock.now()
    }

    /// Something finished: a task, a message, a frame or a blocking job.
    pub(crate) fn progress(&mut self) {
        self.last_progress = self.clock.now();
    }

    /// Fails if nothing has progressed for the whole window.
    pub(crate) fn check(
        &self,
        step: &str,
        cause: impl FnOnce() -> HangCause,
    ) -> Result<(), HarnessError> {
        let Some(window) = self.window() else {
            return Ok(());
        };
        let since = self
            .clock
            .now()
            .saturating_duration_since(self.last_progress);
        if since < window {
            return Ok(());
        }
        Err(HarnessError::Hung {
            step: step.to_owned(),
            since_progress: since,
            cause: cause(),
        })
    }

    /// Fails once a wait that began at `began` has run for the whole window, whatever
    /// happened since: the fixed ceiling on waits for declared external sources.
    pub(crate) fn check_ceiling(
        &self,
        step: &str,
        began: Instant,
        sources: &[String],
    ) -> Result<(), HarnessError> {
        let Some(window) = self.window() else {
            return Ok(());
        };
        let since = self.clock.now().saturating_duration_since(began);
        if since < window {
            return Ok(());
        }
        Err(HarnessError::Hung {
            step: step.to_owned(),
            since_progress: since,
            cause: HangCause::ExternalSources {
                sources: sources.to_vec(),
            },
        })
    }
}

/// The busiest tasks first, for `NeverIdle`.
pub(crate) fn busiest(polls: impl IntoIterator<Item = (UntypedTaskId, u64)>) -> Vec<UntypedTaskId> {
    let mut all: Vec<(UntypedTaskId, u64)> = polls.into_iter().collect();
    all.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
    all.into_iter().take(3).map(|(id, _)| id).collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::MockRealClock;
    use std::sync::Mutex;

    fn at(ms: u64) -> VirtualInstant {
        VirtualInstant::__from_offset(VirtualDuration::from_millis(ms))
    }

    const FRAME: VirtualDuration = VirtualDuration::from_micros(16_667);

    fn id() -> window::Id {
        window::Id::unique()
    }

    #[test]
    fn frame_boundaries_count_from_the_epoch() {
        assert_eq!(
            next_frame_boundary(at(0), FRAME),
            VirtualInstant::__from_offset(FRAME)
        );
        assert_eq!(
            next_frame_boundary(VirtualInstant::__from_offset(FRAME), FRAME),
            VirtualInstant::__from_offset(FRAME * 2)
        );
        assert_eq!(
            next_frame_boundary(at(20), FRAME),
            VirtualInstant::__from_offset(FRAME * 2)
        );
    }

    #[test]
    fn next_frame_lands_on_the_next_boundary() {
        let windows = [(
            id(),
            WindowRedraw {
                frame: true,
                ..WindowRedraw::default()
            },
        )];
        let wake = next_wake_up(at(5), FRAME, &windows);
        assert_eq!(
            wake,
            Some(WakeUp {
                at: VirtualInstant::__from_offset(FRAME),
                kind: WakeKind::Frame
            })
        );
    }

    #[test]
    fn a_virtual_timer_lands_at_its_instant() {
        let window = id();
        let windows = [(
            window,
            WindowRedraw {
                timer: Some(at(500)),
                ..WindowRedraw::default()
            },
        )];
        assert_eq!(
            next_wake_up(at(5), FRAME, &windows),
            Some(WakeUp {
                at: at(500),
                kind: WakeKind::WidgetTimer(window)
            })
        );
    }

    #[test]
    fn a_real_clock_request_makes_no_wake_up_of_its_own() {
        let windows = [(
            id(),
            WindowRedraw {
                real: true,
                ..WindowRedraw::default()
            },
        )];
        assert_eq!(next_wake_up(at(5), FRAME, &windows), None);
    }

    #[test]
    fn wait_contributes_nothing_and_the_minimum_wins() {
        let (a, b, c) = (id(), id(), id());
        let windows = [
            (a, WindowRedraw::default()),
            (
                b,
                WindowRedraw {
                    frame: true,
                    ..WindowRedraw::default()
                },
            ),
            (
                c,
                WindowRedraw {
                    timer: Some(at(3)),
                    input_timer: Some(at(4)),
                    ..WindowRedraw::default()
                },
            ),
        ];
        assert_eq!(
            next_wake_up(at(1), FRAME, &windows),
            Some(WakeUp {
                at: at(3),
                kind: WakeKind::WidgetTimer(c)
            })
        );
        assert_eq!(
            next_wake_up(at(1), FRAME, &[(a, WindowRedraw::default())]),
            None
        );
    }

    #[test]
    fn a_window_waiting_for_a_frame_gets_its_widget_timers_on_that_frame() {
        let window = id();
        let windows = [(
            window,
            WindowRedraw {
                frame: true,
                timer: Some(at(3)),
                input_timer: Some(at(4)),
                real: false,
            },
        )];
        assert_eq!(
            next_wake_up(at(1), FRAME, &windows),
            Some(WakeUp {
                at: VirtualInstant::__from_offset(FRAME),
                kind: WakeKind::Frame
            })
        );
    }

    #[test]
    fn a_redraw_drops_the_last_redraws_timer_and_keeps_input_timers_still_to_come() {
        let pending = WindowRedraw {
            frame: true,
            timer: Some(at(400)),
            input_timer: Some(at(300)),
            real: true,
        };
        assert_eq!(pending.next_timer(), Some(at(300)));
        assert_eq!(
            pending.before_redraw(at(17)),
            WindowRedraw {
                input_timer: Some(at(300)),
                ..WindowRedraw::default()
            }
        );
        assert_eq!(pending.before_redraw(at(300)), WindowRedraw::default());
    }

    #[test]
    fn instants_before_the_epoch_are_real() {
        let base = crate::config::SystemClock.now();
        let epoch = base + EPOCH_OFFSET;
        assert_eq!(classify(epoch, base), Clock::Real);
        assert_eq!(
            classify(epoch, epoch + Duration::from_millis(1250)),
            Clock::Virtual(at(1250))
        );
    }

    fn stepping_clock(step: Duration) -> Arc<dyn RealClock> {
        let start = crate::config::SystemClock.now();
        let ticks = Mutex::new(0u32);
        let mut clock = MockRealClock::new();
        clock.expect_now().returning(move || {
            let mut ticks = ticks.lock().unwrap();
            *ticks += 1;
            start + step * *ticks
        });
        Arc::new(clock)
    }

    #[test]
    fn steady_progress_for_600_seconds_never_hangs() {
        let mut detector = HangDetector::new(
            HangAfter::After(Duration::from_secs(120)),
            stepping_clock(Duration::from_secs(10)),
        );
        for _ in 0..30 {
            detector.progress();
            assert!(
                detector
                    .check("advance", || HangCause::AppCall { what: "update" })
                    .is_ok()
            );
        }
    }

    #[test]
    fn no_progress_for_the_window_hangs() {
        let detector = HangDetector::new(
            HangAfter::After(Duration::from_secs(120)),
            stepping_clock(Duration::from_secs(61)),
        );
        assert!(
            detector
                .check("settle", || HangCause::BlockingWork { job: None })
                .is_ok()
        );
        let error = detector
            .check("settle", || HangCause::BlockingWork { job: None })
            .unwrap_err();
        assert!(matches!(
            error,
            HarnessError::Hung {
                cause: HangCause::BlockingWork { .. },
                ..
            }
        ));
        assert!(error.to_string().contains("spawn_blocking"));
    }

    #[test]
    fn off_never_hangs() {
        let detector = HangDetector::new(HangAfter::Off, stepping_clock(Duration::from_secs(1000)));
        assert!(
            detector
                .check("settle", || HangCause::BlockingWork { job: None })
                .is_ok()
        );
    }

    #[test]
    fn the_ceiling_counts_from_the_start_of_the_wait_whatever_progresses() {
        let mut detector = HangDetector::new(
            HangAfter::After(Duration::from_secs(5)),
            stepping_clock(Duration::from_secs(1)),
        );
        let began = detector.now();
        let sources = vec!["leaky::ticker".to_owned()];
        let mut checks = 0;
        let error = loop {
            detector.progress();
            checks += 1;
            if let Err(error) = detector.check_ceiling("expect", began, &sources) {
                break error;
            }
        };
        assert_eq!(checks, 3);
        let HarnessError::Hung {
            since_progress,
            cause,
            ..
        } = error
        else {
            panic!("not a hang");
        };
        assert_eq!(since_progress, Duration::from_secs(6));
        assert_eq!(cause, HangCause::ExternalSources { sources });
    }

    #[test]
    fn busiest_sorts_by_polls() {
        let ids: Vec<UntypedTaskId> = (1..=4).map(UntypedTaskId::new).collect();
        let order = busiest([(ids[0], 3), (ids[1], 10), (ids[2], 3), (ids[3], 1)]);
        assert_eq!(order, vec![ids[1], ids[0], ids[2]]);
    }
}