fission-test-driver 0.2.0

Live app testing client and protocol helpers for Fission shells
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
//! Automated UI testing client and protocol for Fission applications.
//!
//! This crate provides the JSON protocol types (shared between the test client
//! and the desktop shell server) and a [`LiveTestClient`] that drives a running
//! Fission application over HTTP.
//!
//! # Architecture
//!
//! The application must be launched with `FISSION_TEST_CONTROL_PORT=<port>`.
//! The [`LiveTestClient`] connects to `http://127.0.0.1:<port>` and sends
//! [`TestCommand`] JSON payloads to `/cmd`, receiving [`TestResponse`] replies.

#[cfg(not(target_arch = "wasm32"))]
use anyhow::{anyhow, Result};
#[cfg(not(target_arch = "wasm32"))]
use base64::Engine;
use serde::{Deserialize, Serialize};

// --- Protocol types (shared between client and server) ---

/// A command sent from the test client to the running application.
///
/// Serialized with `#[serde(tag = "cmd")]`. See the crate-level docs for
/// the full command reference.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "cmd")]
pub enum TestCommand {
    Tap {
        x: f32,
        y: f32,
    },
    Drag {
        start_x: f32,
        start_y: f32,
        end_x: f32,
        end_y: f32,
        steps: u32,
    },
    TapText {
        text: String,
    },
    Scroll {
        x: f32,
        y: f32,
        dx: f32,
        dy: f32,
    },
    TypeText {
        text: String,
    },
    PressKey {
        key: String,
        modifiers: u8,
    },
    Screenshot {
        path: String,
    },
    CaptureScreenshot {},
    GetText {},
    GetTree {},
    Wait {
        ms: u64,
    },
    Pump {},
    Quit {},
    // NEW: simulate real winit-level events for realistic testing
    SimulateMouseMove {
        x: f32,
        y: f32,
    },
    SimulateRightClick {
        x: f32,
        y: f32,
    },
    SimulateResize {
        /// Target logical viewport width in test-space pixels.
        width: u32,
        /// Target logical viewport height in test-space pixels.
        height: u32,
    },
}

/// Events injected into the winit event loop via `EventLoopProxy`.
///
/// Input-simulation variants (`MouseMove`, `MouseDown`, etc.) travel through
/// the **same** `Event::UserEvent` → handler path as real `WindowEvent`s, so
/// test code exercises identical code paths as real user interaction.
///
/// Query / control variants (`Screenshot`, `GetText`, etc.) also go through
/// the proxy so the main loop can respond via a dedicated response channel.
#[derive(Debug, Clone)]
pub enum TestEvent {
    // --- Input simulation (mirrors winit WindowEvents) ---
    MouseMove {
        x: f32,
        y: f32,
    },
    MouseDown {
        x: f32,
        y: f32,
        button: u8,
    }, // 0=left, 1=right, 2=middle
    MouseUp {
        x: f32,
        y: f32,
        button: u8,
    },
    KeyDown {
        key_code: String,
        modifiers: u8,
    },
    KeyUp {
        key_code: String,
        modifiers: u8,
    },
    TextInput {
        text: String,
    },
    Scroll {
        x: f32,
        y: f32,
        dx: f32,
        dy: f32,
    },
    Resize {
        width: u32,
        height: u32,
    },
    // --- Queries / control (need response channel) ---
    Screenshot {
        path: String,
    },
    CaptureScreenshot,
    GetText,
    GetTree,
    Pump,
    Wake,
    Quit,
    /// Internal: TapText resolves a text label to coordinates; the server
    /// injects this so the main loop can do the lookup with access to the IR.
    TapText {
        text: String,
    },
    /// Internal: Wait is handled server-side (sleep) then responds.
    Wait {
        ms: u64,
    },
}

/// A visible text element with its bounding rectangle, in logical test-space
/// pixels, returned by [`TestCommand::GetText`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TextItem {
    pub text: String,
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
}

/// A node in the semantic accessibility tree, returned by [`TestCommand::GetTree`].
/// Bounding rectangles are expressed in logical test-space pixels.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SemanticNode {
    pub role: String,
    pub label: Option<String>,
    pub value: Option<String>,
    pub focusable: bool,
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
}

/// The response from the application to a [`TestCommand`].
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "status")]
pub enum TestResponse {
    Ok {},
    Text {
        items: Vec<TextItem>,
    },
    Tree {
        nodes: Vec<SemanticNode>,
    },
    Screenshot {
        png_base64: String,
        /// PNG width in logical test-space pixels.
        width: u32,
        /// PNG height in logical test-space pixels.
        height: u32,
    },
    Error {
        message: String,
    },
}

// --- Client ---

/// An HTTP client that drives a running Fission application for automated UI testing.
///
/// Connect to a running application via [`LiveTestClient::connect(port)`]. The
/// application must have been started with `FISSION_TEST_CONTROL_PORT=<port>`.
///
/// # Example
///
/// ```rust,ignore
/// let client = LiveTestClient::connect(9876);
/// client.wait_for_ready(5000).unwrap();
/// client.tap_text("Submit").unwrap();
/// client.assert_text_visible("Success").unwrap();
/// client.screenshot("/tmp/result.png").unwrap();
/// client.quit().unwrap();
/// ```
#[cfg(not(target_arch = "wasm32"))]
pub struct LiveTestClient {
    base_url: String,
}

#[cfg(not(target_arch = "wasm32"))]
impl LiveTestClient {
    pub fn connect(port: u16) -> Self {
        Self {
            base_url: format!("http://127.0.0.1:{}", port),
        }
    }

    pub fn wait_for_ready(&self, timeout_ms: u64) -> Result<()> {
        let start = std::time::Instant::now();
        let timeout = std::time::Duration::from_millis(timeout_ms);
        loop {
            match ureq::get(&format!("{}/health", self.base_url)).call() {
                Ok(_) => return Ok(()),
                Err(_) => {
                    if start.elapsed() > timeout {
                        return Err(anyhow!("timed out waiting for test server"));
                    }
                    std::thread::sleep(std::time::Duration::from_millis(100));
                }
            }
        }
    }

    fn send(&self, cmd: TestCommand) -> Result<TestResponse> {
        let body = serde_json::to_string(&cmd)?;
        let resp = ureq::post(&format!("{}/cmd", self.base_url))
            .set("Content-Type", "application/json")
            .send_string(&body)
            .map_err(|e| anyhow!("request failed: {}", e))?;
        let text = resp.into_string()?;
        let response: TestResponse = serde_json::from_str(&text)?;
        if let TestResponse::Error { message } = &response {
            return Err(anyhow!("server error: {}", message));
        }
        Ok(response)
    }

    pub fn tap(&self, x: f32, y: f32) -> Result<()> {
        self.send(TestCommand::Tap { x, y })?;
        Ok(())
    }

    pub fn tap_text(&self, text: &str) -> Result<()> {
        // Pump first to ensure layout positions are current
        self.pump()?;
        self.send(TestCommand::TapText {
            text: text.to_string(),
        })?;
        // Pump after to render the result of the tap
        self.pump()?;
        Ok(())
    }

    pub fn drag(
        &self,
        start_x: f32,
        start_y: f32,
        end_x: f32,
        end_y: f32,
        steps: u32,
    ) -> Result<()> {
        self.send(TestCommand::Drag {
            start_x,
            start_y,
            end_x,
            end_y,
            steps,
        })?;
        self.pump()?;
        Ok(())
    }

    pub fn scroll(&self, x: f32, y: f32, dx: f32, dy: f32) -> Result<()> {
        self.send(TestCommand::Scroll { x, y, dx, dy })?;
        Ok(())
    }

    pub fn press_key(&self, key: &str, modifiers: u8) -> Result<()> {
        self.send(TestCommand::PressKey {
            key: key.to_string(),
            modifiers,
        })?;
        self.pump()?;
        Ok(())
    }

    pub fn type_text(&self, text: &str) -> Result<()> {
        self.send(TestCommand::TypeText {
            text: text.to_string(),
        })?;
        Ok(())
    }

    pub fn screenshot(&self, path: &str) -> Result<()> {
        match self.send(TestCommand::CaptureScreenshot {})? {
            TestResponse::Screenshot {
                png_base64,
                width: _,
                height: _,
            } => {
                let bytes = base64::engine::general_purpose::STANDARD
                    .decode(png_base64)
                    .map_err(|e| anyhow!("invalid screenshot payload: {}", e))?;
                std::fs::write(path, bytes)?;
                Ok(())
            }
            other => Err(anyhow!(
                "unexpected response to CaptureScreenshot: {:?}",
                other
            )),
        }
    }

    pub fn get_text(&self) -> Result<Vec<TextItem>> {
        match self.send(TestCommand::GetText {})? {
            TestResponse::Text { items } => Ok(items),
            other => Err(anyhow!("unexpected response: {:?}", other)),
        }
    }

    pub fn get_tree(&self) -> Result<Vec<SemanticNode>> {
        match self.send(TestCommand::GetTree {})? {
            TestResponse::Tree { nodes } => Ok(nodes),
            other => Err(anyhow!("unexpected response: {:?}", other)),
        }
    }

    pub fn wait(&self, ms: u64) -> Result<()> {
        self.send(TestCommand::Wait { ms })?;
        Ok(())
    }

    pub fn pump(&self) -> Result<()> {
        self.send(TestCommand::Pump {})?;
        Ok(())
    }

    pub fn quit(&self) -> Result<()> {
        let _ = self.send(TestCommand::Quit {});
        Ok(())
    }

    // --- NEW: simulate real winit-level events ---

    /// Simulate a mouse move to (x, y) — goes through the real CursorMoved path.
    pub fn simulate_mouse_move(&self, x: f32, y: f32) -> Result<()> {
        self.send(TestCommand::SimulateMouseMove { x, y })?;
        Ok(())
    }

    /// Simulate a right-click at (x, y) — move + down + up with right button.
    pub fn right_click(&self, x: f32, y: f32) -> Result<()> {
        self.send(TestCommand::SimulateRightClick { x, y })?;
        Ok(())
    }

    /// Simulate a window resize in logical test-space pixels.
    pub fn simulate_resize(&self, width: u32, height: u32) -> Result<()> {
        self.send(TestCommand::SimulateResize { width, height })?;
        Ok(())
    }

    // --- High-level helpers ---

    pub fn tap_text_and_wait(&self, text: &str, ms: u64) -> Result<()> {
        self.tap_text(text)?;
        self.wait(ms)?;
        Ok(())
    }

    pub fn assert_text_visible(&self, needle: &str) -> Result<()> {
        let items = self.get_text()?;
        let found = items.iter().any(|t| t.text.contains(needle));
        if !found {
            let all: Vec<&str> = items.iter().map(|t| t.text.as_str()).collect();
            return Err(anyhow!(
                "expected '{}' to be visible, found: {:?}",
                needle,
                &all[..all.len().min(20)]
            ));
        }
        Ok(())
    }

    pub fn assert_text_not_visible(&self, needle: &str) -> Result<()> {
        let items = self.get_text()?;
        let found = items.iter().any(|t| t.text.contains(needle));
        if found {
            return Err(anyhow!("expected '{}' to NOT be visible", needle));
        }
        Ok(())
    }
}