Skip to main content

qframe/runtime/
harness.rs

1//! Driving an application in tests: no terminal, a fake clock and inline background work.
2
3use std::time::Duration;
4
5use ratatui_core::buffer::Buffer;
6use ratatui_core::layout::Rect as BufferRect;
7use ratatui_core::style::{Color, Modifier};
8
9use super::app::App;
10use super::detached::DetachedOutcome;
11use super::engine::{Engine, TaskMode};
12use super::handoff::{HandoffOutcome, HandoffRequest};
13use super::open::{OpenOutcome, OpenRequest};
14use super::termination::Termination;
15use crate::color::{ColorDepth, Rgb};
16use crate::env::Env;
17use crate::event::{Event, KeyEvent, MouseButton, MouseEvent, MouseKind};
18use crate::icons::GlyphMode;
19use crate::keymap::Modifiers;
20
21/// Time the fake clock moves before every simulated key press, so presses are never mistaken
22/// for a held key.
23const KEY_INTERVAL: Duration = Duration::from_millis(150);
24
25/// Runs an [`App`] against an in-memory screen.
26///
27/// Every input method renders afterwards, like the real runtime does. Work of
28/// [`Command::perform`](super::Command::perform) runs inline, one round per step like one pass of
29/// the terminal loop: work that performs again runs at the next step, so a chain of performs
30/// takes one [`Harness::render`] per link and an endless one never blocks a test.
31pub struct Harness<A: App> {
32    engine: Engine<A>,
33    buffer: Buffer,
34    now: Duration,
35}
36
37impl<A: App> Harness<A> {
38    /// A harness with the built-in environment and a `width` × `height` screen, already rendered.
39    ///
40    /// The first frame starts the application as the terminal runtime does: the size reaches
41    /// [`App::resized`], then [`App::init`] runs, so the focus it asks for is in place before the
42    /// first simulated key.
43    pub fn new(app: A, width: u16, height: u16) -> Self {
44        Self::with_env(app, Env::builtin(), width, height)
45    }
46
47    /// A harness with a custom environment.
48    pub fn with_env(app: A, env: Env, width: u16, height: u16) -> Self {
49        let mut harness = Self {
50            engine: Engine::new(app, env, TaskMode::Inline),
51            buffer: Buffer::empty(BufferRect::new(0, 0, width, height)),
52            now: Duration::ZERO,
53        };
54        harness.render();
55        harness
56    }
57
58    /// Paints the current view.
59    pub fn render(&mut self) -> &mut Self {
60        self.settle_tasks();
61        self.engine.render(&mut self.buffer, self.now);
62        // Settling hover or scrolling to a focused widget can ask for one more frame at once.
63        for _ in 0..3 {
64            let due = self.engine.deadline().is_some_and(|deadline| deadline <= self.now);
65            if !self.engine.dirty && !due {
66                break;
67            }
68            self.engine.render(&mut self.buffer, self.now);
69        }
70        self
71    }
72
73    /// Runs the perform work queued so far, then lets background tasks run up to the fake clock:
74    /// every task works until it sleeps past `now` or ends, and everything they sent is applied.
75    /// Tasks started by those messages settle too. Perform work queued meanwhile runs at the next
76    /// step, so work that performs again never keeps a step from ending.
77    fn settle_tasks(&mut self) {
78        self.engine.run_queued_work();
79        loop {
80            self.engine.task_clock.settle(self.now);
81            if self.engine.poll_tasks() == 0 {
82                break;
83            }
84        }
85    }
86
87    /// Delivers `message` to the application as if a widget had sent it, then renders.
88    pub fn send(&mut self, message: A::Msg) -> &mut Self {
89        self.engine.update(message);
90        self.render()
91    }
92
93    /// Presses a key chord such as `"ctrl+s"`, `"tab"` or `"?"`.
94    pub fn press(&mut self, chord: &str) -> &mut Self {
95        self.now += KEY_INTERVAL;
96        self.engine.handle(Event::Key(KeyEvent::press(chord)), self.now);
97        self.render()
98    }
99
100    /// Types `text` one character at a time.
101    pub fn type_text(&mut self, text: &str) -> &mut Self {
102        for c in text.chars() {
103            let chord = match c {
104                ' ' => "space".to_owned(),
105                '+' => "+".to_owned(),
106                c if c.is_uppercase() => format!("shift+{}", c.to_lowercase()),
107                c => c.to_string(),
108            };
109            self.press(&chord);
110        }
111        self
112    }
113
114    /// Delivers `events` in order at the current clock time and renders once afterwards, the
115    /// way the terminal loop handles every event waiting between two frames: several keys a fast
116    /// typist, a terminal multiplexer or a paste without bracketed paste sent in one read. Each
117    /// event meets what the ones before it did, as the view is rebuilt off screen between them,
118    /// so four keys typed into a controlled [`TextInput`](crate::widgets::TextInput) at once all
119    /// arrive.
120    pub fn events(&mut self, events: &[Event]) -> &mut Self {
121        for event in events {
122            self.engine.handle(event.clone(), self.now);
123        }
124        self.render()
125    }
126
127    /// Delivers `event` at an exact clock time, without moving the clock.
128    #[cfg(test)]
129    pub(crate) fn inject(&mut self, event: Event, at: Duration) -> &mut Self {
130        self.engine.handle(event, at);
131        self.render()
132    }
133
134    /// Pastes `text`.
135    pub fn paste(&mut self, text: &str) -> &mut Self {
136        self.engine.handle(Event::Paste(text.to_owned()), self.now);
137        self.render()
138    }
139
140    /// Clicks the left button on a cell.
141    pub fn click(&mut self, x: i32, y: i32) -> &mut Self {
142        self.mouse(MouseKind::Down(MouseButton::Left), x, y);
143        self.mouse(MouseKind::Up(MouseButton::Left), x, y)
144    }
145
146    /// Clicks the first cell of the first occurrence of `text` on screen.
147    ///
148    /// # Panics
149    ///
150    /// Panics when `text` is not on screen.
151    pub fn click_text(&mut self, text: &str) -> &mut Self {
152        let (x, y) = self.find(text).unwrap_or_else(|| panic!("`{text}` is not on screen:\n{}", self.screen()));
153        self.click(x, y)
154    }
155
156    /// Presses the left button on `from`, drags to `to` and releases there.
157    pub fn drag(&mut self, from: (i32, i32), to: (i32, i32)) -> &mut Self {
158        self.mouse(MouseKind::Down(MouseButton::Left), from.0, from.1);
159        self.mouse(MouseKind::Drag(MouseButton::Left), to.0, to.1);
160        self.mouse(MouseKind::Up(MouseButton::Left), to.0, to.1)
161    }
162
163    /// Moves the pointer to a cell.
164    pub fn hover(&mut self, x: i32, y: i32) -> &mut Self {
165        self.mouse(MouseKind::Moved, x, y)
166    }
167
168    /// Sends a mouse event.
169    pub fn mouse(&mut self, kind: MouseKind, x: i32, y: i32) -> &mut Self {
170        self.engine.handle(Event::Mouse(MouseEvent { kind, x, y, mods: Modifiers::default() }), self.now);
171        self.render()
172    }
173
174    /// Moves the fake clock forward and renders. Idleness moves with it: what
175    /// [`View::idle_for`](crate::widget::View::idle_for) reads grows by `duration`, and a
176    /// [`View::on_idle`](crate::widget::View::on_idle) watch whose silence is reached is told.
177    /// Every simulated input (a key, the mouse, a paste) starts the silence again; `send`,
178    /// `resize` and theme or language changes do not.
179    ///
180    /// A termination whose [`Termination::grace`] is over by then quits, as it does in the
181    /// runtime.
182    pub fn advance(&mut self, duration: Duration) -> &mut Self {
183        self.now += duration;
184        self.engine.tick(self.now);
185        self.engine.end_when_due(self.now);
186        self.render()
187    }
188
189    /// Simulates the signal behind `cause`, the way the terminal runtime hears a `SIGTERM` or a
190    /// `SIGHUP`, then renders. The application hears it through
191    /// [`App::terminating`](super::App::terminating) exactly as it would in a terminal, so a test
192    /// can check its answer:
193    ///
194    /// - An answer of `None` quits at once: [`Harness::quit_requested`] is true.
195    /// - A message is applied; the application stays until it quits or until
196    ///   [`Harness::advance`] moves the clock past [`Termination::grace`].
197    /// - Calling this again with [`Termination::Terminate`] quits, as a second signal does. A
198    ///   repeated [`Termination::Hangup`] changes nothing, and one during a pending terminate is
199    ///   told to the application again.
200    ///
201    /// The harness keeps drawing after a hangup, so a test can still read the screen; the
202    /// runtime stops drawing, since the terminal is gone.
203    ///
204    /// ```
205    /// use qframe::prelude::*;
206    /// use qframe::runtime::Termination;
207    ///
208    /// struct Editor;
209    ///
210    /// impl App for Editor {
211    ///     type Msg = ();
212    ///     fn update(&mut self, (): ()) -> Command<()> {
213    ///         Command::none()
214    ///     }
215    ///     fn view(&self, ui: &mut View<'_, ()>) {
216    ///         ui.add(Text::new("notes.md"));
217    ///     }
218    /// }
219    ///
220    /// // An application that implements nothing quits cleanly on either signal.
221    /// let mut app = Harness::new(Editor, 20, 3);
222    /// app.terminate(Termination::Terminate);
223    /// assert!(app.quit_requested());
224    /// ```
225    pub fn terminate(&mut self, cause: Termination) -> &mut Self {
226        self.engine.terminate(cause, self.now);
227        self.render()
228    }
229
230    /// Delivers a key event exactly as given, without moving the clock: a
231    /// [`KeyKind::Repeat`](crate::event::KeyKind::Repeat) or
232    /// [`KeyKind::Release`](crate::event::KeyKind::Release) from a terminal with the kitty
233    /// keyboard protocol, or a press repeated by a held key.
234    pub fn key(&mut self, event: KeyEvent) -> &mut Self {
235        self.engine.handle(Event::Key(event), self.now);
236        self.render()
237    }
238
239    /// Switches theme, as `Command::set_theme` would.
240    pub fn set_theme(&mut self, id: &str) -> &mut Self {
241        self.engine.env.set_theme(id);
242        self.render()
243    }
244
245    /// Switches language, as `Command::set_locale` would.
246    pub fn set_locale(&mut self, code: &str) -> &mut Self {
247        self.engine.env.set_locale(code);
248        self.render()
249    }
250
251    /// Sets the region, as `Command::set_region` would.
252    pub fn set_region(&mut self, region: Option<&str>) -> &mut Self {
253        self.engine.env.set_region(region);
254        self.render()
255    }
256
257    /// Turns reduced motion on or off.
258    pub fn set_reduced_motion(&mut self, reduced: bool) -> &mut Self {
259        self.engine.env.set_reduced_motion(reduced);
260        self.render()
261    }
262
263    /// Draws as a terminal with `depth` colours would. Cells then carry palette indices instead of
264    /// colours, which [`Harness::fg`] and [`Harness::bg`] cannot read; compare
265    /// [`Harness::buffer`] cells for those.
266    pub fn set_depth(&mut self, depth: ColorDepth) -> &mut Self {
267        self.engine.env.set_depth(depth);
268        self.render()
269    }
270
271    /// Switches the glyph column drawn.
272    pub fn set_glyph_mode(&mut self, mode: GlyphMode) -> &mut Self {
273        self.engine.env.set_glyph_mode(mode);
274        self.render()
275    }
276
277    /// Resizes the screen to `width` × `height` and renders, as a terminal resize does in the
278    /// runtime: the backend hands the engine a fresh, empty buffer of the new size and the next
279    /// frame is drawn in full. A new size reaches [`App::resized`] before that frame is built.
280    pub fn resize(&mut self, width: u16, height: u16) -> &mut Self {
281        self.buffer = Buffer::empty(BufferRect::new(0, 0, width, height));
282        self.engine.dirty = true;
283        self.render()
284    }
285
286    /// The screen as text, one line per row, trailing spaces removed. A double-width character
287    /// reads as itself, without the cell it covers, so `防火墙` is found as it is written.
288    #[must_use]
289    pub fn screen(&self) -> String {
290        let mut out = String::new();
291        for y in 0..self.buffer.area.height {
292            out.push_str(self.row(y).0.trim_end());
293            out.push('\n');
294        }
295        out
296    }
297
298    /// The screen as a self-contained HTML fragment with colours and weights, for looking at
299    /// renders in a browser. Wrap fragments with [`html_page`] to get a document.
300    #[must_use]
301    pub fn html(&self, caption: &str) -> String {
302        let area = self.buffer.area;
303        let escape = |text: &str| text.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;");
304        let css = |color: Color| rgb(color).map_or_else(|| "inherit".to_owned(), |c| c.to_string());
305        let mut out = format!("<figure><figcaption>{}</figcaption><div class=\"screen\">", escape(caption));
306        for y in 0..area.height {
307            out.push_str("<div class=\"row\">");
308            for x in visible_columns(&self.buffer, y) {
309                let cell = &self.buffer[(x, y)];
310                let modifier = cell.modifier;
311                let weight = if modifier.contains(Modifier::BOLD) { "font-weight:700;" } else { "" };
312                let style = if modifier.contains(Modifier::ITALIC) { "font-style:italic;" } else { "" };
313                let line = if modifier.contains(Modifier::UNDERLINED) { "text-decoration:underline;" } else { "" };
314                out.push_str(&format!(
315                    "<span style=\"color:{};background:{};width:{}ch;{weight}{style}{line}\">{}</span>",
316                    css(cell.fg),
317                    css(cell.bg),
318                    crate::text::width(cell.symbol()).max(1),
319                    escape(cell.symbol())
320                ));
321            }
322            out.push_str("</div>");
323        }
324        out.push_str("</div></figure>");
325        out
326    }
327
328    /// Screen position of the first occurrence of `text`, in cells; text after a double-width
329    /// character is found at the column it is drawn in.
330    #[must_use]
331    pub fn find(&self, text: &str) -> Option<(i32, i32)> {
332        (0..self.buffer.area.height).find_map(|y| {
333            let (line, columns) = self.row(y);
334            line.find(text).map(|byte| (i32::from(columns[byte]), i32::from(y)))
335        })
336    }
337
338    /// Row `y` of the screen as text, with the column each byte of that text was drawn in.
339    fn row(&self, y: u16) -> (String, Vec<u16>) {
340        let mut line = String::new();
341        let mut columns = Vec::new();
342        for x in visible_columns(&self.buffer, y) {
343            let symbol = self.buffer[(x, y)].symbol();
344            columns.extend(std::iter::repeat_n(x, symbol.len()));
345            line.push_str(symbol);
346        }
347        (line, columns)
348    }
349
350    /// Text colour of a cell.
351    ///
352    /// # Panics
353    ///
354    /// Panics when the cell is outside the screen.
355    #[must_use]
356    pub fn fg(&self, x: u16, y: u16) -> Option<Rgb> {
357        rgb(self.buffer[(x, y)].fg)
358    }
359
360    /// Background colour of a cell.
361    ///
362    /// # Panics
363    ///
364    /// Panics when the cell is outside the screen.
365    #[must_use]
366    pub fn bg(&self, x: u16, y: u16) -> Option<Rgb> {
367        rgb(self.buffer[(x, y)].bg)
368    }
369
370    /// Whether a cell is bold.
371    ///
372    /// # Panics
373    ///
374    /// Panics when the cell is outside the screen.
375    #[must_use]
376    pub fn is_bold(&self, x: u16, y: u16) -> bool {
377        self.buffer[(x, y)].modifier.contains(Modifier::BOLD)
378    }
379
380    /// The rendered buffer.
381    #[must_use]
382    pub fn buffer(&self) -> &Buffer {
383        &self.buffer
384    }
385
386    /// The application.
387    #[must_use]
388    pub fn app(&self) -> &A {
389        &self.engine.app
390    }
391
392    /// The environment.
393    #[must_use]
394    pub fn env(&self) -> &Env {
395        &self.engine.env
396    }
397
398    /// Texts copied to the clipboard so far.
399    #[must_use]
400    pub fn copied(&self) -> &[String] {
401        &self.engine.clipboard
402    }
403
404    /// The in-process clipboard: the text copied last, if any.
405    #[must_use]
406    pub fn clipboard(&self) -> Option<&str> {
407        self.engine.clipboard_text.as_deref()
408    }
409
410    /// Stands in for the system clipboard that pasting reads first: `Some` text as if the user
411    /// had copied it in another program, `None` for an empty clipboard (the start). A harness
412    /// never reads the real clipboard or asks a terminal, so without this pasting uses the text
413    /// the application copied last.
414    pub fn set_system_clipboard(&mut self, text: Option<&str>) -> &mut Self {
415        let system = super::clipboard::SystemClipboard::Fixed(text.map(str::to_owned));
416        self.engine.clipboard_reader.set_system(system);
417        self
418    }
419
420    /// The handoffs of [`Command::handoff`](super::Command::handoff) the application asked for,
421    /// oldest first. A harness has no terminal to hand over, so it records the request and
422    /// answers it with the outcome of [`Harness::set_handoff_outcome`] instead of running the
423    /// program.
424    #[must_use]
425    pub fn handoffs(&self) -> &[HandoffRequest] {
426        self.engine.handoff_requests()
427    }
428
429    /// The outcome every handoff from now on ends with; `Finished { code: Some(0) }` without
430    /// this.
431    pub fn set_handoff_outcome(&mut self, outcome: HandoffOutcome) -> &mut Self {
432        self.engine.set_handoff_outcome(outcome);
433        self
434    }
435
436    /// The handoffs of [`Command::handoff_detached`](super::Command::handoff_detached) the
437    /// application asked for, oldest first. Like [`Harness::handoffs`] they are recorded, not
438    /// run, and answered with the outcome of [`Harness::set_detached_outcome`].
439    #[must_use]
440    pub fn detached_handoffs(&self) -> &[HandoffRequest] {
441        self.engine.detached_requests()
442    }
443
444    /// The outcome every detached handoff from now on ends with; `Finished { code: Some(0) }`
445    /// without this. A [`DetachedOutcome::Detached`] with the child of
446    /// [`LiveChild::for_tests`](super::LiveChild::for_tests) lets the test play the program: what
447    /// the application writes is recorded on its [`TestChild`](super::TestChild), and the lines
448    /// the test says there reach [`DetachedHandoff::on_line`](super::DetachedHandoff::on_line)
449    /// at the next step.
450    ///
451    /// The harness keeps the outcome, and with it a clone of the child, until it is given
452    /// another or dropped; the child's input closes then at the latest, as it does when a real
453    /// run ends.
454    pub fn set_detached_outcome(&mut self, outcome: DetachedOutcome) -> &mut Self {
455        self.engine.set_detached_outcome(outcome);
456        self
457    }
458
459    /// The openings of [`Command::open`](super::Command::open) and
460    /// [`Command::open_with`](super::Command::open_with) the application asked for, oldest first.
461    ///
462    /// A harness reaches no desktop: the opening is recorded and answered with the outcome of
463    /// [`Harness::set_open_outcome`] instead of starting anything. [`OpenRequest::target`] is
464    /// what was asked to be opened, so a test reads the address without knowing which opener
465    /// this system has.
466    #[must_use]
467    pub fn opens(&self) -> &[OpenRequest] {
468        self.engine.open_requests()
469    }
470
471    /// The outcome every opening from now on ends with; [`OpenOutcome::Opened`] without this.
472    pub fn set_open_outcome(&mut self, outcome: OpenOutcome) -> &mut Self {
473        self.engine.set_open_outcome(outcome);
474        self
475    }
476
477    /// Whether the application asked to quit.
478    #[must_use]
479    pub fn quit_requested(&self) -> bool {
480        self.engine.quit
481    }
482
483    /// Whether the widget named `name` has keyboard focus.
484    #[must_use]
485    pub fn is_focused(&self, name: &str) -> bool {
486        self.engine.interaction.focused.is_some_and(|id| self.engine.frame.names.get(&id).is_some_and(|n| n == name))
487    }
488}
489
490/// Wraps [`Harness::html`] fragments in an HTML document that lays screens out on a dark page.
491#[must_use]
492pub fn html_page(fragments: &[String]) -> String {
493    format!(
494        "<!doctype html><meta charset=\"utf-8\"><title>Quvyta review</title><style>\
495         body{{background:#050507;margin:24px;font-family:'JetBrainsMono Nerd Font Mono','JetBrains Mono',monospace}}\
496         figure{{margin:0 0 28px}}figcaption{{color:#8a8f99;font:12px sans-serif;margin-bottom:6px}}\
497         .screen{{display:inline-block;font-size:14px;line-height:19px;white-space:pre}}\
498         .row{{display:flex;height:19px}}.row span{{display:inline-block;overflow:hidden}}</style>{}",
499        fragments.concat()
500    )
501}
502
503/// The columns of row `y` a terminal shows a symbol of: every one except those a wide
504/// character before them covers. Such a cell holds nothing or, when ratatui or a painter unaware
505/// of the character drew it, a space; reading it would split `防火墙` into `防 火 墙`.
506fn visible_columns(buffer: &Buffer, y: u16) -> impl Iterator<Item = u16> + '_ {
507    let mut covered = 0u16;
508    (0..buffer.area.width).filter(move |&x| {
509        if covered > 0 {
510            covered -= 1;
511            return false;
512        }
513        let symbol = buffer[(x, y)].symbol();
514        covered = crate::text::width(symbol).saturating_sub(1);
515        !symbol.is_empty()
516    })
517}
518
519fn rgb(color: Color) -> Option<Rgb> {
520    match color {
521        Color::Rgb(r, g, b) => Some(Rgb::new(r, g, b)),
522        _ => None,
523    }
524}
525
526#[cfg(test)]
527mod resize_tests {
528    use super::Harness;
529    use crate::runtime::{App, Command};
530    use crate::widget::View;
531    use crate::widgets::Text;
532
533    struct Greeting;
534
535    impl App for Greeting {
536        type Msg = ();
537        fn update(&mut self, (): ()) -> Command<()> {
538            Command::none()
539        }
540        fn view(&self, ui: &mut View<'_, ()>) {
541            ui.add(Text::new("container engines"));
542        }
543    }
544
545    #[test]
546    fn resize_redraws_the_whole_screen_at_the_new_size() {
547        let mut harness = Harness::new(Greeting, 30, 2);
548        assert_eq!(harness.screen(), "container engines\n\n");
549        harness.resize(9, 1);
550        assert_eq!(harness.screen(), "container\n");
551        harness.resize(0, 0);
552        assert_eq!(harness.screen(), "");
553        harness.resize(40, 3);
554        assert_eq!((harness.buffer().area.width, harness.buffer().area.height), (40, 3));
555        assert_eq!(harness.screen(), "container engines\n\n\n");
556    }
557}
558
559#[cfg(test)]
560mod handoff_tests {
561    use std::ffi::OsString;
562
563    use super::Harness;
564    use crate::runtime::{App, Command, Handoff, HandoffOutcome};
565    use crate::widget::View;
566    use crate::widgets::{Button, Text};
567
568    /// Asks for the authorization ticket and shows how the handoff ended.
569    #[derive(Default)]
570    struct Installer {
571        outcomes: Vec<HandoffOutcome>,
572    }
573
574    #[derive(Clone)]
575    enum Msg {
576        Authorize,
577        Done(HandoffOutcome),
578    }
579
580    impl App for Installer {
581        type Msg = Msg;
582        fn update(&mut self, msg: Msg) -> Command<Msg> {
583            match msg {
584                Msg::Authorize => Command::handoff(
585                    Handoff::new("sudo", Msg::Done).arg("-v").notice("Authorizing the installation").pause(false),
586                ),
587                Msg::Done(outcome) => {
588                    self.outcomes.push(outcome);
589                    Command::none()
590                }
591            }
592        }
593        fn view(&self, ui: &mut View<'_, Msg>) {
594            ui.add(Button::new("Authorize").on_press(Msg::Authorize)).id("authorize");
595            let text = match self.outcomes.last() {
596                None => "not asked yet".to_owned(),
597                Some(HandoffOutcome::Finished { code }) => format!("finished {code:?}"),
598                Some(HandoffOutcome::Failed(reason)) => format!("failed {reason}"),
599            };
600            ui.add(Text::new(text));
601        }
602    }
603
604    #[test]
605    fn a_handoff_is_recorded_and_answered_with_the_outcome_the_test_set() {
606        let mut harness = Harness::new(Installer::default(), 40, 3);
607        assert!(harness.handoffs().is_empty(), "nothing was asked for yet");
608        harness.send(Msg::Authorize);
609        let asked = harness.handoffs();
610        assert_eq!(asked.len(), 1);
611        assert_eq!(asked[0].program, OsString::from("sudo"));
612        assert_eq!(asked[0].args, vec![OsString::from("-v")]);
613        assert_eq!(asked[0].notice.as_deref(), Some("Authorizing the installation"));
614        assert!(!asked[0].pause);
615        // No program ran: the outcome the harness holds answered the request.
616        assert_eq!(harness.app().outcomes, [HandoffOutcome::Finished { code: Some(0) }]);
617        assert!(harness.screen().contains("finished Some(0)"), "{}", harness.screen());
618    }
619
620    #[test]
621    fn the_outcome_a_test_sets_reaches_the_application() {
622        let mut harness = Harness::new(Installer::default(), 40, 3);
623        harness.set_handoff_outcome(HandoffOutcome::Finished { code: Some(1) });
624        harness.send(Msg::Authorize);
625        assert_eq!(harness.app().outcomes, [HandoffOutcome::Finished { code: Some(1) }]);
626        harness.set_handoff_outcome(HandoffOutcome::Failed("sudo is not installed".to_owned()));
627        harness.send(Msg::Authorize);
628        assert_eq!(harness.app().outcomes.len(), 2);
629        assert!(harness.screen().contains("failed sudo is not installed"), "{}", harness.screen());
630        assert_eq!(harness.handoffs().len(), 2, "both requests are kept, oldest first");
631    }
632
633    #[test]
634    fn several_handoffs_are_answered_one_after_another() {
635        let mut harness = Harness::new(Installer::default(), 40, 3);
636        harness.send(Msg::Authorize).send(Msg::Authorize).send(Msg::Authorize);
637        assert_eq!(harness.handoffs().len(), 3);
638        assert_eq!(harness.app().outcomes.len(), 3);
639    }
640}
641
642#[cfg(test)]
643mod wide_text_tests {
644    use super::Harness;
645    use crate::runtime::{App, Command};
646    use crate::widget::View;
647    use crate::widgets::{Button, Text};
648
649    /// A Chinese status line and a button with a Chinese label that counts its presses.
650    #[derive(Default)]
651    struct Firewall {
652        presses: u32,
653    }
654
655    impl App for Firewall {
656        type Msg = ();
657        fn update(&mut self, (): ()) -> Command<()> {
658            self.presses += 1;
659            Command::none()
660        }
661        fn view(&self, ui: &mut View<'_, ()>) {
662            ui.add(Text::new("状态 防火墙 on"));
663            ui.add(Button::new("启用").on_press(()));
664        }
665    }
666
667    /// The screen as ratatui leaves it when it draws wide text itself: the cell each wide
668    /// character covers holds a space, as does a cell drawn by any painter that knows nothing of
669    /// the character before it.
670    fn with_covered_cells_as_spaces(harness: &mut Harness<Firewall>) {
671        let area = harness.buffer.area;
672        for y in 0..area.height {
673            let mut covered = 0;
674            for x in 0..area.width {
675                let cell = &mut harness.buffer[(x, y)];
676                if covered > 0 {
677                    covered -= 1;
678                    cell.reset();
679                    continue;
680                }
681                covered = crate::text::width(cell.symbol()).saturating_sub(1);
682            }
683        }
684    }
685
686    fn firewall() -> Harness<Firewall> {
687        let mut harness = Harness::new(Firewall::default(), 30, 3);
688        with_covered_cells_as_spaces(&mut harness);
689        harness
690    }
691
692    #[test]
693    fn the_screen_reads_wide_text_without_gaps() {
694        let harness = firewall();
695        let screen = harness.screen();
696        assert!(screen.starts_with("状态 防火墙 on\n"), "{screen}");
697        assert!(screen.contains("防火墙"), "{screen}");
698    }
699
700    #[test]
701    fn find_gives_the_column_a_wide_text_is_drawn_in() {
702        let harness = firewall();
703        assert_eq!(harness.find("防火墙"), Some((5, 0)));
704        assert_eq!(harness.find("on"), Some((12, 0)), "text after wide characters keeps its column");
705        let (x, y) = harness.find("启用").expect("the button label is on screen");
706        assert_eq!(harness.buffer()[(u16::try_from(x).unwrap(), u16::try_from(y).unwrap())].symbol(), "启");
707    }
708
709    #[test]
710    fn click_text_presses_a_wide_label() {
711        let mut harness = firewall();
712        harness.click_text("启用");
713        assert_eq!(harness.app().presses, 1);
714    }
715
716    #[test]
717    fn html_draws_a_wide_character_once() {
718        let harness = firewall();
719        let html = harness.html("wide");
720        let first_row = html.split("<div class=\"row\">").nth(1).expect("a first row");
721        assert_eq!(first_row.matches("<span").count(), 30 - 5, "five characters take two cells each: {first_row}");
722        assert!(first_row.contains(">防</span><span"), "{first_row}");
723    }
724}