iced_test/
lib.rs

1//! Test your `iced` applications in headless mode.
2//!
3//! # Basic Usage
4//! Let's assume we want to test [the classical counter interface].
5//!
6//! First, we will want to create a [`Simulator`] of our interface:
7//!
8//! ```rust,no_run
9//! # struct Counter { value: i64 }
10//! # impl Counter {
11//! #    pub fn view(&self) -> iced_runtime::core::Element<(), iced_runtime::core::Theme, iced_renderer::Renderer> { unimplemented!() }
12//! # }
13//! use iced_test::simulator;
14//!
15//! let mut counter = Counter { value: 0 };
16//! let mut ui = simulator(counter.view());
17//! ```
18//!
19//! Now we can simulate a user interacting with our interface. Let's use [`Simulator::click`] to click
20//! the counter buttons:
21//!
22//! ```rust,no_run
23//! # struct Counter { value: i64 }
24//! # impl Counter {
25//! #    pub fn view(&self) -> iced_runtime::core::Element<(), iced_runtime::core::Theme, iced_renderer::Renderer> { unimplemented!() }
26//! # }
27//! # use iced_test::simulator;
28//! #
29//! # let mut counter = Counter { value: 0 };
30//! # let mut ui = simulator(counter.view());
31//! #
32//! let _ = ui.click("+");
33//! let _ = ui.click("+");
34//! let _ = ui.click("-");
35//! ```
36//!
37//! [`Simulator::click`] takes a type implementing the [`Selector`] trait. A [`Selector`] describes a way to query the widgets of an interface.
38//! In this case, we leverage the [`Selector`] implementation of `&str`, which selects a widget by the text it contains.
39//!
40//! We can now process any messages produced by these interactions and then assert that the final value of our counter is
41//! indeed `1`!
42//!
43//! ```rust,no_run
44//! # struct Counter { value: i64 }
45//! # impl Counter {
46//! #    pub fn update(&mut self, message: ()) {}
47//! #    pub fn view(&self) -> iced_runtime::core::Element<(), iced_runtime::core::Theme, iced_renderer::Renderer> { unimplemented!() }
48//! # }
49//! # use iced_test::simulator;
50//! #
51//! # let mut counter = Counter { value: 0 };
52//! # let mut ui = simulator(counter.view());
53//! #
54//! # let _ = ui.click("+");
55//! # let _ = ui.click("+");
56//! # let _ = ui.click("-");
57//! #
58//! for message in ui.into_messages() {
59//!     counter.update(message);
60//! }
61//!
62//! assert_eq!(counter.value, 1);
63//! ```
64//!
65//! We can even rebuild the interface to make sure the counter _displays_ the proper value with [`Simulator::find`]:
66//!
67//! ```rust,no_run
68//! # struct Counter { value: i64 }
69//! # impl Counter {
70//! #    pub fn view(&self) -> iced_runtime::core::Element<(), iced_runtime::core::Theme, iced_renderer::Renderer> { unimplemented!() }
71//! # }
72//! # use iced_test::simulator;
73//! #
74//! # let mut counter = Counter { value: 0 };
75//! let mut ui = simulator(counter.view());
76//!
77//! assert!(ui.find("1").is_ok(), "Counter should display 1!");
78//! ```
79//!
80//! And that's it! That's the gist of testing `iced` applications!
81//!
82//! [`Simulator`] contains additional operations you can use to simulate more interactions—like [`tap_key`](Simulator::tap_key) or
83//! [`typewrite`](Simulator::typewrite)—and even perform [_snapshot testing_](Simulator::snapshot)!
84//!
85//! [the classical counter interface]: https://book.iced.rs/architecture.html#dissecting-an-interface
86pub use iced_program as program;
87pub use iced_renderer as renderer;
88pub use iced_runtime as runtime;
89pub use iced_runtime::core;
90
91pub use iced_selector as selector;
92
93pub mod emulator;
94pub mod ice;
95pub mod instruction;
96pub mod simulator;
97
98mod error;
99
100pub use emulator::Emulator;
101pub use error::Error;
102pub use ice::Ice;
103pub use instruction::Instruction;
104pub use selector::Selector;
105pub use simulator::{Simulator, simulator};
106
107use crate::core::Size;
108use crate::core::time::{Duration, Instant};
109use crate::core::window;
110
111use std::path::Path;
112
113/// Runs an [`Ice`] test suite for the given [`Program`](program::Program).
114///
115/// Any `.ice` tests will be parsed from the given directory and executed in
116/// an [`Emulator`] of the given [`Program`](program::Program).
117///
118/// Remember that an [`Emulator`] executes the real thing! Side effects _will_
119/// take place. It is up to you to ensure your tests have reproducible environments
120/// by leveraging [`Preset`][program::Preset].
121pub fn run(
122    program: impl program::Program + 'static,
123    tests_dir: impl AsRef<Path>,
124) -> Result<(), Error> {
125    use crate::runtime::futures::futures::StreamExt;
126    use crate::runtime::futures::futures::channel::mpsc;
127    use crate::runtime::futures::futures::executor;
128
129    use std::ffi::OsStr;
130    use std::fs;
131
132    let files = fs::read_dir(tests_dir)?;
133    let mut tests = Vec::new();
134
135    for file in files {
136        let file = file?;
137
138        if file.path().extension().and_then(OsStr::to_str) != Some("ice") {
139            continue;
140        }
141
142        let content = fs::read_to_string(file.path())?;
143
144        match Ice::parse(&content) {
145            Ok(ice) => {
146                let preset = if let Some(preset) = &ice.preset {
147                    let Some(preset) = program
148                        .presets()
149                        .iter()
150                        .find(|candidate| candidate.name() == preset)
151                    else {
152                        return Err(Error::PresetNotFound {
153                            name: preset.to_owned(),
154                            available: program
155                                .presets()
156                                .iter()
157                                .map(program::Preset::name)
158                                .map(str::to_owned)
159                                .collect(),
160                        });
161                    };
162
163                    Some(preset)
164                } else {
165                    None
166                };
167
168                tests.push((file, ice, preset));
169            }
170            Err(error) => {
171                return Err(Error::IceParsingFailed {
172                    file: file.path().to_path_buf(),
173                    error,
174                });
175            }
176        }
177    }
178
179    // TODO: Concurrent runtimes
180    for (file, ice, preset) in tests {
181        let (sender, mut receiver) = mpsc::channel(1);
182
183        let mut emulator = Emulator::with_preset(
184            sender,
185            &program,
186            ice.mode,
187            ice.viewport,
188            preset,
189        );
190
191        let mut instructions = ice.instructions.into_iter();
192
193        loop {
194            let event = executor::block_on(receiver.next())
195                .expect("emulator runtime should never stop on its own");
196
197            match event {
198                emulator::Event::Action(action) => {
199                    emulator.perform(&program, action);
200                }
201                emulator::Event::Failed(instruction) => {
202                    return Err(Error::IceTestingFailed {
203                        file: file.path().to_path_buf(),
204                        instruction,
205                    });
206                }
207                emulator::Event::Ready => {
208                    let Some(instruction) = instructions.next() else {
209                        break;
210                    };
211
212                    emulator.run(&program, instruction);
213                }
214            }
215        }
216    }
217
218    Ok(())
219}
220
221/// Takes a screenshot of the given [`Program`](program::Program) with the given theme, viewport,
222/// and scale factor after running it for the given [`Duration`].
223pub fn screenshot<P: program::Program + 'static>(
224    program: &P,
225    theme: &P::Theme,
226    viewport: impl Into<Size>,
227    scale_factor: f32,
228    duration: Duration,
229) -> window::Screenshot {
230    use crate::runtime::futures::futures::channel::mpsc;
231
232    let (sender, mut receiver) = mpsc::channel(100);
233
234    let mut emulator = Emulator::new(
235        sender,
236        program,
237        emulator::Mode::Immediate,
238        viewport.into(),
239    );
240
241    let start = Instant::now();
242
243    loop {
244        if let Some(event) = receiver.try_next().ok().flatten() {
245            match event {
246                emulator::Event::Action(action) => {
247                    emulator.perform(program, action);
248                }
249                emulator::Event::Failed(_) => {
250                    unreachable!(
251                        "no instructions should be executed during a screenshot"
252                    );
253                }
254                emulator::Event::Ready => {}
255            }
256        }
257
258        if start.elapsed() >= duration {
259            break;
260        }
261
262        std::thread::sleep(Duration::from_millis(1));
263    }
264
265    emulator.screenshot(program, theme, scale_factor)
266}