fission-test-driver 0.8.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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
#[cfg(not(target_arch = "wasm32"))]
use anyhow::{anyhow, Context, Result};
#[cfg(not(target_arch = "wasm32"))]
use base64::Engine;
#[cfg(not(target_arch = "wasm32"))]
use serde::{Deserialize, Serialize};
#[cfg(not(target_arch = "wasm32"))]
use serde_json::{json, Value};
#[cfg(not(target_arch = "wasm32"))]
use std::collections::VecDeque;
#[cfg(not(target_arch = "wasm32"))]
use std::fs;
#[cfg(not(target_arch = "wasm32"))]
use std::net::TcpListener;
#[cfg(not(target_arch = "wasm32"))]
use std::path::PathBuf;
#[cfg(not(target_arch = "wasm32"))]
use std::process::{Child, Command, Stdio};
#[cfg(not(target_arch = "wasm32"))]
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
#[cfg(not(target_arch = "wasm32"))]
use tungstenite::{connect, Message};

#[cfg(not(target_arch = "wasm32"))]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BrowserSmokeMode {
    Dom,
    FissionCanvas,
}

#[cfg(not(target_arch = "wasm32"))]
#[derive(Clone, Debug)]
pub struct BrowserTestOptions {
    pub url: String,
    pub mode: BrowserSmokeMode,
    pub chrome_path: Option<PathBuf>,
    pub cdp_port: Option<u16>,
    pub viewport_width: u32,
    pub viewport_height: u32,
    pub timeout_ms: u64,
    pub screenshot_path: Option<PathBuf>,
}

#[cfg(not(target_arch = "wasm32"))]
impl BrowserTestOptions {
    pub fn new(url: impl Into<String>) -> Self {
        Self {
            url: url.into(),
            mode: BrowserSmokeMode::Dom,
            chrome_path: None,
            cdp_port: None,
            viewport_width: 1280,
            viewport_height: 900,
            timeout_ms: 60_000,
            screenshot_path: None,
        }
    }

    pub fn fission_canvas(mut self) -> Self {
        self.mode = BrowserSmokeMode::FissionCanvas;
        self
    }

    pub fn screenshot(mut self, path: impl Into<PathBuf>) -> Self {
        self.screenshot_path = Some(path.into());
        self
    }
}

#[cfg(not(target_arch = "wasm32"))]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BrowserSmokeReport {
    pub url: String,
    pub title: String,
    pub width: u32,
    pub height: u32,
    pub renderer: Option<String>,
    pub body_text_len: usize,
    pub screenshot_path: Option<PathBuf>,
}

#[cfg(not(target_arch = "wasm32"))]
pub fn detect_chrome() -> Option<PathBuf> {
    if let Some(path) = std::env::var_os("FISSION_CHROME").map(PathBuf::from) {
        if path.is_file() {
            return Some(path);
        }
    }
    for candidate in [
        "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
        "/Applications/Chromium.app/Contents/MacOS/Chromium",
        "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
    ] {
        let path = PathBuf::from(candidate);
        if path.is_file() {
            return Some(path);
        }
    }
    for candidate in ["google-chrome", "chromium", "chromium-browser", "chrome"] {
        if let Ok(output) = Command::new("sh")
            .arg("-c")
            .arg(format!("command -v {candidate}"))
            .output()
        {
            if output.status.success() {
                let value = String::from_utf8_lossy(&output.stdout).trim().to_string();
                if !value.is_empty() {
                    return Some(PathBuf::from(value));
                }
            }
        }
    }
    None
}

#[cfg(not(target_arch = "wasm32"))]
pub fn run_browser_smoke(options: BrowserTestOptions) -> Result<BrowserSmokeReport> {
    let chrome = options
        .chrome_path
        .clone()
        .or_else(detect_chrome)
        .context("Chrome/Chromium was not found; set FISSION_CHROME=/path/to/chrome")?;
    let cdp_port = options.cdp_port.unwrap_or_else(free_port);
    let mut session = ChromeSession::launch(&chrome, cdp_port, &options)?;
    let ws_url = wait_for_target(
        cdp_port,
        &options.url,
        Duration::from_millis(options.timeout_ms),
    )?;
    let mut client = CdpClient::connect(&ws_url)?;
    client.send("Runtime.enable", json!({}))?;
    client.send("Log.enable", json!({}))?;
    client.send("Page.enable", json!({}))?;
    client.send(
        "Emulation.setDeviceMetricsOverride",
        json!({
            "width": options.viewport_width,
            "height": options.viewport_height,
            "deviceScaleFactor": 1,
            "mobile": false
        }),
    )?;

    let deadline = Instant::now() + Duration::from_millis(options.timeout_ms);
    let mut last_status = None;
    while Instant::now() < deadline {
        client.drain_events(Duration::from_millis(25))?;
        if !client.errors.is_empty() {
            return Err(anyhow!(
                "browser reported errors:\n{}",
                client.errors.join("\n")
            ));
        }
        let status = read_runtime_status(&mut client)?;
        let ready = match options.mode {
            BrowserSmokeMode::Dom => status.ready_dom,
            BrowserSmokeMode::FissionCanvas => status.ready_canvas && status.renderer.is_some(),
        };
        if ready {
            if let Some(path) = &options.screenshot_path {
                capture_screenshot(&mut client, path)?;
            }
            let report = BrowserSmokeReport {
                url: options.url.clone(),
                title: status.title,
                width: status.width,
                height: status.height,
                renderer: status.renderer,
                body_text_len: status.body_text_len,
                screenshot_path: options.screenshot_path.clone(),
            };
            session.kill();
            return Ok(report);
        }
        last_status = Some(status);
        std::thread::sleep(Duration::from_millis(100));
    }
    Err(anyhow!(
        "browser smoke test timed out for {}; last status: {:?}",
        options.url,
        last_status
    ))
}

#[cfg(not(target_arch = "wasm32"))]
#[derive(Debug, Deserialize)]
struct RuntimeStatus {
    ready_dom: bool,
    ready_canvas: bool,
    title: String,
    width: u32,
    height: u32,
    body_text_len: usize,
    renderer: Option<String>,
}

#[cfg(not(target_arch = "wasm32"))]
fn read_runtime_status(client: &mut CdpClient) -> Result<RuntimeStatus> {
    let expression = r#"(() => {
      const body = document.body;
      const canvas = document.querySelector('canvas');
      const rect = canvas ? canvas.getBoundingClientRect() : { width: 0, height: 0 };
      const renderer = globalThis.__FISSION_RENDERER_INFO ?? null;
      return {
        ready_dom: document.readyState === 'complete' && !!body && body.innerText.trim().length > 0,
        ready_canvas: !!canvas && rect.width > 0 && rect.height > 0,
        title: document.title || '',
        width: Math.round(rect.width || window.innerWidth || 0),
        height: Math.round(rect.height || window.innerHeight || 0),
        body_text_len: body ? body.innerText.trim().length : 0,
        renderer: renderer ? renderer.active : null,
      };
    })()"#;
    let result = client.send(
        "Runtime.evaluate",
        json!({ "expression": expression, "returnByValue": true }),
    )?;
    if let Some(details) = result.get("exceptionDetails") {
        return Err(anyhow!("runtime evaluation failed: {details}"));
    }
    let value = result
        .get("result")
        .and_then(|result| result.get("value"))
        .cloned()
        .context("Runtime.evaluate returned no value")?;
    serde_json::from_value(value).context("failed to decode browser runtime status")
}

#[cfg(not(target_arch = "wasm32"))]
fn capture_screenshot(client: &mut CdpClient, path: &PathBuf) -> Result<()> {
    let result = client.send(
        "Page.captureScreenshot",
        json!({ "format": "png", "captureBeyondViewport": true }),
    )?;
    let data = result
        .get("data")
        .and_then(|value| value.as_str())
        .context("Page.captureScreenshot returned no data")?;
    let bytes = base64::engine::general_purpose::STANDARD
        .decode(data)
        .context("Chrome returned invalid screenshot base64")?;
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(path, bytes).with_context(|| format!("failed to write {}", path.display()))
}

#[cfg(not(target_arch = "wasm32"))]
fn wait_for_target(cdp_port: u16, expected_url: &str, timeout: Duration) -> Result<String> {
    let deadline = Instant::now() + timeout;
    let mut last_error = None;
    while Instant::now() < deadline {
        match ureq::get(&format!("http://127.0.0.1:{cdp_port}/json/list")).call() {
            Ok(response) => {
                let targets: Value = response.into_json()?;
                if let Some(target) = targets.as_array().and_then(|items| {
                    items.iter().find(|entry| {
                        entry.get("type").and_then(Value::as_str) == Some("page")
                            && entry
                                .get("url")
                                .and_then(Value::as_str)
                                .is_some_and(|url| url.starts_with(expected_url))
                    })
                }) {
                    if let Some(url) = target.get("webSocketDebuggerUrl").and_then(Value::as_str) {
                        return Ok(url.to_string());
                    }
                }
            }
            Err(error) => last_error = Some(error.to_string()),
        }
        std::thread::sleep(Duration::from_millis(100));
    }
    Err(anyhow!(
        "Chrome CDP target did not become ready for {expected_url}: {}",
        last_error.unwrap_or_else(|| "no matching target".to_string())
    ))
}

#[cfg(not(target_arch = "wasm32"))]
fn free_port() -> u16 {
    TcpListener::bind(("127.0.0.1", 0))
        .expect("failed to allocate local port")
        .local_addr()
        .expect("failed to read local port")
        .port()
}

#[cfg(not(target_arch = "wasm32"))]
struct ChromeSession {
    child: Option<Child>,
    profile_dir: PathBuf,
}

#[cfg(not(target_arch = "wasm32"))]
impl ChromeSession {
    fn launch(chrome: &PathBuf, cdp_port: u16, options: &BrowserTestOptions) -> Result<Self> {
        let profile_dir = std::env::temp_dir().join(format!(
            "fission-cdp-{}-{}",
            std::process::id(),
            SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        fs::create_dir_all(&profile_dir)?;
        let child = Command::new(chrome)
            .arg("--headless=new")
            .arg("--enable-unsafe-webgpu")
            .arg("--no-first-run")
            .arg("--no-default-browser-check")
            .arg(format!("--remote-debugging-port={cdp_port}"))
            .arg(format!("--user-data-dir={}", profile_dir.display()))
            .arg(format!(
                "--window-size={},{}",
                options.viewport_width, options.viewport_height
            ))
            .arg(&options.url)
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .with_context(|| format!("failed to start {}", chrome.display()))?;
        Ok(Self {
            child: Some(child),
            profile_dir,
        })
    }

    fn kill(&mut self) {
        if let Some(mut child) = self.child.take() {
            let _ = child.kill();
            let _ = child.wait();
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl Drop for ChromeSession {
    fn drop(&mut self) {
        self.kill();
        let _ = fs::remove_dir_all(&self.profile_dir);
    }
}

#[cfg(not(target_arch = "wasm32"))]
struct CdpClient {
    socket: tungstenite::WebSocket<tungstenite::stream::MaybeTlsStream<std::net::TcpStream>>,
    next_id: u64,
    backlog: VecDeque<Value>,
    errors: Vec<String>,
}

#[cfg(not(target_arch = "wasm32"))]
impl CdpClient {
    fn connect(ws_url: &str) -> Result<Self> {
        let (mut socket, _) =
            connect(ws_url).context("failed to connect to Chrome CDP websocket")?;
        if let tungstenite::stream::MaybeTlsStream::Plain(stream) = socket.get_mut() {
            stream.set_read_timeout(Some(Duration::from_millis(100)))?;
        }
        Ok(Self {
            socket,
            next_id: 1,
            backlog: VecDeque::new(),
            errors: Vec::new(),
        })
    }

    fn send(&mut self, method: &str, params: Value) -> Result<Value> {
        let id = self.next_id;
        self.next_id += 1;
        self.socket.send(Message::Text(serde_json::to_string(
            &json!({ "id": id, "method": method, "params": params }),
        )?))?;
        let deadline = Instant::now() + Duration::from_secs(15);
        loop {
            if let Some(message) = self.backlog.pop_front() {
                if message.get("id").and_then(Value::as_u64) == Some(id) {
                    return Self::command_result(method, message);
                }
                self.handle_event(&message);
                continue;
            }
            if Instant::now() >= deadline {
                return Err(anyhow!("CDP command timed out: {method}"));
            }
            let message = match self.socket.read() {
                Ok(message) => message,
                Err(tungstenite::Error::Io(error))
                    if matches!(
                        error.kind(),
                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
                    ) =>
                {
                    continue;
                }
                Err(error) => return Err(error.into()),
            };
            let text = match message {
                Message::Text(text) => text,
                Message::Binary(bytes) => String::from_utf8_lossy(&bytes).to_string(),
                Message::Ping(_) | Message::Pong(_) => continue,
                Message::Close(_) => return Err(anyhow!("CDP websocket closed")),
                Message::Frame(_) => continue,
            };
            let value: Value = serde_json::from_str(&text)?;
            if value.get("id").and_then(Value::as_u64) == Some(id) {
                return Self::command_result(method, value);
            }
            self.handle_event(&value);
        }
    }

    fn drain_events(&mut self, budget: Duration) -> Result<()> {
        let deadline = Instant::now() + budget;
        while Instant::now() < deadline {
            match self.socket.read() {
                Ok(Message::Text(text)) => {
                    let value: Value = serde_json::from_str(&text)?;
                    if value.get("id").is_some() {
                        self.backlog.push_back(value);
                    } else {
                        self.handle_event(&value);
                    }
                }
                Ok(Message::Binary(bytes)) => {
                    let value: Value = serde_json::from_slice(&bytes)?;
                    if value.get("id").is_some() {
                        self.backlog.push_back(value);
                    } else {
                        self.handle_event(&value);
                    }
                }
                Ok(Message::Ping(_) | Message::Pong(_) | Message::Frame(_)) => {}
                Ok(Message::Close(_)) => return Err(anyhow!("CDP websocket closed")),
                Err(tungstenite::Error::Io(error))
                    if matches!(
                        error.kind(),
                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
                    ) => {}
                Err(tungstenite::Error::ConnectionClosed) => return Ok(()),
                Err(error) => return Err(error.into()),
            }
        }
        Ok(())
    }

    fn command_result(method: &str, message: Value) -> Result<Value> {
        if let Some(error) = message.get("error") {
            return Err(anyhow!("{method}: {error}"));
        }
        Ok(message.get("result").cloned().unwrap_or_else(|| json!({})))
    }

    fn handle_event(&mut self, message: &Value) {
        match message.get("method").and_then(Value::as_str) {
            Some("Runtime.exceptionThrown") => self.errors.push(format!(
                "runtime exception: {}",
                message
                    .pointer("/params/exceptionDetails/exception/description")
                    .or_else(|| message.pointer("/params/exceptionDetails/text"))
                    .and_then(Value::as_str)
                    .unwrap_or("unknown")
            )),
            Some("Runtime.consoleAPICalled") => {
                let level = message.pointer("/params/type").and_then(Value::as_str);
                if matches!(level, Some("error" | "assert")) {
                    self.errors
                        .push(format!("console.{}: {}", level.unwrap(), message));
                }
            }
            Some("Log.entryAdded") => {
                if message
                    .pointer("/params/entry/level")
                    .and_then(Value::as_str)
                    == Some("error")
                {
                    let text = message
                        .pointer("/params/entry/text")
                        .and_then(Value::as_str)
                        .unwrap_or("unknown browser log error");
                    if !text.contains("/__fission/renderer") {
                        self.errors.push(format!("browser log error: {text}"));
                    }
                }
            }
            _ => {}
        }
    }
}