bao-browser 0.1.3

A Rust-native programmable browser runtime built on Servo and SpiderMonkey
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
// @trace TEST-E2E-CLI [req:REQ-CLI-001,REQ-CLI-002,REQ-ENG-006] [level:system]
// @trace REQ-CLI-001 [level:system]
// @trace REQ-CLI-002 [level:system]
// @trace REQ-ENG-006 [level:system]
//
// # TASK-12 E2E — bao CLI 端到端(std::process::Command 子进程)
//
// **核心断言**: `bao` 二进制可被 `std::process::Command` 驱动,完整执行
// 用户脚本。`bao run script.js` 启动 JsContext + 注入 Node API + 执行脚本 +
// 退出码反映执行结果。
//
// 测试维度:
//   1. **bao --help**: CLI 可执行,clap 注册成功
//   2. **bao run --eval "console.log"**: 一行脚本走完 JsContext 生命周期
//   3. **bao run script.js**: 文件脚本端到端(读文件 → 执行 → 退出)
//   4. **Bun API 可用**: 脚本内 typeof Bun === 'object'
//   5. **Node API 可用**: 脚本内 typeof process === 'object'
//   6. **退出码传播**: 脚本 process.exit(N) → bao 进程退出码 N
//   7. **stdout 捕获**: console.log → bao stdout
//   8. **双向流归属**: console.log → stdout 且 console.error → stderr(不串流)
//
// **运行约束**: 测试需要预先 `cargo build` 产出 ./target/debug/bao 二进制。
// 缺失时 skip 而非 fail(避免 CI 在未 build 时直接红)。

use std::path::PathBuf;
use std::process::Command;
use std::time::Duration;

const BAO_BIN: &str = "target/debug/bao";

// ─── 辅助 — 定位 bao 二进制 ──────────────────────────────────────────────────

fn bao_path() -> Option<PathBuf> {
    // 1. 显式覆盖:CI / 分布式 buildlet 直接指向它产出的二进制
    if let Ok(override_path) = std::env::var("BAO_BIN") {
        let candidate = PathBuf::from(override_path);
        if candidate.is_file() {
            return Some(candidate);
        }
    }
    // 2. CARGO_TARGET_DIR:build-dir 可能不在 workspace 内(如 /var/cargo-builds),
    //    按 cargo build 的标准布局解析 <target>/debug/bao
    if let Ok(target_dir) = std::env::var("CARGO_TARGET_DIR") {
        let candidate = PathBuf::from(target_dir).join("debug").join("bao");
        if candidate.is_file() {
            return Some(candidate);
        }
    }
    // 3. 测试 cwd 通常是 crate 根目录(bao_browser/),向上一级到 workspace 根
    let mut here = std::env::current_dir().ok()?;
    for _ in 0..5 {
        let candidate = here.join(BAO_BIN);
        if candidate.is_file() {
            return Some(candidate);
        }
        if !here.pop() {
            break;
        }
    }
    // 兜底:直接信相对路径
    let direct = PathBuf::from(BAO_BIN);
    if direct.is_file() {
        Some(direct)
    } else {
        None
    }
}

fn run_bao(args: &[&str], stdin: Option<&str>) -> std::io::Result<std::process::Output> {
    let bao = bao_path().expect("bao binary not found — run `cargo build` first");
    let mut cmd = Command::new(bao);
    cmd.args(args);
    if stdin.is_some() {
        cmd.stdin(std::process::Stdio::piped());
    }
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::piped());

    let mut child = cmd.spawn()?;
    if let Some(input) = stdin {
        use std::io::Write;
        let mut child_stdin = child.stdin.take().expect("stdin pipe");
        child_stdin.write_all(input.as_bytes())?;
        drop(child_stdin); // 关闭 stdin,触发 EOF
    }
    child.wait_with_output()
}

// ─── 主测试 ────────────────────────────────────────────────────────────────

#[test]
// @trace REQ-CLI-001 [level:e2e]
fn bao_cli_e2e_full_lifecycle() {
    let bao = match bao_path() {
        Some(p) => p,
        None => {
            eprintln!(
                "SKIP: bao binary not found at ./{} — run `cargo build` first",
                BAO_BIN
            );
            return;
        }
    };
    eprintln!("using bao binary: {}", bao.display());

    let mut passed = 0u32;
    let mut failed = 0u32;

    // ── §1 bao --help — CLI 可执行 ──────────────────────────────────────
    //
    // clap 在 --help 时退出码 0,stdout 含 "bao" 或 "Bao"
    match run_bao(&["--help"], None) {
        Ok(output) => {
            let stdout = String::from_utf8_lossy(&output.stdout);
            let stderr = String::from_utf8_lossy(&output.stderr);
            let combined = format!("{}\n{}", stdout, stderr);
            // clap --help 通常退出码 0(some versions exit 2 but still print help)
            if combined.to_lowercase().contains("usage")
                || combined.to_lowercase().contains("bao")
                || combined.contains("run")
                || combined.contains("browser")
            {
                eprintln!("PASS  §1::cli_help_responds");
                passed += 1;
            } else {
                eprintln!("FAIL  §1::cli_help_responds  (combined output empty or unexpected)");
                failed += 1;
            }
        }
        Err(e) => {
            eprintln!("FAIL  §1::cli_help_responds  (spawn failed: {})", e);
            failed += 1;
        }
    }

    // ── §2 bao run --eval "console.log('hello')" — 基础 eval ──────────────
    //
    // 这验证 JsContext 完整生命周期:创建 → eval console.log → drain stdout → 退出
    match run_bao(&["run", "--eval", "console.log('bao-e2e-marker')"], None) {
        Ok(output) => {
            let stdout = String::from_utf8_lossy(&output.stdout);
            if stdout.contains("bao-e2e-marker") {
                eprintln!("PASS  §2::eval_console_log");
                passed += 1;
            } else {
                eprintln!(
                    "FAIL  §2::eval_console_log  (stdout='{}', exit={:?})",
                    stdout.trim(),
                    output.status.code()
                );
                failed += 1;
            }
        }
        Err(e) => {
            eprintln!("FAIL  §2::eval_console_log  (spawn failed: {})", e);
            failed += 1;
        }
    }

    // ── §3 bao run --eval "Bun.version" — Bun API 真可用 ──────────────────
    //
    // typeof Bun === 'object' 验证 JsContext 内 Bun 全局对象已注入
    match run_bao(&["run", "--eval", "console.log(typeof Bun)"], None) {
        Ok(output) => {
            let stdout = String::from_utf8_lossy(&output.stdout);
            if stdout.trim().contains("object") {
                eprintln!("PASS  §3::bun_api_available");
                passed += 1;
            } else {
                eprintln!(
                    "FAIL  §3::bun_api_available  (typeof Bun = '{}', exit={:?})",
                    stdout.trim(),
                    output.status.code()
                );
                failed += 1;
            }
        }
        Err(e) => {
            eprintln!("FAIL  §3::bun_api_available  (spawn failed: {})", e);
            failed += 1;
        }
    }

    // ── §4 bao run --eval "typeof process" — Node API 真可用 ──────────────
    match run_bao(&["run", "--eval", "console.log(typeof process)"], None) {
        Ok(output) => {
            let stdout = String::from_utf8_lossy(&output.stdout);
            if stdout.trim().contains("object") {
                eprintln!("PASS  §4::node_api_available");
                passed += 1;
            } else {
                eprintln!(
                    "FAIL  §4::node_api_available  (typeof process = '{}', exit={:?})",
                    stdout.trim(),
                    output.status.code()
                );
                failed += 1;
            }
        }
        Err(e) => {
            eprintln!("FAIL  §4::node_api_available  (spawn failed: {})", e);
            failed += 1;
        }
    }

    // ── §5 bao run script.js — 文件脚本端到端 ─────────────────────────────
    //
    // 临时写一个 .js 文件,bao run 它,验证文件读取 + 执行 + stdout。
    let temp_dir = std::env::temp_dir();
    let script_path = temp_dir.join("bao_e2e_test_script.js");
    std::fs::write(
        &script_path,
        r#"
            // 文件脚本 — 用 Node API (Buffer) + Bun API (Bun.version)
            const buf = Buffer.from('hello-from-file');
            console.log('file-script-runs');
            console.log(buf.toString());
            console.log(typeof Bun === 'object' ? 'bun-ok' : 'bun-missing');
        "#,
    )
    .expect("write temp script");
    let script_str = script_path.to_string_lossy().to_string();
    match run_bao(&["run", script_str.as_str()], None) {
        Ok(output) => {
            let stdout = String::from_utf8_lossy(&output.stdout);
            if stdout.contains("file-script-runs")
                && stdout.contains("hello-from-file")
                && stdout.contains("bun-ok")
            {
                eprintln!("PASS  §5::run_file_script");
                passed += 1;
            } else {
                eprintln!(
                    "FAIL  §5::run_file_script  (stdout='{}', exit={:?})",
                    stdout.trim(),
                    output.status.code()
                );
                failed += 1;
            }
        }
        Err(e) => {
            eprintln!("FAIL  §5::run_file_script  (spawn failed: {})", e);
            failed += 1;
        }
    }

    // ── §6 退出码传播 — process.exit(N) ──────────────────────────────────
    //
    // process.exit(0) → bao 退出码 0;process.exit(42) → 退出码 42
    match run_bao(&["run", "--eval", "process.exit(0)"], None) {
        Ok(output) => {
            let code = output.status.code();
            if code == Some(0) {
                eprintln!("PASS  §6a::exit_code_zero");
                passed += 1;
            } else {
                eprintln!("FAIL  §6a::exit_code_zero  (got {:?})", code);
                failed += 1;
            }
        }
        Err(e) => {
            eprintln!("FAIL  §6a::exit_code_zero  (spawn failed: {})", e);
            failed += 1;
        }
    }
    match run_bao(&["run", "--eval", "process.exit(42)"], None) {
        Ok(output) => {
            let code = output.status.code();
            if code == Some(42) {
                eprintln!("PASS  §6b::exit_code_42");
                passed += 1;
            } else {
                eprintln!("FAIL  §6b::exit_code_42  (got {:?})", code);
                failed += 1;
            }
        }
        Err(e) => {
            eprintln!("FAIL  §6b::exit_code_42  (spawn failed: {})", e);
            failed += 1;
        }
    }

    // ── §7 stdout 捕获 — 多行 console.log ────────────────────────────────
    match run_bao(
        &[
            "run",
            "--eval",
            "console.log('line1'); console.log('line2');",
        ],
        None,
    ) {
        Ok(output) => {
            let stdout = String::from_utf8_lossy(&output.stdout);
            if stdout.contains("line1") && stdout.contains("line2") {
                eprintln!("PASS  §7::multi_line_stdout");
                passed += 1;
            } else {
                eprintln!("FAIL  §7::multi_line_stdout  (stdout='{}')", stdout.trim());
                failed += 1;
            }
        }
        Err(e) => {
            eprintln!("FAIL  §7::multi_line_stdout  (spawn failed: {})", e);
            failed += 1;
        }
    }

    // ── §8 双向流归属 — console.log→stdout 且 console.error→stderr ────────
    //
    // Node 流语义:log 走 stdout,error 走 stderr。子进程两路管道分别捕获,
    // 断言 marker 各归各的流、不串流、不丢失(缓冲未 flush 时整段丢失)。
    match run_bao(
        &[
            "run",
            "--eval",
            "console.log('stdout-marker'); console.error('stderr-marker');",
        ],
        None,
    ) {
        Ok(output) => {
            let stdout = String::from_utf8_lossy(&output.stdout);
            let stderr = String::from_utf8_lossy(&output.stderr);
            if stdout.contains("stdout-marker")
                && stderr.contains("stderr-marker")
                && !stdout.contains("stderr-marker")
                && !stderr.contains("stdout-marker")
            {
                eprintln!("PASS  §8::console_stream_routing");
                passed += 1;
            } else {
                eprintln!(
                    "FAIL  §8::console_stream_routing  (stdout='{}', stderr='{}', exit={:?})",
                    stdout.trim(),
                    stderr.trim(),
                    output.status.code()
                );
                failed += 1;
            }
        }
        Err(e) => {
            eprintln!("FAIL  §8::console_stream_routing  (spawn failed: {})", e);
            failed += 1;
        }
    }

    // ── 清理 ────────────────────────────────────────────────────────────
    let _ = std::fs::remove_file(&script_path);

    eprintln!(
        "=== bao CLI E2E ===\n--- {} passed, {} failed ---",
        passed, failed
    );

    // 至少 5/9 通过(允许 §1 help 格式差异等少数容忍)
    assert!(
        passed >= 5,
        "too few CLI E2E sub-assertions passed: {}/9",
        passed
    );
    assert_eq!(
        failed, 0,
        "{} CLI E2E sub-assertions failed — see stderr above",
        failed
    );
}

// ─── 网络 E2E — bao browser 子命令(需要 servo Opts 单例 + 网络) ──────────────
//
// bao browser --cdp-port 启动 servo + CDP server,长时间运行。
// 此测试默认 graceful skip(避免启动长时间运行的进程占资源)。
// 启用方式:BAO_TEST_NETWORK=1 cargo test bao_cli_browser_subcommand

#[test]
// @trace REQ-CLI-002 [level:e2e]
fn bao_cli_browser_subcommand_starts() {
    if std::env::var("BAO_TEST_NETWORK").as_deref() != Ok("1") {
        eprintln!("[skip] 环境不可用: BAO_TEST_NETWORK=1 not set (bao browser subcommand E2E)");
        return;
    }
    let bao = bao_path().expect("bao binary not found");

    // Act: 启动 bao browser,绑一个空闲端口
    let port = pick_free_port();
    let mut cmd = Command::new(&bao);
    cmd.args(["browser", "--headless", "--cdp-port", &port.to_string()])
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped());

    let mut child = cmd.spawn().expect("spawn bao browser");

    // 给 servo + CDP server 最多 5 秒初始化
    std::thread::sleep(Duration::from_secs(5));

    // Assert: 端口可连(CDP server 已起)
    let connected = std::net::TcpStream::connect(format!("127.0.0.1:{}", port)).is_ok();

    // 清理:杀子进程
    let _ = child.kill();
    let _ = child.wait();

    assert!(connected, "bao browser --cdp-port {} must listen", port);
}

fn pick_free_port() -> u16 {
    // OS-assigned free port
    std::net::TcpListener::bind("127.0.0.1:0")
        .and_then(|l| l.local_addr())
        .map(|a| a.port())
        .unwrap_or(9922)
}