forked from bytecodealliance/wasm-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.rs
More file actions
272 lines (250 loc) · 8.5 KB
/
Copy pathcli.rs
File metadata and controls
272 lines (250 loc) · 8.5 KB
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
//! A test suite to test the `wasm-tools` CLI itself.
//!
//! This test suite will look for `*.wat` and `*.wit` files in the
//! `tests/cli/**` directory, recursively. For more information about supported
//! directives and features of this test suite see the `tests/cli/readme.wat`
//! file which has an explanatory comment at the top for what's going on.
use anyhow::{Context, Result, bail};
use indexmap::IndexMap;
use libtest_mimic::{Arguments, Trial};
use pretty_assertions::StrComparison;
use std::env;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use tempfile::TempDir;
fn main() {
let mut tests = Vec::new();
find_tests("tests/cli".as_ref(), &mut tests);
let bless = env::var("BLESS").is_ok();
let mut trials = Vec::new();
for test in tests {
let trial = Trial::test(format!("{test:?}"), move || {
run_test(&test, bless)
.with_context(|| format!("failed test {test:?}"))
.map_err(|e| format!("{e:?}").into())
})
// This test suite can't run on wasm since it involves spawning
// subprocesses.
.with_ignored_flag(cfg!(target_family = "wasm"));
trials.push(trial);
}
let mut args = Arguments::from_args();
if cfg!(target_family = "wasm") && !cfg!(target_feature = "atomics") {
args.test_threads = Some(1);
}
libtest_mimic::run(&args, trials).exit();
}
fn run_test(test: &Path, bless: bool) -> Result<()> {
let contents = std::fs::read_to_string(test)?;
let mut directives = contents
.lines()
.enumerate()
.filter(|(_, l)| !l.is_empty())
.filter_map(|(i, l)| {
l.strip_prefix("// ")
.or(l.strip_prefix(";; "))
.map(|l| (i + 1, l))
});
let mut commands = IndexMap::new();
while let Some((i, line)) = directives.next() {
let run = line.strip_prefix("RUN");
let fail = line.strip_prefix("FAIL");
let (directive, should_fail) = match run.map(|l| (l, false)).or(fail.map(|l| (l, true))) {
Some(pair) => pair,
None => continue,
};
let (cmd, name) = match directive.strip_prefix("[") {
Some(prefix) => match prefix.find("]:") {
Some(i) => (&prefix[i + 2..], &prefix[..i]),
None => bail!("line {i}: failed to find `]:` after `[`"),
},
None => match directive.strip_prefix(":") {
Some(cmd) => (cmd, ""),
None => bail!("line {i}: failed to find `:` after `RUN` or `FAIL`"),
},
};
let mut cmd = cmd.to_string();
while cmd.ends_with("\\") {
cmd.pop();
match directives.next() {
Some((_, line)) => cmd.push_str(line),
None => bail!("line {i}: directive ends in `\\` but nothing on next line"),
}
}
match commands.insert(name, (cmd, should_fail, i)) {
Some(_) => bail!("line {i}: duplicate directive named {name:?}"),
None => {}
}
}
if commands.is_empty() {
bail!("failed to find `// RUN: ...` or `// FAIL: ...` at the top of this file");
}
let exe = Path::new(env!("CARGO_BIN_EXE_wasm-tools"));
let tempdir = TempDir::new_in(exe.parent().unwrap())?;
for (name, (line, should_fail, i)) in commands {
run_test_directive(test, &name, &line, bless, should_fail, exe, &tempdir).with_context(
|| {
let kind = if should_fail { "FAIL" } else { "RUN" };
format!("failed {kind} directive `{name}` on line {i}")
},
)?;
}
Ok(())
}
fn run_test_directive(
test: &Path,
name: &str,
line: &str,
bless: bool,
should_fail: bool,
exe: &Path,
tempdir: &TempDir,
) -> Result<()> {
let mut cmd = Command::new(exe);
let mut stdin = None;
for arg in line.split_whitespace() {
let arg = arg.replace("%tmpdir", tempdir.path().to_str().unwrap());
if arg == "|" {
let output = execute(&mut cmd, stdin.as_deref(), false)?;
stdin = Some(output.stdout);
cmd = Command::new(exe);
} else if arg == "%" {
cmd.arg(test);
} else {
cmd.arg(arg);
}
}
let output = execute(&mut cmd, stdin.as_deref(), should_fail)?;
let extension = test.extension().unwrap().to_str().unwrap();
let extension = if name.is_empty() {
extension.to_string()
} else {
format!("{extension}.{name}")
};
assert_output(
bless,
&output.stdout,
&test.with_extension(&format!("{extension}.stdout")),
&tempdir,
)
.context("failed to check stdout expectation (auto-update with BLESS=1)")?;
assert_output(
bless,
&output.stderr,
&test.with_extension(&format!("{extension}.stderr")),
&tempdir,
)
.context("failed to check stderr expectation (auto-update with BLESS=1)")?;
Ok(())
}
fn execute(cmd: &mut Command, stdin: Option<&[u8]>, should_fail: bool) -> Result<Output> {
cmd.stdin(Stdio::piped());
cmd.stdout(Stdio::piped());
cmd.stderr(Stdio::piped());
let mut p = cmd
.env("COLUMNS", "80")
.spawn()
.with_context(|| format!("failed to spawn {cmd:?}"))?;
let mut io = p.stdin.take().unwrap();
if let Some(stdin) = stdin {
io.write_all(stdin).context("failed to write to stdin")?;
}
drop(io);
let output = p
.wait_with_output()
.context("failed to wait for process exit")?;
let mut failure = None;
match output.status.code() {
Some(0) => {
if should_fail {
failure = Some("succeeded instead of failed");
}
}
Some(1) | Some(2) => {
if !should_fail {
failure = Some("failed");
}
}
_ => failure = Some("unknown exit code"),
}
if let Some(msg) = failure {
bail!(
"{cmd:?} {msg}:
status: {}
stdout: {}
stderr: {}",
output.status,
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
}
Ok(output)
}
fn assert_output(bless: bool, output: &[u8], path: &Path, tempdir: &TempDir) -> Result<()> {
let tempdir = tempdir.path().to_str().unwrap();
// sanitize the output to be consistent across platforms and handle per-test
// differences such as `%tmpdir`, as well as the version number of the crate being
// tested in the producers custom section.
let mut output = String::from_utf8_lossy(output)
.replace(tempdir, "%tmpdir")
.replace("\\", "/")
.replace("wasm-tools.exe", "wasm-tools")
.lines()
.map(|line| {
if let Some(start) = line.find("(processed-by \"wit-component\"") {
let (before, _) = line.split_at(start);
format!("{before}(processed-by \"wit-component\" \"%version\")")
} else {
line.to_owned()
}
})
.collect::<Vec<String>>()
.join("\n")
.trim_end()
.to_string();
// Leave a single trailing newline on all test outputs
if !output.is_empty() {
output.push_str("\n");
}
if bless {
if output.is_empty() {
drop(std::fs::remove_file(path));
} else {
std::fs::write(path, output).with_context(|| format!("failed to write {path:?}"))?;
}
return Ok(());
}
if output.is_empty() {
if path.exists() {
bail!("command had no output but {path:?} exists");
} else {
Ok(())
}
} else {
let contents = std::fs::read_to_string(path)
.with_context(|| format!("failed to read {path:?}"))?
.replace("\r\n", "\n");
if output != contents {
bail!(
"failed test: result is not as expected:{}",
StrComparison::new(&contents, &output),
);
}
Ok(())
}
}
fn find_tests(path: &Path, tests: &mut Vec<PathBuf>) {
for f in path.read_dir().unwrap() {
let f = f.unwrap();
if f.file_type().unwrap().is_dir() {
find_tests(&f.path(), tests);
continue;
}
match f.path().extension().and_then(|s| s.to_str()) {
Some("wat") | Some("wit") | Some("wast") => {}
_ => continue,
}
tests.push(f.path());
}
}