Skip to main content

freya_testing/
lib.rs

1//! Testing utilities for Freya applications.
2//!
3//! Simulate your app execution in a headless environment.
4//!
5//! Use [launch_test] or [TestingRunner] to instantiate a headless testing runner.
6//!
7//! # Examples
8//!
9//! Basic usage:
10//!
11//! ```rust,no_run
12//! use freya::prelude::*;
13//! use freya_testing::TestingRunner;
14//!
15//! fn app() -> impl IntoElement {
16//!     let mut state = use_consume::<State<i32>>();
17//!     rect().on_mouse_up(move |_| *state.write() += 1)
18//! }
19//!
20//! fn main() {
21//!     let (mut test, state) = TestingRunner::new(
22//!         app,
23//!         (300., 300.).into(),
24//!         |runner| runner.provide_root_context(|| State::create(0)),
25//!         1.,
26//!     );
27//!     test.sync_and_update();
28//!     // Simulate a mouse click
29//!     test.click_cursor((15., 15.));
30//!     assert_eq!(*state.peek(), 1);
31//! }
32//! ```
33//!
34//! For a runnable example see `examples/testing_events.rs` in the repository.
35
36use std::{
37    borrow::Cow,
38    cell::RefCell,
39    collections::HashMap,
40    fs::File,
41    io::Write,
42    path::PathBuf,
43    rc::Rc,
44    time::{
45        Duration,
46        Instant,
47    },
48};
49
50use freya_clipboard::copypasta::{
51    ClipboardContext,
52    ClipboardProvider,
53};
54use freya_components::{
55    cache::AssetCacher,
56    integration::integration,
57};
58use freya_core::{
59    integration::*,
60    prelude::*,
61};
62use freya_engine::prelude::{
63    EncodedImageFormat,
64    FontCollection,
65    FontMgr,
66    SkData,
67    TypefaceFontProvider,
68    raster_n32_premul,
69};
70use ragnarok::{
71    CursorPoint,
72    EventsExecutorRunner,
73    EventsMeasurerRunner,
74    NodesState,
75};
76use torin::prelude::{
77    LayoutNode,
78    Size2D,
79};
80
81pub mod prelude {
82    pub use freya_core::{
83        events::platform::*,
84        prelude::*,
85    };
86
87    pub use crate::{
88        DocRunner,
89        TestingRunner,
90        launch_doc,
91        launch_test,
92    };
93}
94
95type DocRunnerHook = Box<dyn FnOnce(&mut TestingRunner)>;
96
97pub struct DocRunner {
98    app: AppComponent,
99    size: Size2D,
100    scale_factor: f64,
101    hook: Option<DocRunnerHook>,
102    image_path: PathBuf,
103}
104
105impl DocRunner {
106    pub fn render(self) {
107        let (mut test, _) = TestingRunner::new(self.app, self.size, |_| {}, self.scale_factor);
108        if let Some(hook) = self.hook {
109            (hook)(&mut test);
110        }
111        test.render_to_file(self.image_path);
112    }
113
114    pub fn with_hook(mut self, hook: impl FnOnce(&mut TestingRunner) + 'static) -> Self {
115        self.hook = Some(Box::new(hook));
116        self
117    }
118
119    pub fn with_image_path(mut self, image_path: PathBuf) -> Self {
120        self.image_path = image_path;
121        self
122    }
123
124    pub fn with_scale_factor(mut self, scale_factor: f64) -> Self {
125        self.scale_factor = scale_factor;
126        self
127    }
128
129    pub fn with_size(mut self, size: Size2D) -> Self {
130        self.size = size;
131        self
132    }
133}
134
135pub fn launch_doc(app: impl Into<AppComponent>, path: impl Into<PathBuf>) -> DocRunner {
136    DocRunner {
137        app: app.into(),
138        size: Size2D::new(250., 250.),
139        scale_factor: 1.0,
140        hook: None,
141        image_path: path.into(),
142    }
143}
144
145pub fn launch_test(app: impl Into<AppComponent>) -> TestingRunner {
146    TestingRunner::new(app, Size2D::new(500., 500.), |_| {}, 1.0).0
147}
148
149pub struct TestingRunner {
150    nodes_state: NodesState<NodeId>,
151    runner: Runner,
152    tree: Rc<RefCell<Tree>>,
153    size: Size2D,
154
155    accessibility: AccessibilityTree,
156
157    events_receiver: futures_channel::mpsc::UnboundedReceiver<EventsChunk>,
158    events_sender: futures_channel::mpsc::UnboundedSender<EventsChunk>,
159
160    font_manager: FontMgr,
161    font_collection: FontCollection,
162
163    platform: Platform,
164
165    animation_clock: AnimationClock,
166    ticker_sender: RenderingTickerSender,
167
168    default_fonts: Vec<Cow<'static, str>>,
169    scale_factor: f64,
170}
171
172impl TestingRunner {
173    pub fn new<T>(
174        app: impl Into<AppComponent>,
175        size: Size2D,
176        hook: impl FnOnce(&mut Runner) -> T,
177        scale_factor: f64,
178    ) -> (Self, T) {
179        let (events_sender, events_receiver) = futures_channel::mpsc::unbounded();
180        let app = app.into();
181        let mut runner = Runner::new(move || integration(app.clone()).into_element());
182
183        runner.provide_root_context(ScreenReader::new);
184
185        let (mut ticker_sender, ticker) = RenderingTicker::new();
186        ticker_sender.set_overflow(true);
187        runner.provide_root_context(|| ticker);
188
189        let animation_clock = runner.provide_root_context(AnimationClock::new);
190
191        runner.provide_root_context(AssetCacher::create);
192
193        let tree = Tree::default();
194        let tree = Rc::new(RefCell::new(tree));
195
196        let platform = runner.provide_root_context({
197            let tree = tree.clone();
198            || Platform {
199                focused_accessibility_id: State::create(ACCESSIBILITY_ROOT_ID),
200                focused_accessibility_node: State::create(accesskit::Node::new(
201                    accesskit::Role::Window,
202                )),
203                root_size: State::create(size),
204                navigation_mode: State::create(NavigationMode::NotKeyboard),
205                preferred_theme: State::create(PreferredTheme::Light),
206                is_app_focused: State::create(true),
207                accent_color: State::create(AccentColor::default()),
208                sender: Rc::new(move |user_event| {
209                    match user_event {
210                        UserEvent::RequestRedraw => {
211                            // Nothing
212                        }
213                        UserEvent::FocusAccessibilityNode(strategy) => {
214                            tree.borrow_mut().accessibility_diff.request_focus(strategy);
215                        }
216                        UserEvent::SetCursorIcon(_) => {
217                            // Nothing
218                        }
219                        UserEvent::Erased(_) => {
220                            // Nothing
221                        }
222                    }
223                }),
224            }
225        });
226
227        runner.provide_root_context(|| {
228            let clipboard: Option<Box<dyn ClipboardProvider>> = ClipboardContext::new()
229                .ok()
230                .map(|c| Box::new(c) as Box<dyn ClipboardProvider>);
231
232            State::create(clipboard)
233        });
234
235        runner.provide_root_context(|| tree.borrow().accessibility_generator.clone());
236
237        let hook_result = hook(&mut runner);
238
239        let mut font_collection = FontCollection::new();
240        let def_mgr = FontMgr::default();
241        let provider = TypefaceFontProvider::new();
242        let font_manager: FontMgr = provider.into();
243        font_collection.set_default_font_manager(def_mgr, None);
244        font_collection.set_dynamic_font_manager(font_manager.clone());
245        font_collection.paragraph_cache_mut().turn_on(false);
246
247        runner.provide_root_context(|| font_collection.clone());
248
249        let nodes_state = NodesState::default();
250        let accessibility = AccessibilityTree::default();
251
252        let mut runner = Self {
253            runner,
254            tree,
255            size,
256
257            accessibility,
258            platform,
259
260            nodes_state,
261            events_receiver,
262            events_sender,
263
264            font_manager,
265            font_collection,
266
267            animation_clock,
268            ticker_sender,
269
270            default_fonts: default_fonts(),
271            scale_factor,
272        };
273
274        runner.sync_and_update();
275
276        (runner, hook_result)
277    }
278
279    pub fn set_fonts(&mut self, fonts: HashMap<&str, &[u8]>) {
280        let mut provider = TypefaceFontProvider::new();
281        for (font_name, font_data) in fonts {
282            let ft_type = self
283                .font_collection
284                .fallback_manager()
285                .unwrap()
286                .new_from_data(font_data, None)
287                .unwrap_or_else(|| panic!("Failed to load font {font_name}."));
288            provider.register_typeface(ft_type, Some(font_name));
289        }
290        let font_manager: FontMgr = provider.into();
291        self.font_manager = font_manager.clone();
292        self.font_collection.set_dynamic_font_manager(font_manager);
293    }
294
295    pub fn set_default_fonts(&mut self, fonts: &[Cow<'static, str>]) {
296        self.default_fonts.clear();
297        self.default_fonts.extend_from_slice(fonts);
298        self.tree.borrow_mut().layout.reset();
299        self.tree.borrow_mut().text_cache.reset();
300        self.tree.borrow_mut().measure_layout(
301            self.size,
302            &mut self.font_collection,
303            &self.font_manager,
304            &self.events_sender,
305            self.scale_factor,
306            &self.default_fonts,
307        );
308        self.tree.borrow_mut().accessibility_diff.clear();
309        self.accessibility.focused_id = ACCESSIBILITY_ROOT_ID;
310        self.accessibility.init(&mut self.tree.borrow_mut());
311        self.sync_and_update();
312    }
313
314    pub async fn handle_events(&mut self) {
315        self.runner.handle_events().await
316    }
317
318    pub fn handle_events_immediately(&mut self) {
319        self.runner.handle_events_immediately()
320    }
321
322    pub fn sync_and_update(&mut self) {
323        while let Ok(events_chunk) = self.events_receiver.try_recv() {
324            match events_chunk {
325                EventsChunk::Processed(processed_events) => {
326                    let events_executor_adapter = EventsExecutorAdapter {
327                        runner: &mut self.runner,
328                    };
329                    events_executor_adapter.run(&mut self.nodes_state, processed_events);
330                }
331                EventsChunk::Batch(events) => {
332                    for event in events {
333                        self.runner.handle_event(
334                            event.node_id,
335                            event.name,
336                            event.data,
337                            event.bubbles,
338                        );
339                    }
340                }
341            }
342        }
343
344        let mutations = self.runner.sync_and_update();
345        self.runner.run_in(|| {
346            self.tree.borrow_mut().apply_mutations(mutations);
347        });
348        self.tree.borrow_mut().measure_layout(
349            self.size,
350            &mut self.font_collection,
351            &self.font_manager,
352            &self.events_sender,
353            self.scale_factor,
354            &self.default_fonts,
355        );
356
357        let accessibility_update = self
358            .accessibility
359            .process_updates(&mut self.tree.borrow_mut(), &self.events_sender);
360
361        self.platform
362            .focused_accessibility_id
363            .set_if_modified(accessibility_update.focus);
364        let node_id = self.accessibility.focused_node_id().unwrap();
365        let tree = self.tree.borrow();
366        let layout_node = tree.layout.get(&node_id).unwrap();
367        self.platform
368            .focused_accessibility_node
369            .set_if_modified(AccessibilityTree::create_node(node_id, layout_node, &tree));
370    }
371
372    /// Poll async tasks and events every `step` time for a total time of `duration`.
373    /// This is useful for animations for instance.
374    pub fn poll(&mut self, step: Duration, duration: Duration) {
375        let started = Instant::now();
376        while started.elapsed() < duration {
377            self.handle_events_immediately();
378            self.sync_and_update();
379            std::thread::sleep(step);
380            self.ticker_sender.broadcast_blocking(()).unwrap();
381        }
382    }
383
384    /// Poll async tasks and events every `step`, N times.
385    /// This is useful for animations for instance.
386    pub fn poll_n(&mut self, step: Duration, times: u32) {
387        for _ in 0..times {
388            self.handle_events_immediately();
389            self.sync_and_update();
390            std::thread::sleep(step);
391            self.ticker_sender.broadcast_blocking(()).unwrap();
392        }
393    }
394
395    pub fn send_event(&mut self, platform_event: PlatformEvent) {
396        let mut events_measurer_adapter = EventsMeasurerAdapter {
397            tree: &mut self.tree.borrow_mut(),
398            scale_factor: self.scale_factor,
399        };
400        let processed_events = events_measurer_adapter.run(
401            &mut vec![platform_event],
402            &mut self.nodes_state,
403            self.accessibility.focused_node_id(),
404        );
405        self.events_sender
406            .unbounded_send(EventsChunk::Processed(processed_events))
407            .unwrap();
408    }
409
410    pub fn move_cursor(&mut self, cursor: impl Into<CursorPoint>) {
411        self.send_event(PlatformEvent::Mouse {
412            name: MouseEventName::MouseMove,
413            cursor: cursor.into(),
414            button: Some(MouseButton::Left),
415        })
416    }
417
418    pub fn write_text(&mut self, text: impl ToString) {
419        let text = text.to_string();
420        self.send_event(PlatformEvent::Keyboard {
421            name: KeyboardEventName::KeyDown,
422            key: Key::Character(text),
423            code: Code::Unidentified,
424            modifiers: Modifiers::default(),
425        });
426        self.sync_and_update();
427    }
428
429    pub fn press_key(&mut self, key: Key) {
430        self.send_event(PlatformEvent::Keyboard {
431            name: KeyboardEventName::KeyDown,
432            key,
433            code: Code::Unidentified,
434            modifiers: Modifiers::default(),
435        });
436        self.sync_and_update();
437    }
438
439    pub fn press_cursor(&mut self, cursor: impl Into<CursorPoint>) {
440        let cursor = cursor.into();
441        self.send_event(PlatformEvent::Mouse {
442            name: MouseEventName::MouseDown,
443            cursor,
444            button: Some(MouseButton::Left),
445        });
446        self.sync_and_update();
447    }
448
449    pub fn release_cursor(&mut self, cursor: impl Into<CursorPoint>) {
450        let cursor = cursor.into();
451        self.send_event(PlatformEvent::Mouse {
452            name: MouseEventName::MouseUp,
453            cursor,
454            button: Some(MouseButton::Left),
455        });
456        self.sync_and_update();
457    }
458
459    pub fn click_cursor(&mut self, cursor: impl Into<CursorPoint>) {
460        let cursor = cursor.into();
461        self.send_event(PlatformEvent::Mouse {
462            name: MouseEventName::MouseDown,
463            cursor,
464            button: Some(MouseButton::Left),
465        });
466        self.sync_and_update();
467        self.send_event(PlatformEvent::Mouse {
468            name: MouseEventName::MouseUp,
469            cursor,
470            button: Some(MouseButton::Left),
471        });
472        self.sync_and_update();
473    }
474
475    pub fn press_touch(&mut self, location: impl Into<CursorPoint>) {
476        self.send_event(PlatformEvent::Touch {
477            name: TouchEventName::TouchStart,
478            location: location.into(),
479            finger_id: 0,
480            phase: TouchPhase::Started,
481            force: None,
482        });
483        self.sync_and_update();
484    }
485
486    pub fn move_touch(&mut self, location: impl Into<CursorPoint>) {
487        self.send_event(PlatformEvent::Touch {
488            name: TouchEventName::TouchMove,
489            location: location.into(),
490            finger_id: 0,
491            phase: TouchPhase::Moved,
492            force: None,
493        });
494        self.sync_and_update();
495    }
496
497    pub fn release_touch(&mut self, location: impl Into<CursorPoint>) {
498        self.send_event(PlatformEvent::Touch {
499            name: TouchEventName::TouchEnd,
500            location: location.into(),
501            finger_id: 0,
502            phase: TouchPhase::Ended,
503            force: None,
504        });
505        self.sync_and_update();
506    }
507
508    pub fn scroll(&mut self, cursor: impl Into<CursorPoint>, scroll: impl Into<CursorPoint>) {
509        let cursor = cursor.into();
510        let scroll = scroll.into();
511        self.send_event(PlatformEvent::Wheel {
512            name: WheelEventName::Wheel,
513            scroll,
514            cursor,
515            source: WheelSource::Device,
516        });
517        self.sync_and_update();
518    }
519
520    pub fn animation_clock(&mut self) -> &mut AnimationClock {
521        &mut self.animation_clock
522    }
523
524    pub fn render(&mut self) -> SkData {
525        let mut surface = raster_n32_premul((self.size.width as i32, self.size.height as i32))
526            .expect("Failed to create the surface.");
527
528        let render_pipeline = RenderPipeline {
529            font_collection: &mut self.font_collection,
530            font_manager: &self.font_manager,
531            tree: &self.tree.borrow(),
532            canvas: surface.canvas(),
533            scale_factor: self.scale_factor,
534            background: Color::WHITE,
535        };
536        render_pipeline.render();
537
538        let image = surface.image_snapshot();
539        let mut context = surface.direct_context();
540        image
541            .encode(context.as_mut(), EncodedImageFormat::PNG, None)
542            .expect("Failed to encode the snapshot.")
543    }
544
545    pub fn render_to_file(&mut self, path: impl Into<PathBuf>) {
546        let path = path.into();
547
548        let image = self.render();
549
550        let mut snapshot_file = File::create(path).expect("Failed to create the snapshot file.");
551
552        snapshot_file
553            .write_all(&image)
554            .expect("Failed to save the snapshot file.");
555    }
556
557    pub fn find<T>(
558        &self,
559        matcher: impl Fn(TestingNode, &dyn ElementExt) -> Option<T>,
560    ) -> Option<T> {
561        let mut matched = None;
562        {
563            let tree = self.tree.borrow();
564            tree.traverse_depth(|id| {
565                if matched.is_some() {
566                    return;
567                }
568                let element = tree.elements.get(&id).unwrap();
569                let node = TestingNode {
570                    tree: self.tree.clone(),
571                    id,
572                };
573                matched = matcher(node, element.as_ref());
574            });
575        }
576
577        matched
578    }
579
580    pub fn find_many<T>(
581        &self,
582        matcher: impl Fn(TestingNode, &dyn ElementExt) -> Option<T>,
583    ) -> Vec<T> {
584        let mut matched = Vec::new();
585        {
586            let tree = self.tree.borrow();
587            tree.traverse_depth(|id| {
588                let element = tree.elements.get(&id).unwrap();
589                let node = TestingNode {
590                    tree: self.tree.clone(),
591                    id,
592                };
593                if let Some(result) = matcher(node, element.as_ref()) {
594                    matched.push(result);
595                }
596            });
597        }
598
599        matched
600    }
601}
602
603pub struct TestingNode {
604    tree: Rc<RefCell<Tree>>,
605    id: NodeId,
606}
607
608impl TestingNode {
609    pub fn layout(&self) -> LayoutNode {
610        self.tree.borrow().layout.get(&self.id).cloned().unwrap()
611    }
612
613    pub fn children(&self) -> Vec<Self> {
614        let children = self
615            .tree
616            .borrow()
617            .children
618            .get(&self.id)
619            .cloned()
620            .unwrap_or_default();
621
622        children
623            .into_iter()
624            .map(|child_id| Self {
625                id: child_id,
626                tree: self.tree.clone(),
627            })
628            .collect()
629    }
630
631    pub fn is_visible(&self) -> bool {
632        let layout = self.layout();
633        let effect_state = self
634            .tree
635            .borrow()
636            .effect_state
637            .get(&self.id)
638            .cloned()
639            .unwrap();
640
641        effect_state.is_visible(&self.tree.borrow().layout, &layout.area)
642    }
643
644    pub fn element(&self) -> Rc<dyn ElementExt> {
645        self.tree
646            .borrow()
647            .elements
648            .get(&self.id)
649            .cloned()
650            .expect("Element does not exist.")
651    }
652}