Skip to main content

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_futures as futures;
87pub use iced_program as program;
88pub use iced_renderer as renderer;
89pub use iced_runtime as runtime;
90pub use iced_runtime::core;
91
92pub use iced_selector as selector;
93
94pub mod emulator;
95pub mod ice;
96pub mod instruction;
97pub mod simulator;
98
99mod error;
100
101pub use emulator::Emulator;
102pub use error::Error;
103pub use ice::Ice;
104pub use instruction::Instruction;
105pub use selector::Selector;
106pub use simulator::{Simulator, simulator};
107
108use crate::core::Size;
109use crate::core::theme;
110use crate::core::time::{Duration, Instant};
111use crate::core::window;
112
113use std::path::Path;
114
115/// Runs an [`Ice`] test suite for the given [`Program`](program::Program).
116///
117/// Any `.ice` tests will be parsed from the given directory and executed in
118/// an [`Emulator`] of the given [`Program`](program::Program).
119///
120/// Remember that an [`Emulator`] executes the real thing! Side effects _will_
121/// take place. It is up to you to ensure your tests have reproducible environments
122/// by leveraging [`Preset`][program::Preset].
123pub fn run<P: program::Program + 'static>(
124    program: P,
125    tests_dir: impl AsRef<Path>,
126) -> Result<(), Error> {
127    use crate::futures::futures::StreamExt;
128    use crate::futures::futures::channel::mpsc;
129    use crate::futures::futures::executor;
130
131    use std::ffi::OsStr;
132    use std::fs;
133
134    let errors_dir = tests_dir.as_ref().join("errors");
135
136    if errors_dir.exists() {
137        fs::remove_dir_all(&errors_dir)?;
138    }
139
140    let files = fs::read_dir(tests_dir)?;
141    let mut tests = Vec::new();
142
143    for file in files {
144        let file = file?;
145
146        if file.path().extension().and_then(OsStr::to_str) != Some("ice") {
147            continue;
148        }
149
150        let content = fs::read_to_string(file.path())?;
151
152        match Ice::parse(&content) {
153            Ok(ice) => {
154                let preset = if let Some(preset) = &ice.preset {
155                    let Some(preset) = program
156                        .presets()
157                        .iter()
158                        .find(|candidate| candidate.name() == preset)
159                    else {
160                        return Err(Error::PresetNotFound {
161                            name: preset.to_owned(),
162                            available: program
163                                .presets()
164                                .iter()
165                                .map(program::Preset::name)
166                                .map(str::to_owned)
167                                .collect(),
168                        });
169                    };
170
171                    Some(preset)
172                } else {
173                    None
174                };
175
176                tests.push((file, ice, preset));
177            }
178            Err(error) => {
179                return Err(Error::IceParsingFailed {
180                    file: file.path().to_path_buf(),
181                    error,
182                });
183            }
184        }
185    }
186
187    // TODO: Concurrent runtimes
188    for (file, ice, preset) in tests {
189        let (sender, mut receiver) = mpsc::channel(1);
190
191        let mut emulator = Emulator::with_preset(sender, &program, ice.mode, ice.viewport, preset);
192
193        let mut instructions = ice.instructions.iter();
194        let mut current = 0;
195
196        loop {
197            let event = executor::block_on(receiver.next())
198                .expect("emulator runtime should never stop on its own");
199
200            match event {
201                emulator::Event::Action(action) => {
202                    emulator.perform(&program, action);
203                }
204                emulator::Event::Failed(instruction) => {
205                    fs::create_dir_all(&errors_dir)?;
206
207                    let theme = emulator
208                        .theme(&program)
209                        .unwrap_or_else(|| <P::Theme as theme::Base>::default(theme::Mode::None));
210
211                    let screenshot = emulator.screenshot(&program, &theme, 2.0);
212
213                    let image = fs::File::create(
214                        errors_dir.join(
215                            file.path()
216                                .with_extension("png")
217                                .file_name()
218                                .expect("Test must have a filename"),
219                        ),
220                    )?;
221
222                    let mut encoder =
223                        png::Encoder::new(image, screenshot.size.width, screenshot.size.height);
224                    encoder.set_color(png::ColorType::Rgba);
225
226                    let mut writer = encoder.write_header()?;
227                    writer.write_image_data(&screenshot.rgba)?;
228                    writer.finish()?;
229
230                    let reproduction = Ice {
231                        viewport: ice.viewport,
232                        mode: ice.mode,
233                        preset: ice.preset,
234                        instructions: ice.instructions[..current].to_vec(),
235                    };
236
237                    fs::write(errors_dir.join(file.file_name()), reproduction.to_string())?;
238
239                    return Err(Error::IceTestingFailed {
240                        file: file.path().to_path_buf(),
241                        instruction,
242                    });
243                }
244                emulator::Event::Ready => {
245                    let Some(instruction) = instructions.next() else {
246                        break;
247                    };
248
249                    emulator.run(&program, instruction);
250                    current += 1;
251                }
252            }
253        }
254    }
255
256    Ok(())
257}
258
259/// Takes a screenshot of the given [`Program`](program::Program) with the given theme, viewport,
260/// and scale factor after running it for the given [`Duration`].
261pub fn screenshot<P: program::Program + 'static>(
262    program: &P,
263    theme: &P::Theme,
264    viewport: impl Into<Size>,
265    scale_factor: f32,
266    duration: Duration,
267) -> window::Screenshot {
268    use crate::runtime::futures::futures::channel::mpsc;
269
270    let (sender, mut receiver) = mpsc::channel(100);
271
272    let mut emulator = Emulator::new(sender, program, emulator::Mode::Immediate, viewport.into());
273
274    let start = Instant::now();
275
276    loop {
277        if let Some(event) = receiver.try_next().ok().flatten() {
278            match event {
279                emulator::Event::Action(action) => {
280                    emulator.perform(program, action);
281                }
282                emulator::Event::Failed(_) => {
283                    unreachable!("no instructions should be executed during a screenshot");
284                }
285                emulator::Event::Ready => {}
286            }
287        }
288
289        if start.elapsed() >= duration {
290            break;
291        }
292
293        std::thread::sleep(Duration::from_millis(1));
294    }
295
296    emulator.screenshot(program, theme, scale_factor)
297}