sinomo-ui-testing 0.3.0

Deterministic in-process UI automation for SUI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
use std::{
    cell::RefCell,
    rc::Rc,
    sync::{
        Arc, Mutex,
        atomic::{AtomicBool, Ordering},
    },
};

use sui_core::{
    Color, Event, ImageHandle, ImeEvent, KeyState, PointerEventKind, PointerKind, Result,
    SemanticsAction, SemanticsNode, SemanticsRole, SemanticsValue, Size, TimerToken, WakeEvent,
    WindowEvent,
};
use sui_layout::Constraints;
use sui_render_wgpu::WgpuExternalTextureRegistry;
use sui_runtime::{
    Application, ArrangeCtx, EventCtx, MeasureCtx, PaintCtx, SemanticsCtx, Widget, WidgetChildren,
    WidgetPodMutVisitor, WidgetPodVisitor, WindowBuilder,
};
use sui_scene::{ImageSource, RegisteredExternalImage};
use sui_testing::prelude::*;

#[test]
fn saves_form_in_a_unit_test() -> Result<()> {
    let app = TestApp::new(|| {
        let state = Rc::new(RefCell::new(AppState::default()));
        Application::new().window(
            WindowBuilder::new()
                .title("Unit Test Example")
                .root(FormRoot::new(state)),
        )
    })?;

    let window = app.main_window()?;

    window
        .get_by_role(SemanticsRole::TextInput)
        .with_name("Name")
        .fill("Ada")?;
    window
        .get_by_role(SemanticsRole::TextInput)
        .with_name("Name")
        .expect()
        .to_have_value("Ada")?;

    window
        .get_by_role(SemanticsRole::Button)
        .with_name("Save")
        .click()?;

    window.get_by_text("Saved").expect().to_be_visible()?;
    Ok(())
}

#[test]
fn touch_tap_delivers_touch_pointer_events() -> Result<()> {
    let state = Arc::new(Mutex::new(String::new()));
    let runtime = {
        let state = Arc::clone(&state);
        Application::new()
            .window(
                WindowBuilder::new()
                    .title("Touch Test")
                    .root(TouchProbe::new(state)),
            )
            .build()?
    };
    let app = TestApp::from_runtime(runtime)?;

    app.main_window()?
        .get_by_role(SemanticsRole::Button)
        .with_name("Touch target")
        .touch_tap()?;

    assert_eq!(state.lock().expect("touch state").as_str(), "touch-down:1");
    Ok(())
}

#[test]
fn registry_aware_headless_app_renders_an_external_texture() -> Result<()> {
    let handle = ImageHandle::new(9_501);
    let ready = Arc::new(AtomicBool::new(false));
    let registry = WgpuExternalTextureRegistry::new();
    let runtime =
        Application::new()
            .window(WindowBuilder::new().title("External texture test").root(
                ExternalTextureProbe {
                    handle,
                    ready: Arc::clone(&ready),
                },
            ))
            .build()?;
    let app = TestApp::from_runtime_with_external_texture_registry(runtime, registry.clone())?;
    let window = app.main_window()?;

    registry.upload_rgba8(
        handle,
        2,
        2,
        Arc::<[u8]>::from(
            [0_u8, 255, 0, 255]
                .into_iter()
                .cycle()
                .take(2 * 2 * 4)
                .collect::<Vec<_>>(),
        ),
        1,
    )?;
    ready.store(true, Ordering::Release);
    window.dispatch_event_now(Event::Window(WindowEvent::Resized(Size::new(32.0, 32.0))))?;
    window.run_until_idle()?;

    window
        .get_by_role(SemanticsRole::Image)
        .with_name("External texture probe")
        .expect()
        .to_be_visible()?;
    let screenshot = window.capture_screenshot()?;
    assert!(
        screenshot
            .pixels()
            .chunks_exact(4)
            .any(|pixel| pixel[1] > 200 && pixel[0] < 20 && pixel[2] < 20),
        "the headless renderer must sample the uploaded green texture"
    );
    Ok(())
}

#[derive(Debug, Default)]
struct AppState {
    name: String,
    status: String,
    save_timer: Option<TimerToken>,
}

struct TouchProbe {
    state: Arc<Mutex<String>>,
}

struct ExternalTextureProbe {
    handle: ImageHandle,
    ready: Arc<AtomicBool>,
}

impl Widget for ExternalTextureProbe {
    fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
        constraints.clamp(Size::new(32.0, 32.0))
    }

    fn arrange(&mut self, _ctx: &mut ArrangeCtx, _bounds: sui_core::Rect) {}

    fn paint(&self, ctx: &mut PaintCtx) {
        if self.ready.load(Ordering::Acquire) {
            ctx.register_external_image(
                self.handle,
                RegisteredExternalImage::new(2, 2).expect("valid external test image extent"),
            );
            ctx.draw_image_source(ctx.bounds(), ImageSource::new(self.handle));
        } else {
            ctx.fill_bounds(Color::BLACK);
        }
    }

    fn semantics(&self, ctx: &mut SemanticsCtx) {
        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Image, ctx.bounds());
        node.name = Some("External texture probe".to_owned());
        ctx.push(node);
    }
}

impl TouchProbe {
    fn new(state: Arc<Mutex<String>>) -> Self {
        Self { state }
    }
}

impl Widget for TouchProbe {
    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
        if let Event::Pointer(pointer) = event
            && pointer.kind == PointerEventKind::Down
            && pointer.pointer_kind == PointerKind::Touch
        {
            *self.state.lock().expect("touch state") = format!("touch-down:{}", pointer.pointer_id);
            ctx.request_paint();
            ctx.request_semantics();
            ctx.set_handled();
        }
    }

    fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
        constraints.clamp(Size::new(160.0, 64.0))
    }

    fn arrange(&mut self, _ctx: &mut ArrangeCtx, _bounds: sui_core::Rect) {}

    fn paint(&self, ctx: &mut PaintCtx) {
        ctx.fill_bounds(Color::rgba(0.18, 0.25, 0.34, 1.0));
    }

    fn semantics(&self, ctx: &mut SemanticsCtx) {
        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Button, ctx.bounds());
        node.name = Some("Touch target".to_string());
        node.actions = vec![SemanticsAction::Activate];
        ctx.push(node);
    }
}

struct FormRoot {
    children: WidgetChildren,
}

impl FormRoot {
    fn new(state: Rc<RefCell<AppState>>) -> Self {
        let mut children = WidgetChildren::new();
        children.push(NameInput::new(Rc::clone(&state)));
        children.push(SaveButton::new(state));
        Self { children }
    }
}

impl Widget for FormRoot {
    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
        let viewport = constraints.clamp(Size::new(420.0, 220.0));
        let control = Constraints::tight(Size::new(200.0, 44.0));

        self.children.measure_child(0, ctx, control);
        self.children.measure_child(1, ctx, control);

        viewport
    }

    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: sui_core::Rect) {
        self.children.arrange_child(
            0,
            ctx,
            sui_core::Rect::new(bounds.x() + 24.0, bounds.y() + 24.0, 200.0, 44.0),
        );
        self.children.arrange_child(
            1,
            ctx,
            sui_core::Rect::new(bounds.x() + 24.0, bounds.y() + 92.0, 200.0, 44.0),
        );
    }

    fn paint(&self, ctx: &mut PaintCtx) {
        ctx.clear(Color::rgba(0.08, 0.09, 0.11, 1.0));
        self.children.paint(ctx);
    }

    fn semantics(&self, ctx: &mut SemanticsCtx) {
        let mut root = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Window, ctx.bounds());
        root.name = Some("Unit Test Example".to_string());
        ctx.push(root);
        self.children.semantics(ctx);
    }

    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
        self.children.visit_children(visitor);
    }

    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
        self.children.visit_children_mut(visitor);
    }
}

struct NameInput {
    state: Rc<RefCell<AppState>>,
}

impl NameInput {
    fn new(state: Rc<RefCell<AppState>>) -> Self {
        Self { state }
    }
}

impl Widget for NameInput {
    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
        match event {
            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Down => {
                ctx.request_focus();
                ctx.request_paint();
                ctx.request_semantics();
                ctx.set_handled();
            }
            Event::Ime(ImeEvent::CompositionCommit { text }) if ctx.is_focused() => {
                self.state.borrow_mut().name = text.clone();
                ctx.request_paint();
                ctx.request_semantics();
                ctx.set_handled();
            }
            _ => {}
        }
    }

    fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
        constraints.clamp(Size::new(200.0, 44.0))
    }

    fn paint(&self, ctx: &mut PaintCtx) {
        let background = if ctx.is_focused() {
            Color::rgba(0.18, 0.23, 0.32, 1.0)
        } else {
            Color::rgba(0.13, 0.15, 0.20, 1.0)
        };
        ctx.fill_bounds(background);
        ctx.label(
            ctx.bounds(),
            format!("Name: {}", self.state.borrow().name),
            Color::rgba(0.95, 0.96, 0.98, 1.0),
        );
    }

    fn semantics(&self, ctx: &mut SemanticsCtx) {
        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::TextInput, ctx.bounds());
        node.name = Some("Name".to_string());
        node.value = Some(SemanticsValue::Text(self.state.borrow().name.clone()));
        node.actions = vec![SemanticsAction::Focus, SemanticsAction::SetValue];
        ctx.push(node);
    }

    fn accepts_focus(&self) -> bool {
        true
    }

    fn focus_changed(&mut self, ctx: &mut EventCtx, _focused: bool) {
        ctx.request_paint();
        ctx.request_semantics();
    }
}

struct SaveButton {
    state: Rc<RefCell<AppState>>,
}

impl SaveButton {
    fn new(state: Rc<RefCell<AppState>>) -> Self {
        Self { state }
    }
}

impl Widget for SaveButton {
    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
        match event {
            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Down => {
                start_save(&self.state, ctx);
            }
            Event::Keyboard(key)
                if key.state == KeyState::Pressed
                    && ctx.is_focused()
                    && matches!(key.key.as_str(), "Enter" | " ") =>
            {
                start_save(&self.state, ctx);
            }
            Event::Wake(WakeEvent::Timer { token, .. }) => {
                let mut state = self.state.borrow_mut();
                if state.save_timer == Some(*token) {
                    state.status = "Saved".to_string();
                    state.save_timer = None;
                    ctx.request_paint();
                    ctx.request_semantics();
                    ctx.set_handled();
                }
            }
            _ => {}
        }
    }

    fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
        constraints.clamp(Size::new(200.0, 44.0))
    }

    fn paint(&self, ctx: &mut PaintCtx) {
        let state = self.state.borrow();
        let background = if ctx.is_focused() {
            Color::rgba(0.25, 0.52, 0.88, 1.0)
        } else {
            Color::rgba(0.17, 0.24, 0.37, 1.0)
        };
        ctx.fill_bounds(background);
        ctx.label(
            ctx.bounds(),
            format!("Save {}", state.status),
            Color::rgba(0.95, 0.96, 0.98, 1.0),
        );
    }

    fn semantics(&self, ctx: &mut SemanticsCtx) {
        let state = self.state.borrow();

        let mut button = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Button, ctx.bounds());
        button.name = Some("Save".to_string());
        button.actions = vec![SemanticsAction::Focus, SemanticsAction::Activate];
        ctx.push(button);

        let mut status = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Text, ctx.bounds());
        status.parent = Some(ctx.root_widget_id());
        status.name = Some(state.status.clone());
        ctx.push(status);
    }

    fn accepts_focus(&self) -> bool {
        true
    }

    fn focus_changed(&mut self, ctx: &mut EventCtx, _focused: bool) {
        ctx.request_paint();
        ctx.request_semantics();
    }
}

fn start_save(state: &Rc<RefCell<AppState>>, ctx: &mut EventCtx) {
    let mut state = state.borrow_mut();
    state.status = "Saving".to_string();
    state.save_timer = Some(ctx.schedule_timer_after(1.0));
    ctx.request_focus();
    ctx.request_paint();
    ctx.request_semantics();
    ctx.set_handled();
}