Skip to main content

hypersig_desktop/
testing.rs

1//! An [`Os`] a test scripts and reads, under the `testing` feature.
2//!
3//! ```
4//! use std::path::PathBuf;
5//!
6//! use hypersig_desktop::testing::{DialogKind, FakeOs};
7//!
8//! # tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(async {
9//! let fake = FakeOs::new();
10//! fake.answer_dialog([PathBuf::from("/notes/today.md")]);
11//! let os = fake.os();
12//!
13//! // A handler given `os` asks for a file and gets the one the test chose.
14//! assert_eq!(os.dialog().open_file().await, Some(PathBuf::from("/notes/today.md")));
15//! os.clipboard().write_text("copied").await.unwrap();
16//! assert_eq!(fake.clipboard_text().as_deref(), Some("copied"));
17//! assert_eq!(fake.dialogs()[0].kind, DialogKind::OpenFile);
18//! # });
19//! ```
20
21use std::collections::VecDeque;
22use std::ffi::OsString;
23use std::path::PathBuf;
24use std::sync::{Arc, Mutex, PoisonError};
25
26use hypersig::{SafeUrl, Url};
27
28use crate::os::Os;
29
30/// A fake system: the answers its dialogs give, and what the handlers did.
31#[derive(Debug, Clone, Default)]
32pub struct FakeOs {
33    fake: Arc<Mutex<Fake>>,
34}
35
36/// How the handlers arranged a window, as [`FakeOs::window`] returns it.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
38#[non_exhaustive]
39pub struct Arranged {
40    /// The placement [`Window::place`](crate::Window::place) gave last.
41    pub placement: crate::Placement,
42    /// The layer [`Window::layer`](crate::Window::layer) gave last.
43    pub layer: crate::Layer,
44    /// The corner [`Window::move_to`](crate::Window::move_to) gave last.
45    pub position: Option<(i32, i32)>,
46    /// The size [`Window::resize`](crate::Window::resize) gave last.
47    pub size: Option<(u32, u32)>,
48}
49
50impl Fake {
51    /// Records `change` to the open window at `index`.
52    pub(crate) fn arrange(&mut self, index: usize, change: crate::arrange::Arrange) {
53        use crate::arrange::Arrange;
54        if !self.windows.get(index).is_some_and(Option::is_some) {
55            return;
56        }
57        let arranged = self.arranged.entry(index).or_default();
58        match change {
59            Arrange::Place(placement) => arranged.placement = placement,
60            Arrange::Layer(layer) => arranged.layer = layer,
61            Arrange::Move(x, y) => arranged.position = Some((x, y)),
62            Arrange::Resize(width, height) => arranged.size = Some((width, height)),
63        }
64    }
65}
66
67/// What a [`FakeOs`] holds.
68#[derive(Debug)]
69pub(crate) struct Fake {
70    pub(crate) answers: VecDeque<Option<Vec<PathBuf>>>,
71    /// The buttons a test chose for the message boxes to come, in order.
72    pub(crate) choices: VecDeque<Choice>,
73    /// Each message box shown, in order.
74    pub(crate) messages: Vec<ShownMessage>,
75    pub(crate) dialogs: Vec<ShownDialog>,
76    pub(crate) clipboard: Option<String>,
77    /// Each window opened, in order, with `None` once it is closed.
78    pub(crate) windows: Vec<Option<Url>>,
79    /// The index in `windows` of the window opened or focused last.
80    pub(crate) focused: Option<usize>,
81    /// How the handlers arranged each window, by its index in `windows`.
82    pub(crate) arranged: std::collections::HashMap<usize, Arranged>,
83    pub(crate) external: Vec<SafeUrl>,
84    pub(crate) launches: tokio::sync::broadcast::Sender<crate::Launch>,
85    pub(crate) badge: u32,
86    /// Whether the handlers had the application start at login.
87    pub(crate) autostart: bool,
88    pub(crate) tray: Option<crate::Tray>,
89    /// The menus the handlers put in the menu bar last.
90    pub(crate) menus: Vec<crate::Menu>,
91    /// Each global shortcut registered, with where its presses go.
92    pub(crate) shortcuts:
93        std::collections::HashMap<crate::Shortcut, tokio::sync::broadcast::Sender<crate::Press>>,
94    /// Each notification shown, with where to say it was clicked.
95    pub(crate) notifications: Vec<(
96        crate::Notification,
97        Option<tokio::sync::oneshot::Sender<bool>>,
98    )>,
99}
100
101impl Default for Fake {
102    fn default() -> Self {
103        Self {
104            answers: VecDeque::new(),
105            choices: VecDeque::new(),
106            messages: Vec::new(),
107            dialogs: Vec::new(),
108            clipboard: None,
109            windows: Vec::new(),
110            focused: None,
111            arranged: std::collections::HashMap::new(),
112            external: Vec::new(),
113            launches: crate::handoff::channel(),
114            badge: 0,
115            autostart: false,
116            tray: None,
117            menus: Vec::new(),
118            shortcuts: std::collections::HashMap::new(),
119            notifications: Vec::new(),
120        }
121    }
122}
123
124impl Fake {
125    /// Records `message`, shown with an OK button only.
126    pub(crate) fn tell(&mut self, message: crate::Message) {
127        self.messages.push(ShownMessage {
128            kind: MessageKind::Tell,
129            message,
130        });
131    }
132
133    /// Records `message` and returns whether the test chose OK.
134    pub(crate) fn confirm(&mut self, message: crate::Message) -> bool {
135        match self.choice(MessageKind::Confirm, message) {
136            Choice::Ok => true,
137            Choice::Cancel => false,
138            other => panic!("a box of OK and Cancel was answered with Choice::{other:?}"),
139        }
140    }
141
142    /// Records `message` and returns the button the test chose.
143    pub(crate) fn ask(&mut self, message: crate::Message) -> crate::Answer {
144        match self.choice(MessageKind::Ask, message) {
145            Choice::Yes => crate::Answer::Yes,
146            Choice::No => crate::Answer::No,
147            Choice::Cancel => crate::Answer::Cancel,
148            Choice::Ok => panic!("a box of Yes, No, and Cancel was answered with Choice::Ok"),
149        }
150    }
151
152    /// Records `message` and takes the next choice the test gave.
153    ///
154    /// # Panics
155    ///
156    /// Panics when the test gave no choice for it.
157    fn choice(&mut self, kind: MessageKind, message: crate::Message) -> Choice {
158        let number = self.messages.len() + 1;
159        let choice = self.choices.pop_front().unwrap_or_else(|| {
160            panic!("message box {number} was shown, and the test chose no button for it with FakeOs::choose")
161        });
162        self.messages.push(ShownMessage { kind, message });
163        choice
164    }
165
166    /// Records `dialog` and returns the next answer a test gave for it.
167    ///
168    /// # Panics
169    ///
170    /// Panics when the test gave no answer for this dialog, which fails the
171    /// test rather than hiding a dialog it did not expect, and when a dialog
172    /// that chooses one path is answered with another number of paths.
173    pub(crate) fn answer_dialog(&mut self, dialog: ShownDialog) -> Option<Vec<PathBuf>> {
174        let number = self.dialogs.len() + 1;
175        let answer = self.answers.pop_front().unwrap_or_else(|| {
176            panic!(
177                "dialog {number} was shown, and the test gave FakeOs no answer for it with answer_dialog or cancel_dialog"
178            )
179        });
180        if let Some(paths) = &answer
181            && dialog.kind != DialogKind::OpenFiles
182            && paths.len() != 1
183        {
184            panic!(
185                "dialog {number} was shown with DialogKind::{:?}, which chooses one path, and the test answered it with {} paths",
186                dialog.kind,
187                paths.len()
188            );
189        }
190        self.dialogs.push(dialog);
191        answer
192    }
193}
194
195/// A dialog a handler showed, as [`FakeOs::dialogs`] returns it.
196#[derive(Debug, Clone, PartialEq, Eq)]
197#[non_exhaustive]
198pub struct ShownDialog {
199    /// The method that showed it.
200    pub kind: DialogKind,
201    /// The title [`Dialog::title`](crate::Dialog::title) gave.
202    pub title: Option<String>,
203    /// Each name and extensions [`Dialog::filter`](crate::Dialog::filter) gave, in order.
204    pub filters: Vec<(String, Vec<String>)>,
205    /// The directory [`Dialog::directory`](crate::Dialog::directory) gave.
206    pub directory: Option<PathBuf>,
207    /// The name [`Dialog::file_name`](crate::Dialog::file_name) gave.
208    pub file_name: Option<String>,
209}
210
211/// A message box a handler showed, as [`FakeOs::messages`] returns it.
212#[derive(Debug, Clone, PartialEq, Eq)]
213#[non_exhaustive]
214pub struct ShownMessage {
215    /// The method that showed it.
216    pub kind: MessageKind,
217    /// What it showed.
218    pub message: crate::Message,
219}
220
221/// Which method of `Os` showed a message box.
222#[derive(Debug, Clone, Copy, PartialEq, Eq)]
223#[non_exhaustive]
224pub enum MessageKind {
225    /// [`Os::tell`](crate::Os::tell), with an OK button.
226    Tell,
227    /// [`Os::confirm`](crate::Os::confirm), with OK and Cancel.
228    Confirm,
229    /// [`Os::ask`](crate::Os::ask), with Yes, No, and Cancel.
230    Ask,
231}
232
233/// The button a test chooses in a message box, with [`FakeOs::choose`].
234#[derive(Debug, Clone, Copy, PartialEq, Eq)]
235#[non_exhaustive]
236pub enum Choice {
237    /// OK, which [`Os::confirm`](crate::Os::confirm) shows.
238    Ok,
239    /// Yes, which [`Os::ask`](crate::Os::ask) shows.
240    Yes,
241    /// No, which [`Os::ask`](crate::Os::ask) shows.
242    No,
243    /// Cancel, which both show.
244    Cancel,
245}
246
247/// Which method of [`Dialog`](crate::Dialog) showed a dialog.
248#[derive(Debug, Clone, Copy, PartialEq, Eq)]
249#[non_exhaustive]
250pub enum DialogKind {
251    /// [`Dialog::open_file`](crate::Dialog::open_file).
252    OpenFile,
253    /// [`Dialog::open_files`](crate::Dialog::open_files).
254    OpenFiles,
255    /// [`Dialog::pick_folder`](crate::Dialog::pick_folder).
256    PickFolder,
257    /// [`Dialog::save_file`](crate::Dialog::save_file).
258    SaveFile,
259}
260
261impl FakeOs {
262    /// A fake system with no answers, no clipboard text, and no windows.
263    #[must_use]
264    pub fn new() -> Self {
265        Self::default()
266    }
267
268    /// The [`Os`] to give the application's handlers.
269    #[must_use]
270    pub fn os(&self) -> Os {
271        Os::fake(Arc::clone(&self.fake))
272    }
273
274    /// Makes the next dialog answer as if the person chose `paths`.
275    ///
276    /// Dialogs take the answers in the order they were given. A dialog
277    /// other than [`DialogKind::OpenFiles`] panics unless `paths` holds
278    /// exactly one path, since the person chooses one there.
279    pub fn answer_dialog(&self, paths: impl IntoIterator<Item = PathBuf>) {
280        self.lock()
281            .answers
282            .push_back(Some(paths.into_iter().collect()));
283    }
284
285    /// Makes the next message box that waits for a choice answer as if the
286    /// person chose `choice`. [`Os::tell`](crate::Os::tell) takes none.
287    ///
288    /// A box panics when its choice is not one of its buttons.
289    pub fn choose(&self, choice: Choice) {
290        self.lock().choices.push_back(choice);
291    }
292
293    /// The message boxes the handlers showed, in order.
294    #[must_use]
295    pub fn messages(&self) -> Vec<ShownMessage> {
296        self.lock().messages.clone()
297    }
298
299    /// Makes the next dialog answer as if the person cancelled it.
300    pub fn cancel_dialog(&self) {
301        self.lock().answers.push_back(None);
302    }
303
304    /// The dialogs the handlers have shown and the test answered, in order.
305    #[must_use]
306    pub fn dialogs(&self) -> Vec<ShownDialog> {
307        self.lock().dialogs.clone()
308    }
309
310    /// The text on the fake clipboard.
311    #[must_use]
312    pub fn clipboard_text(&self) -> Option<String> {
313        self.lock().clipboard.clone()
314    }
315
316    /// Puts `text` on the fake clipboard, as another program would.
317    pub fn set_clipboard_text(&self, text: impl Into<String>) {
318        self.lock().clipboard = Some(text.into());
319    }
320
321    /// The pages of the windows the handlers opened and have not closed.
322    #[must_use]
323    pub fn open_windows(&self) -> Vec<Url> {
324        self.lock().windows.iter().flatten().cloned().collect()
325    }
326
327    /// How the handlers arranged `window`, or `None` once it is closed.
328    #[must_use]
329    pub fn window(&self, window: &crate::Window) -> Option<Arranged> {
330        let fake = self.lock();
331        let index = window.fake_index()?;
332        fake.windows.get(index)?.as_ref()?;
333        Some(fake.arranged.get(&index).copied().unwrap_or_default())
334    }
335
336    /// The page of the window opened or focused last, while it is open.
337    #[must_use]
338    pub fn focused_window(&self) -> Option<Url> {
339        let fake = self.lock();
340        fake.windows.get(fake.focused?)?.clone()
341    }
342
343    /// An [`Updater`](crate::Updater) that finds no newer version and makes
344    /// no request, for the handlers' state in place of the one
345    /// [`App::run`](crate::App::run) gives.
346    #[cfg(feature = "updater")]
347    #[must_use]
348    pub fn updater(&self) -> crate::Updater {
349        crate::Updater::fake()
350    }
351
352    /// Hands `args`, started in `dir`, to the [`Launches`](crate::Launches)
353    /// taken from this fake's `Os`, as a second start of the application
354    /// would.
355    pub fn launch(&self, dir: impl Into<PathBuf>, args: impl IntoIterator<Item = OsString>) {
356        let launch = crate::Launch::new(dir.into(), args.into_iter().collect());
357        // With no `Launches` taken, nobody hears it, as in the application.
358        let _ = self.lock().launches.send(launch);
359    }
360
361    /// The count the handlers last put on the application's icon, 0 when
362    /// none is shown.
363    #[must_use]
364    pub fn badge(&self) -> u32 {
365        self.lock().badge
366    }
367
368    /// The notifications the handlers showed, in order.
369    #[must_use]
370    pub fn notifications(&self) -> Vec<crate::Notification> {
371        self.lock()
372            .notifications
373            .iter()
374            .map(|(shown, _)| shown.clone())
375            .collect()
376    }
377
378    /// Clicks the notification shown `index`th from 0, so its
379    /// [`Notified::clicked`](crate::Notified::clicked) returns `true`. A
380    /// notification the test does not click returns `false` once the
381    /// `FakeOs` and every `Os` from it are dropped.
382    ///
383    /// # Panics
384    ///
385    /// Panics when no notification was shown at `index`, or it was clicked
386    /// already.
387    pub fn click_notification(&self, index: usize) {
388        let mut fake = self.lock();
389        let clicked = fake
390            .notifications
391            .get_mut(index)
392            .and_then(|(_, clicked)| clicked.take())
393            .unwrap_or_else(|| panic!("no notification {index} is waiting to be clicked"));
394        let _ = clicked.send(true);
395    }
396
397    /// Whether the handlers registered `shortcut`.
398    #[must_use]
399    pub fn has_shortcut(&self, shortcut: crate::Shortcut) -> bool {
400        self.lock().shortcuts.contains_key(&shortcut)
401    }
402
403    /// Sends `press` of `shortcut`, as the person would, to every
404    /// [`Presses`](crate::Presses) of it.
405    ///
406    /// # Panics
407    ///
408    /// Panics when the handlers did not register `shortcut`.
409    pub fn press_shortcut(&self, shortcut: crate::Shortcut, press: crate::Press) {
410        let fake = self.lock();
411        let presses = fake
412            .shortcuts
413            .get(&shortcut)
414            .unwrap_or_else(|| panic!("no handler registered the shortcut {shortcut:?}"));
415        let _ = presses.send(press);
416    }
417
418    /// The tray the handlers showed last, if any.
419    #[must_use]
420    pub fn tray(&self) -> Option<crate::Tray> {
421        self.lock().tray.clone()
422    }
423
424    /// Clicks `item` in the tray's menu, as the person would.
425    ///
426    /// # Panics
427    ///
428    /// Panics when the tray shown, if any, has no such item.
429    pub fn click_tray_item(&self, item: &crate::TrayItem) {
430        let shown = self
431            .lock()
432            .tray
433            .as_ref()
434            .is_some_and(|tray| tray.items.iter().any(|shown| shown.id == item.id));
435        assert!(shown, "the tray shown has no item labeled {:?}", item.label);
436        let _ = item.clicked.send(());
437    }
438
439    /// The menus the handlers put in the menu bar last.
440    #[must_use]
441    pub fn menus(&self) -> Vec<crate::Menu> {
442        self.lock().menus.clone()
443    }
444
445    /// Clicks `item` in the menu bar, as the person would.
446    ///
447    /// # Panics
448    ///
449    /// Panics when no menu of the menu bar holds `item`.
450    pub fn click_menu_item(&self, item: &crate::MenuItem) {
451        let shown = self
452            .lock()
453            .menus
454            .iter()
455            .any(|menu| menu.items().any(|shown| shown.id == item.id));
456        assert!(
457            shown,
458            "no menu of the menu bar has an item labeled {:?}",
459            item.label
460        );
461        let _ = item.clicked.send(());
462    }
463
464    /// The URLs the handlers opened in another program.
465    #[must_use]
466    pub fn opened_externally(&self) -> Vec<SafeUrl> {
467        self.lock().external.clone()
468    }
469
470    fn lock(&self) -> std::sync::MutexGuard<'_, Fake> {
471        self.fake.lock().unwrap_or_else(PoisonError::into_inner)
472    }
473}
474
475#[cfg(test)]
476mod tests {
477    use std::path::PathBuf;
478
479    use axum::Router;
480    use hypersig::Route;
481
482    use super::{DialogKind, FakeOs, ShownDialog};
483
484    fn block_on<F: Future>(future: F) -> F::Output {
485        tokio::runtime::Builder::new_current_thread()
486            .build()
487            .unwrap_or_else(|error| panic!("no runtime: {error}"))
488            .block_on(future)
489    }
490
491    #[test]
492    fn a_dialog_is_recorded_with_its_kind_and_setup() {
493        let fake = FakeOs::new();
494        fake.answer_dialog([PathBuf::from("/notes/today.md")]);
495        let saved = block_on(
496            fake.os()
497                .dialog()
498                .title("Save the note")
499                .filter("Markdown", &["md"])
500                .directory("/notes")
501                .file_name("today.md")
502                .save_file(),
503        );
504        assert_eq!(saved, Some(PathBuf::from("/notes/today.md")));
505        assert_eq!(
506            fake.dialogs(),
507            [ShownDialog {
508                kind: DialogKind::SaveFile,
509                title: Some("Save the note".to_owned()),
510                filters: vec![("Markdown".to_owned(), vec!["md".to_owned()])],
511                directory: Some(PathBuf::from("/notes")),
512                file_name: Some("today.md".to_owned()),
513            }]
514        );
515    }
516
517    #[test]
518    fn open_files_takes_an_empty_answer() {
519        let fake = FakeOs::new();
520        fake.answer_dialog([]);
521        assert_eq!(block_on(fake.os().dialog().open_files()), Some(vec![]));
522    }
523
524    #[test]
525    #[should_panic(
526        expected = "dialog 1 was shown with DialogKind::OpenFile, which chooses one path, and the test answered it with 0 paths"
527    )]
528    fn a_dialog_of_one_path_refuses_an_empty_answer() {
529        let fake = FakeOs::new();
530        fake.answer_dialog([]);
531        let _ = block_on(fake.os().dialog().open_file());
532    }
533
534    #[test]
535    fn an_unanswered_dialog_is_not_recorded() {
536        let fake = FakeOs::new();
537        let os = fake.os();
538        let shown = std::thread::spawn(move || block_on(os.dialog().pick_folder())).join();
539        assert!(shown.is_err(), "the unanswered dialog panics");
540        assert_eq!(fake.dialogs(), []);
541    }
542
543    #[derive(hypersig::Signals, serde::Serialize, serde::Deserialize)]
544    struct NotePage {
545        id: u64,
546    }
547
548    hypersig::routes! {
549        fn pages(Router<()>);
550        const NOTE: Route<u64> = "/notes/{id}" => note;
551    }
552
553    async fn note((): (), id: u64) -> hypersig::Page<NotePage> {
554        hypersig::Page::new("Note", NotePage { id })
555    }
556
557    fn ok<T>(result: Result<T, crate::Error>) -> T {
558        result.unwrap_or_else(|error| panic!("{error}"))
559    }
560
561    #[test]
562    fn the_window_opened_or_focused_last_is_focused() {
563        let _ = pages(Router::new());
564        let fake = FakeOs::new();
565        let os = fake.os();
566        let first = ok(block_on(os.windows().open(&NOTE.url(1))));
567        let second = ok(block_on(os.windows().open(&NOTE.url(2))));
568        assert_eq!(fake.focused_window(), Some(NOTE.url(2)));
569        ok(first.focus());
570        assert_eq!(fake.focused_window(), Some(NOTE.url(1)));
571        ok(first.close());
572        assert_eq!(fake.focused_window(), None);
573        ok(second.focus());
574        ok(first.focus());
575        assert_eq!(fake.focused_window(), Some(NOTE.url(2)));
576    }
577
578    #[test]
579    fn the_badge_keeps_the_count_set_last() {
580        let fake = FakeOs::new();
581        assert_eq!(fake.badge(), 0);
582        ok(fake.os().badge(3));
583        ok(fake.os().badge(0));
584        ok(fake.os().badge(5));
585        assert_eq!(fake.badge(), 5);
586    }
587
588    #[test]
589    fn a_message_box_is_recorded_and_answered_by_the_test() {
590        use super::{Choice, MessageKind};
591        use crate::{Answer, Level, Message};
592        let fake = FakeOs::new();
593        let os = fake.os();
594        block_on(os.tell(Message::new(Level::Info, "Saved")));
595        fake.choose(Choice::Ok);
596        fake.choose(Choice::No);
597        assert!(block_on(os.confirm(Message::new(Level::Warning, "Quit?"))));
598        let answer = block_on(
599            os.ask(Message::new(Level::Warning, "Save?").body("Changes are lost otherwise.")),
600        );
601        assert_eq!(answer, Answer::No);
602        let kinds: Vec<_> = fake.messages().iter().map(|shown| shown.kind).collect();
603        assert_eq!(
604            kinds,
605            [MessageKind::Tell, MessageKind::Confirm, MessageKind::Ask]
606        );
607        assert_eq!(
608            fake.messages()[2].message.text(),
609            Some("Changes are lost otherwise.")
610        );
611    }
612
613    #[test]
614    fn a_window_is_found_focused_and_arranged() {
615        use crate::{Layer, Placement};
616        let fake = FakeOs::new();
617        let os = fake.os();
618        let window = ok(block_on(os.windows().open(&NOTE.url(1))));
619        let focused = ok(block_on(os.windows().focused())).expect("the window opened last");
620        assert_eq!(focused, window);
621        ok(window.place(Placement::Maximized));
622        ok(window.layer(Layer::AlwaysOnTop));
623        ok(window.move_to(10, -20));
624        ok(window.resize(800, 600));
625        let arranged = fake.window(&window).expect("the window is open");
626        assert_eq!(arranged.placement, Placement::Maximized);
627        assert_eq!(arranged.layer, Layer::AlwaysOnTop);
628        assert_eq!(arranged.position, Some((10, -20)));
629        assert_eq!(arranged.size, Some((800, 600)));
630        ok(window.close());
631        assert!(fake.window(&window).is_none());
632        assert!(ok(block_on(os.windows().focused())).is_none());
633    }
634
635    #[test]
636    fn a_menu_bar_is_recorded_and_its_item_clicked_by_the_test() {
637        use crate::{Menu, MenuItem};
638        let fake = FakeOs::new();
639        let open = MenuItem::new("Open");
640        let mut clicks = open.clicks();
641        ok(fake.os().menus([Menu::new("File").item(&open)]));
642        assert_eq!(fake.menus()[0].labels(), ["Open"]);
643        fake.click_menu_item(&open);
644        assert!(block_on(clicks.next()));
645    }
646
647    #[test]
648    fn the_start_at_login_is_kept_by_the_fake_system() {
649        let fake = FakeOs::new();
650        let os = fake.os();
651        assert!(!ok(block_on(os.autostart().is_enabled())));
652        ok(block_on(os.autostart().enable()));
653        assert!(ok(block_on(os.autostart().is_enabled())));
654        ok(block_on(os.autostart().disable()));
655        assert!(!ok(block_on(os.autostart().is_enabled())));
656    }
657
658    #[test]
659    fn a_shortcut_is_registered_and_pressed_by_the_test() {
660        use crate::{Key, Modifiers, Press, Shortcut};
661        const TALK: Shortcut = Shortcut::new(Modifiers::CONTROL, Key::Space);
662        let fake = FakeOs::new();
663        let os = fake.os();
664        assert!(!fake.has_shortcut(TALK));
665        let mut first = ok(block_on(os.shortcut(TALK)));
666        let mut second = ok(block_on(os.shortcut(TALK)));
667        assert!(fake.has_shortcut(TALK));
668        fake.press_shortcut(TALK, Press::Pressed);
669        fake.press_shortcut(TALK, Press::Released);
670        assert_eq!(block_on(first.next()), Some(Press::Pressed));
671        assert_eq!(block_on(first.next()), Some(Press::Released));
672        assert_eq!(block_on(second.next()), Some(Press::Pressed));
673    }
674
675    #[test]
676    fn a_notification_is_recorded_and_clicked_by_the_test() {
677        let fake = FakeOs::new();
678        let os = fake.os();
679        let (clicked, left) = block_on(async {
680            let first = ok(os
681                .notify(crate::Notification::new("Ada").body("Lunch?"))
682                .await);
683            let second = ok(os.notify(crate::Notification::new("Grace")).await);
684            fake.click_notification(0);
685            (first, second)
686        });
687        assert_eq!(fake.notifications()[0].title(), "Ada");
688        assert_eq!(fake.notifications()[0].text(), Some("Lunch?"));
689        assert_eq!(fake.notifications()[1].text(), None);
690        assert!(block_on(clicked.clicked()));
691        drop((fake, os));
692        assert!(!block_on(left.clicked()));
693    }
694}