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::time::{Duration, Instant};
110use crate::core::window;
111
112use std::path::Path;
113
114/// Runs an [`Ice`] test suite for the given [`Program`](program::Program).
115///
116/// Any `.ice` tests will be parsed from the given directory and executed in
117/// an [`Emulator`] of the given [`Program`](program::Program).
118///
119/// Remember that an [`Emulator`] executes the real thing! Side effects _will_
120/// take place. It is up to you to ensure your tests have reproducible environments
121/// by leveraging [`Preset`][program::Preset].
122pub fn run(
123 program: impl program::Program + 'static,
124 tests_dir: impl AsRef<Path>,
125) -> Result<(), Error> {
126 use crate::futures::futures::StreamExt;
127 use crate::futures::futures::channel::mpsc;
128 use crate::futures::futures::executor;
129
130 use std::ffi::OsStr;
131 use std::fs;
132
133 let files = fs::read_dir(tests_dir)?;
134 let mut tests = Vec::new();
135
136 for file in files {
137 let file = file?;
138
139 if file.path().extension().and_then(OsStr::to_str) != Some("ice") {
140 continue;
141 }
142
143 let content = fs::read_to_string(file.path())?;
144
145 match Ice::parse(&content) {
146 Ok(ice) => {
147 let preset = if let Some(preset) = &ice.preset {
148 let Some(preset) = program
149 .presets()
150 .iter()
151 .find(|candidate| candidate.name() == preset)
152 else {
153 return Err(Error::PresetNotFound {
154 name: preset.to_owned(),
155 available: program
156 .presets()
157 .iter()
158 .map(program::Preset::name)
159 .map(str::to_owned)
160 .collect(),
161 });
162 };
163
164 Some(preset)
165 } else {
166 None
167 };
168
169 tests.push((file, ice, preset));
170 }
171 Err(error) => {
172 return Err(Error::IceParsingFailed {
173 file: file.path().to_path_buf(),
174 error,
175 });
176 }
177 }
178 }
179
180 // TODO: Concurrent runtimes
181 for (file, ice, preset) in tests {
182 let (sender, mut receiver) = mpsc::channel(1);
183
184 let mut emulator = Emulator::with_preset(sender, &program, ice.mode, ice.viewport, preset);
185
186 let mut instructions = ice.instructions.into_iter();
187
188 loop {
189 let event = executor::block_on(receiver.next())
190 .expect("emulator runtime should never stop on its own");
191
192 match event {
193 emulator::Event::Action(action) => {
194 emulator.perform(&program, action);
195 }
196 emulator::Event::Failed(instruction) => {
197 return Err(Error::IceTestingFailed {
198 file: file.path().to_path_buf(),
199 instruction,
200 });
201 }
202 emulator::Event::Ready => {
203 let Some(instruction) = instructions.next() else {
204 break;
205 };
206
207 emulator.run(&program, instruction);
208 }
209 }
210 }
211 }
212
213 Ok(())
214}
215
216/// Takes a screenshot of the given [`Program`](program::Program) with the given theme, viewport,
217/// and scale factor after running it for the given [`Duration`].
218pub fn screenshot<P: program::Program + 'static>(
219 program: &P,
220 theme: &P::Theme,
221 viewport: impl Into<Size>,
222 scale_factor: f32,
223 duration: Duration,
224) -> window::Screenshot {
225 use crate::runtime::futures::futures::channel::mpsc;
226
227 let (sender, mut receiver) = mpsc::channel(100);
228
229 let mut emulator = Emulator::new(sender, program, emulator::Mode::Immediate, viewport.into());
230
231 let start = Instant::now();
232
233 loop {
234 if let Some(event) = receiver.try_next().ok().flatten() {
235 match event {
236 emulator::Event::Action(action) => {
237 emulator.perform(program, action);
238 }
239 emulator::Event::Failed(_) => {
240 unreachable!("no instructions should be executed during a screenshot");
241 }
242 emulator::Event::Ready => {}
243 }
244 }
245
246 if start.elapsed() >= duration {
247 break;
248 }
249
250 std::thread::sleep(Duration::from_millis(1));
251 }
252
253 emulator.screenshot(program, theme, scale_factor)
254}