1
//! Meta-test that runs the WASM frontend tests in headless Chromium.
2
//!
3
//! It spawns `wasm-pack test` as a subprocess so the browser tests run as part
4
//! of `cargo test --workspace`. A missing tool fails the test: a skip would
5
//! report green for tests that never ran.
6

            
7
use std::io::ErrorKind;
8
use std::path::Path;
9
use std::process::{Command, Stdio};
10

            
11
use tempfile::TempDir;
12

            
13
const CHROME_BINARIES: &[&str] = &[
14
    "chromium",
15
    "chromium-browser",
16
    "google-chrome",
17
    "google-chrome-stable",
18
];
19

            
20
enum Probe {
21
    Missing,
22
    Broken,
23
    Working(String),
24
}
25

            
26
7
fn probe(cmd: &str) -> Probe {
27
7
    match Command::new(cmd)
28
7
        .arg("--version")
29
7
        .stderr(Stdio::null())
30
7
        .output()
31
    {
32
3
        Err(err) if err.kind() == ErrorKind::NotFound => Probe::Missing,
33
4
        Ok(out) if out.status.success() => {
34
4
            Probe::Working(String::from_utf8_lossy(&out.stdout).into_owned())
35
        }
36
        _ => Probe::Broken,
37
    }
38
7
}
39

            
40
2
fn tool_problem(name: &str, probe: Probe) -> Option<String> {
41
2
    match probe {
42
        Probe::Missing => Some(format!("{name} (missing)")),
43
        Probe::Broken => Some(format!("{name} (present but not working)")),
44
2
        Probe::Working(_) => None,
45
    }
46
2
}
47

            
48
1
fn chrome_problem() -> Option<String> {
49
1
    let probes: Vec<(&str, Probe)> = CHROME_BINARIES
50
1
        .iter()
51
4
        .map(|cmd| (*cmd, probe(cmd)))
52
        .collect();
53
1
    if probes.iter().any(|(_, p)| matches!(p, Probe::Working(_))) {
54
1
        return None;
55
    }
56
    match probes.into_iter().find(|(_, p)| matches!(p, Probe::Broken)) {
57
        Some((cmd, broken)) => tool_problem(cmd, broken),
58
        None => Some(format!(
59
            "a Chrome browser ({}) (missing)",
60
            CHROME_BINARIES.join(" / ")
61
        )),
62
    }
63
1
}
64

            
65
1
fn tool_problems() -> Vec<String> {
66
1
    [
67
1
        tool_problem("wasm-pack", probe("wasm-pack")),
68
1
        tool_problem("chromedriver", probe("chromedriver")),
69
1
        chrome_problem(),
70
1
    ]
71
1
    .into_iter()
72
1
    .flatten()
73
1
    .collect()
74
1
}
75

            
76
/// The `wasm-bindgen` version `Cargo.lock` resolves.
77
2
fn locked_wasm_bindgen(lockfile: &str) -> Option<&str> {
78
2
    lockfile
79
2
        .split("[[package]]")
80
614
        .find(|package| package.contains("name = \"wasm-bindgen\"\n"))
81
2
        .and_then(|package| {
82
2
            package
83
2
                .lines()
84
6
                .find_map(|line| line.strip_prefix("version = "))
85
2
        })
86
2
        .map(|version| version.trim_matches('"'))
87
2
}
88

            
89
/// A `wasm-bindgen` on PATH is used by wasm-pack as is, so it must match the
90
/// lockfile; without one wasm-pack downloads the right version.
91
1
fn check_wasm_bindgen(lock_path: &Path) -> Result<(), String> {
92
1
    let lockfile = std::fs::read_to_string(lock_path)
93
        .map_err(|err| format!("cannot read {}: {err}", lock_path.display()))?;
94
1
    let wanted = locked_wasm_bindgen(&lockfile)
95
        .ok_or_else(|| format!("no wasm-bindgen package in {}", lock_path.display()))?;
96
1
    match probe("wasm-bindgen") {
97
        Probe::Missing => Ok(()),
98
        Probe::Broken => Err("wasm-bindgen on PATH is present but not working".to_owned()),
99
1
        Probe::Working(out) => match out.split_whitespace().nth(1) {
100
1
            Some(found) if found == wanted => Ok(()),
101
            found => Err(format!(
102
                "wasm-bindgen-cli {} on PATH, Cargo.lock wants {wanted}: rebuild the builder image",
103
                found.unwrap_or("of unknown version")
104
            )),
105
        },
106
    }
107
1
}
108

            
109
/// The runner's own defaults (5 s for chromedriver to bind its port, 20 s for a
110
/// test binary) are too tight on a loaded machine; these are ceilings, so a
111
/// healthy run waits no longer.
112
const RUNNER_LIMITS: [(&str, &str); 2] = [
113
    ("WASM_BINDGEN_TEST_DRIVER_TIMEOUT", "60"),
114
    ("WASM_BINDGEN_TEST_TIMEOUT", "120"),
115
];
116

            
117
2
fn wasm_pack_test(frontend_dir: &Path, tmp: &Path) -> Command {
118
2
    let mut command = Command::new("wasm-pack");
119
2
    command
120
2
        .args([
121
2
            "test",
122
2
            "--headless",
123
2
            "--chrome",
124
2
            "--",
125
2
            "--no-default-features",
126
2
        ])
127
2
        .current_dir(frontend_dir)
128
2
        .env("TMPDIR", tmp)
129
2
        .env_remove("RUSTFLAGS")
130
2
        .env_remove("CARGO_ENCODED_RUSTFLAGS")
131
2
        .env_remove("LLVM_PROFILE_FILE")
132
2
        .envs(RUNNER_LIMITS);
133
2
    command
134
2
}
135

            
136
#[test]
137
1
fn wasm_frontend_behavior_tests() -> Result<(), String> {
138
1
    let problems = tool_problems();
139
1
    if !problems.is_empty() {
140
        return Err(format!(
141
            "WASM frontend tests cannot run: {}",
142
            problems.join(", ")
143
        ));
144
1
    }
145
1
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
146
1
    check_wasm_bindgen(&manifest_dir.join("../Cargo.lock"))?;
147

            
148
1
    let frontend_dir = manifest_dir.join("frontend");
149

            
150
    // The child builds for wasm32-unknown-unknown, which has no profiler
151
    // runtime, so the coverage job's host flags and profile path must not reach
152
    // it. Its `--target` build already bypasses xtask's instrumenting wrapper.
153
1
    let tmp = TempDir::new().map_err(|err| format!("cannot create a private TMPDIR: {err}"))?;
154
1
    let status = wasm_pack_test(&frontend_dir, tmp.path())
155
1
        .status()
156
        .map_err(|err| format!("cannot execute wasm-pack: {err}"))?;
157

            
158
1
    status
159
1
        .success()
160
1
        .then_some(())
161
        .ok_or_else(|| format!("WASM frontend tests failed: wasm-pack exited with {status}"))
162
1
}
163

            
164
#[test]
165
1
fn locked_wasm_bindgen_ignores_similarly_named_packages() {
166
1
    let lockfile = "[[package]]\nname = \"wasm-bindgen-test\"\nversion = \"0.3.79\"\n\n\
167
1
                    [[package]]\nname = \"wasm-bindgen\"\nversion = \"0.2.129\"\n";
168
1
    assert_eq!(locked_wasm_bindgen(lockfile), Some("0.2.129"));
169
1
}
170

            
171
#[test]
172
1
fn the_runner_gets_loaded_machine_limits() {
173
1
    let command = wasm_pack_test(Path::new("."), Path::new("/tmp"));
174
1
    let envs: Vec<_> = command.get_envs().collect();
175
1
    for (name, value) in RUNNER_LIMITS {
176
2
        let found = envs
177
2
            .iter()
178
11
            .find(|(key, _)| *key == name)
179
2
            .and_then(|(_, v)| *v);
180
2
        assert_eq!(found, Some(std::ffi::OsStr::new(value)), "{name}");
181
    }
182
1
}