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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
//! Expectations that are not about widgets: messages, tasks, the clipboard, windows and the
//! app's state. They retry through the same loop as widget expectations.

use std::collections::BTreeSet;
use std::fmt::{self, Debug};
use std::marker::PhantomData;
use std::panic::Location;

use iced_core::{theme, window};
use icedwright_check::assertion::{Evaluation, Outcome};
use icedwright_check::expectations::{self, Pattern, TaskView, WindowView};
use icedwright_check::retry_with;
use icedwright_locator::TextMatch;
use icedwright_probe::TaskName;
use icedwright_trace::StepKind;
use icedwright_types::VirtualDuration;

use super::{Settings, report, settle_soft};
use crate::effects::{Spawn, TaskState};
use crate::error::Result;
use crate::harness::{Harness, TestProgram};

/// A point in the message log, from [`Harness::mark`], after which `since` looks.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Mark {
    messages: usize,
}

/// A typed message pattern, built by [`message!`](crate::message).
#[must_use = "a message pattern does nothing until a matcher uses it"]
pub struct MessagePattern<M> {
    matches: Box<dyn Fn(&M) -> bool>,
    text: &'static str,
}

impl<M> MessagePattern<M> {
    /// A pattern from a predicate and the source text it prints as.
    pub fn new(matches: impl Fn(&M) -> bool + 'static, text: &'static str) -> Self {
        Self {
            matches: Box::new(matches),
            text,
        }
    }
}

impl<M> Pattern<M> for MessagePattern<M> {
    fn matches(&self, message: &M) -> bool {
        (self.matches)(message)
    }

    fn text(&self) -> &str {
        self.text
    }
}

impl<M> Debug for MessagePattern<M> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "message!({})", self.text)
    }
}

/// A [`MessagePattern`] from a pattern, with an optional guard that may capture locals:
/// `message!(Message::Opened(_))`, `message!(Message::Opened(id) if *id == wanted)`.
#[macro_export]
macro_rules! message {
    ($($pattern:pat_param)|+ $(if $guard:expr)? $(,)?) => {
        $crate::MessagePattern::new(
            move |message| ::core::matches!(message, $($pattern)|+ $(if $guard)?),
            ::core::stringify!($($pattern)|+ $(if $guard)?),
        )
    };
}

impl<P: TestProgram> Harness<P> {
    /// A point in the message log, for `expect_messages().since(mark)`.
    #[must_use]
    pub fn mark(&self) -> Mark {
        Mark {
            messages: self.messages.len(),
        }
    }

    /// Expectations about the messages `update` received.
    pub fn expect_messages(&mut self) -> MessagesExpect<'_, P> {
        MessagesExpect {
            harness: self,
            settings: Settings::default(),
            since: 0,
        }
    }

    /// Expectations about the fake clipboard.
    pub fn expect_clipboard(&mut self) -> ClipboardExpect<'_, P> {
        ClipboardExpect {
            harness: self,
            settings: Settings::default(),
        }
    }

    /// Expectations about the app's tasks.
    pub fn expect_tasks(&mut self) -> TasksExpect<'_, P> {
        TasksExpect {
            harness: self,
            settings: Settings::default(),
        }
    }

    /// Expectations about open windows; one window's are about the focused window unless
    /// `.window(id)` names another.
    pub fn expect_windows(&mut self) -> WindowsExpect<'_, P> {
        WindowsExpect {
            harness: self,
            settings: Settings::default(),
            window: None,
        }
    }

    /// Expectations about the app's state, read through a projection that keeps the received
    /// value printable: `ui.expect_state(|app| app.items.len()).to_equal(2)`.
    pub fn expect_state<T, F>(&mut self, project: F) -> StateExpect<'_, P, T, F>
    where
        T: Debug,
        F: for<'a> Fn(&'a P::State) -> T,
    {
        StateExpect {
            harness: self,
            settings: Settings::default(),
            project,
            value: PhantomData,
        }
    }
}

/// Runs one non-widget expectation through the retry loop, as a traced step.
#[track_caller]
fn run<P: TestProgram>(
    harness: &mut Harness<P>,
    settings: &Settings,
    subject: &str,
    matcher: &str,
    outcome: &mut dyn FnMut(&mut Harness<P>) -> Outcome,
) -> Result {
    let location = Location::caller();
    let negated = if settings.negated { "not()." } else { "" };
    let kind = StepKind::Action {
        action: format!("{subject}.{negated}{matcher}()"),
        locator: None,
        resolved: None,
        point: None,
    };
    let result = harness.step(
        || kind,
        |h| {
            let policy = settings.policy(h.default_timeout());
            let passed = retry_with(h, matcher, &policy, &mut |h: &mut Harness<P>| {
                Ok(Evaluation::from(outcome(h)))
            });
            let Err(error) = passed else {
                return Ok(());
            };
            let context = report::Context {
                subject: subject.to_owned(),
                location,
                message: settings.message.as_deref(),
                tree: None,
                window: None,
                soft: settings.soft,
            };
            Err(report::fail(h, error, &context))
        },
    );
    settle_soft(harness, settings.soft, result)
}

/// `.not()`, through [`std::ops::Not`] as on `Expect`.
macro_rules! negate {
    ($($ty:ty),+ $(,)?) => {
        $(
            impl<P: TestProgram> std::ops::Not for $ty {
                type Output = Self;

                fn not(mut self) -> Self {
                    self.settings.negated = !self.settings.negated;
                    self
                }
            }
        )+
    };
}

negate!(
    MessagesExpect<'_, P>,
    TasksExpect<'_, P>,
    ClipboardExpect<'_, P>,
    WindowsExpect<'_, P>
);

impl<P: TestProgram, T, F> std::ops::Not for StateExpect<'_, P, T, F> {
    type Output = Self;

    fn not(mut self) -> Self {
        self.settings.negated = !self.settings.negated;
        self
    }
}

macro_rules! shared_options {
    () => {
        /// How long to retry, in virtual time.
        pub fn timeout(mut self, timeout: impl Into<VirtualDuration>) -> Self {
            self.settings.timeout = Some(timeout.into());
            self
        }

        /// Shown above the failure.
        pub fn message(mut self, context: impl Into<String>) -> Self {
            self.settings.message = Some(context.into());
            self
        }

        /// Once it holds, it must keep holding for this long.
        pub fn during(mut self, window: impl Into<VirtualDuration>) -> Self {
            self.settings.during = Some(window.into());
            self
        }
    };
}

/// Expectations about the message log.
#[must_use = "an expectation does nothing until a matcher is called and its result is used"]
pub struct MessagesExpect<'h, P: TestProgram> {
    harness: &'h mut Harness<P>,
    settings: Settings,
    since: usize,
}

impl<P: TestProgram> Debug for MessagesExpect<'_, P> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MessagesExpect")
            .field("settings", &self.settings)
            .field("since", &self.since)
            .finish_non_exhaustive()
    }
}

impl<'h, P: TestProgram> MessagesExpect<'h, P> {
    shared_options!();

    /// Only messages after `mark`.
    pub fn since(mut self, mark: Mark) -> Self {
        self.since = mark.messages;
        self
    }

    /// The same matchers, recording a failure instead of returning it.
    pub fn soft(mut self) -> SoftMessages<'h, P> {
        self.settings.soft = true;
        SoftMessages(self)
    }

    #[track_caller]
    fn check(self, matcher: &str, judge: &dyn Fn(&[&P::Message]) -> Outcome) -> Result {
        let since = self.since;
        run(
            self.harness,
            &self.settings,
            "ui.expect_messages()",
            matcher,
            &mut |h: &mut Harness<P>| {
                let log: Vec<&P::Message> = h
                    .messages
                    .get(since..)
                    .unwrap_or_default()
                    .iter()
                    .map(|record| &record.message)
                    .collect();
                judge(&log)
            },
        )
    }

    /// A message equal to this one arrived.
    #[track_caller]
    pub fn to_contain(self, message: P::Message) -> Result
    where
        P::Message: PartialEq,
    {
        self.check("to_contain", &|log| {
            expectations::contains(log.iter().copied(), &message)
        })
    }

    /// A message matching the pattern arrived.
    #[track_caller]
    pub fn to_match(self, pattern: MessagePattern<P::Message>) -> Result {
        self.check("to_match", &|log| {
            expectations::matching(log.iter().copied(), &pattern)
        })
    }

    /// Exactly `count` messages match the pattern.
    #[track_caller]
    pub fn to_match_count(self, pattern: MessagePattern<P::Message>, count: usize) -> Result {
        self.check("to_match_count", &|log| {
            expectations::match_count(log.iter().copied(), &pattern, count)
        })
    }

    /// Messages matching each pattern arrived in this order.
    #[track_caller]
    pub fn to_match_in_order(
        self,
        patterns: impl IntoIterator<Item = MessagePattern<P::Message>>,
    ) -> Result {
        let patterns: Vec<MessagePattern<P::Message>> = patterns.into_iter().collect();
        self.check("to_match_in_order", &|log| {
            let refs: Vec<&dyn Pattern<P::Message>> = patterns
                .iter()
                .map(|p| p as &dyn Pattern<P::Message>)
                .collect();
            expectations::in_order(log.iter().copied(), &refs)
        })
    }

    /// No message arrived.
    #[track_caller]
    pub fn to_be_empty(self) -> Result {
        self.check("to_be_empty", &|log| {
            expectations::no_messages(log.iter().copied())
        })
    }
}

/// [`MessagesExpect`] recording failures on the harness.
#[must_use = "a soft expectation does nothing until a matcher is called"]
pub struct SoftMessages<'h, P: TestProgram>(MessagesExpect<'h, P>);

impl<P: TestProgram> Debug for SoftMessages<'_, P> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("SoftMessages").field(&self.0).finish()
    }
}

impl<P: TestProgram> SoftMessages<'_, P> {
    /// [`MessagesExpect::to_contain`], recorded.
    #[track_caller]
    pub fn to_contain(self, message: P::Message) -> Result
    where
        P::Message: PartialEq,
    {
        self.0.to_contain(message)
    }

    /// [`MessagesExpect::to_match`], recorded.
    #[track_caller]
    pub fn to_match(self, pattern: MessagePattern<P::Message>) -> Result {
        self.0.to_match(pattern)
    }

    /// [`MessagesExpect::to_match_count`], recorded.
    #[track_caller]
    pub fn to_match_count(self, pattern: MessagePattern<P::Message>, count: usize) -> Result {
        self.0.to_match_count(pattern, count)
    }

    /// [`MessagesExpect::to_match_in_order`], recorded.
    #[track_caller]
    pub fn to_match_in_order(
        self,
        patterns: impl IntoIterator<Item = MessagePattern<P::Message>>,
    ) -> Result {
        self.0.to_match_in_order(patterns)
    }

    /// [`MessagesExpect::to_be_empty`], recorded.
    #[track_caller]
    pub fn to_be_empty(self) -> Result {
        self.0.to_be_empty()
    }
}

/// Expectations about the app's tasks. Held tasks count as idle, since only the test can
/// release them.
#[must_use = "an expectation does nothing until a matcher is called and its result is used"]
pub struct TasksExpect<'h, P: TestProgram> {
    harness: &'h mut Harness<P>,
    settings: Settings,
}

impl<P: TestProgram> Debug for TasksExpect<'_, P> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TasksExpect")
            .field("settings", &self.settings)
            .finish_non_exhaustive()
    }
}

/// The tasks in flight as task expectations see them: named tasks by name, unnamed ones that
/// do not just carry a named task, and no subscriptions.
fn in_flight<P: TestProgram>(h: &Harness<P>) -> Vec<(String, bool)> {
    let infos = h.task_infos();
    let live = |state: TaskState| matches!(state, TaskState::Pending | TaskState::Held);
    let carriers: BTreeSet<_> = infos
        .iter()
        .filter(|info| info.name().is_some() && live(info.state()))
        .filter_map(crate::effects::TaskInfo::parent)
        .collect();
    infos
        .iter()
        .filter(|info| live(info.state()))
        .filter(|info| *info.spawn() != Spawn::Subscription)
        .filter(|info| info.name().is_some() || !carriers.contains(&info.id()))
        .map(|info| {
            let name = info
                .name()
                .map_or_else(|| format!("unnamed task {}", info.id()), str::to_owned);
            (name, info.state() == TaskState::Held)
        })
        .collect()
}

impl<P: TestProgram> TasksExpect<'_, P> {
    shared_options!();

    #[track_caller]
    fn check(self, matcher: &str, judge: &dyn Fn(&[TaskView<'_>]) -> Outcome) -> Result {
        run(
            self.harness,
            &self.settings,
            "ui.expect_tasks()",
            matcher,
            &mut |h: &mut Harness<P>| {
                let tasks = in_flight(h);
                let views: Vec<TaskView<'_>> = tasks
                    .iter()
                    .map(|(name, held)| TaskView { name, held: *held })
                    .collect();
                judge(&views)
            },
        )
    }

    /// No task is running; held tasks count as idle.
    #[track_caller]
    pub fn to_be_idle(self) -> Result {
        self.check("to_be_idle", &expectations::tasks_idle)
    }

    /// A task with this name is in flight, held or not.
    #[track_caller]
    pub fn to_have_pending<T: TaskName>(self) -> Result {
        self.check("to_have_pending", &|tasks| {
            expectations::task_pending(tasks, T::NAME)
        })
    }

    /// A task with this name is held.
    #[track_caller]
    pub fn to_have_held<T: TaskName>(self) -> Result {
        self.check("to_have_held", &|tasks| {
            expectations::task_held(tasks, T::NAME)
        })
    }

    /// This many tasks are in flight.
    #[track_caller]
    pub fn to_have_pending_count(self, count: usize) -> Result {
        self.check("to_have_pending_count", &|tasks| {
            expectations::task_count(tasks, count)
        })
    }
}

/// Expectations about the fake clipboard.
#[must_use = "an expectation does nothing until a matcher is called and its result is used"]
pub struct ClipboardExpect<'h, P: TestProgram> {
    harness: &'h mut Harness<P>,
    settings: Settings,
}

impl<P: TestProgram> Debug for ClipboardExpect<'_, P> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ClipboardExpect")
            .field("settings", &self.settings)
            .finish_non_exhaustive()
    }
}

impl<P: TestProgram> ClipboardExpect<'_, P> {
    shared_options!();

    #[track_caller]
    fn check(self, matcher: &str, judge: &dyn Fn(&crate::FakeClipboard) -> Outcome) -> Result {
        run(
            self.harness,
            &self.settings,
            "ui.expect_clipboard()",
            matcher,
            &mut |h: &mut Harness<P>| judge(&h.clipboard),
        )
    }

    /// The standard clipboard holds matching text.
    #[track_caller]
    pub fn to_have_text(self, text: impl Into<TextMatch>) -> Result {
        let text = text.into();
        self.check("to_have_text", &|clipboard| {
            expectations::clipboard_text(clipboard.text(), &text)
        })
    }

    /// The primary selection holds matching text.
    #[track_caller]
    pub fn to_have_primary_text(self, text: impl Into<TextMatch>) -> Result {
        let text = text.into();
        self.check("to_have_primary_text", &|clipboard| {
            expectations::clipboard_text(clipboard.primary(), &text)
        })
    }

    /// The standard clipboard is empty.
    #[track_caller]
    pub fn to_be_empty(self) -> Result {
        self.check("to_be_empty", &|clipboard| {
            expectations::clipboard_empty(clipboard.text())
        })
    }
}

/// Expectations about open windows.
#[must_use = "an expectation does nothing until a matcher is called and its result is used"]
pub struct WindowsExpect<'h, P: TestProgram> {
    harness: &'h mut Harness<P>,
    settings: Settings,
    window: Option<window::Id>,
}

impl<P: TestProgram> Debug for WindowsExpect<'_, P> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("WindowsExpect")
            .field("settings", &self.settings)
            .field("window", &self.window)
            .finish_non_exhaustive()
    }
}

impl<P: TestProgram> WindowsExpect<'_, P> {
    shared_options!();

    /// The window one-window matchers look at, instead of the focused one.
    pub fn window(mut self, id: window::Id) -> Self {
        self.window = Some(id);
        self
    }

    #[track_caller]
    fn check(
        self,
        matcher: &str,
        judge: &dyn Fn(usize, Option<&WindowView<'_, theme::Mode>>) -> Outcome,
    ) -> Result {
        let chosen = self.window;
        run(
            self.harness,
            &self.settings,
            "ui.expect_windows()",
            matcher,
            &mut |h: &mut Harness<P>| {
                let id = chosen.or_else(|| h.focused());
                let info = id.and_then(|id| h.window_info(id).ok());
                let view = info.map(|info| WindowView {
                    title: &info.title,
                    theme_mode: info.theme_mode,
                });
                judge(h.windows().len(), view.as_ref())
            },
        )
    }

    /// This many windows are open.
    #[track_caller]
    pub fn to_have_count(self, count: usize) -> Result {
        self.check("to_have_count", &|open, _| {
            expectations::window_count(open, count)
        })
    }

    /// The window's title matches.
    #[track_caller]
    pub fn to_have_title(self, title: impl Into<TextMatch>) -> Result {
        let title = title.into();
        self.check("to_have_title", &|_, window| {
            expectations::window_title(window, &title)
        })
    }

    /// The window's theme resolves to this mode.
    #[track_caller]
    pub fn to_have_theme_mode(self, mode: theme::Mode) -> Result {
        self.check("to_have_theme_mode", &|_, window| {
            expectations::window_theme(window, &mode)
        })
    }
}

/// Expectations about the app's state through a projection.
#[must_use = "an expectation does nothing until a matcher is called and its result is used"]
pub struct StateExpect<'h, P: TestProgram, T, F> {
    harness: &'h mut Harness<P>,
    settings: Settings,
    project: F,
    value: PhantomData<fn() -> T>,
}

impl<P: TestProgram, T, F> Debug for StateExpect<'_, P, T, F> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("StateExpect")
            .field("settings", &self.settings)
            .finish_non_exhaustive()
    }
}

impl<P: TestProgram, T: Debug, F: for<'a> Fn(&'a P::State) -> T> StateExpect<'_, P, T, F> {
    shared_options!();

    /// The projected value equals `expected`.
    #[track_caller]
    pub fn to_equal(self, expected: T) -> Result
    where
        T: PartialEq,
    {
        let project = &self.project;
        run(
            self.harness,
            &self.settings,
            "ui.expect_state(..)",
            "to_equal",
            &mut |h: &mut Harness<P>| expectations::state_equal(&project(&h.state), &expected),
        )
    }

    /// The projected value satisfies `check`.
    #[track_caller]
    pub fn to_satisfy<G>(self, check: G) -> Result
    where
        G: for<'a> Fn(&'a T) -> bool,
    {
        let project = &self.project;
        run(
            self.harness,
            &self.settings,
            "ui.expect_state(..)",
            "to_satisfy",
            &mut |h: &mut Harness<P>| {
                let value = project(&h.state);
                let holds = check(&value);
                expectations::state_satisfies(&value, holds)
            },
        )
    }
}