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
use crate::{sandbox::utils::module, DEFAULT_BUILD_DIR, DEFAULT_STORAGE_DIR};
use move_command_line_common::{
env::read_bool_env_var,
files::{find_filenames, path_to_string},
testing::{format_diff, read_env_update_baseline, EXP_EXT},
};
use move_compiler::command_line::COLOR_MODE_ENV_VAR;
use move_coverage::coverage_map::{CoverageMap, ExecCoverageMapWithModules};
use move_package::{
compilation::{compiled_package::OnDiskCompiledPackage, package_layout::CompiledPackageLayout},
resolution::resolution_graph::ResolvedGraph,
source_package::{layout::SourcePackageLayout, manifest_parser::parse_move_manifest_from_file},
BuildConfig,
};
use std::{
collections::{BTreeMap, HashMap},
env,
fs::{self, File},
io::{self, BufRead, Write},
path::{Path, PathBuf},
process::Command,
};
use tempfile::tempdir;
const NO_MOVE_CLEAN: &str = "NO_MOVE_CLEAN";
pub const TEST_ARGS_FILENAME: &str = "args.txt";
const MOVE_VM_TRACING_ENV_VAR_NAME: &str = "MOVE_VM_TRACE";
const DEFAULT_TRACE_FILE: &str = "trace";
fn collect_coverage(
trace_file: &Path,
build_dir: &Path,
) -> anyhow::Result<ExecCoverageMapWithModules> {
let canonical_build = build_dir.canonicalize().unwrap();
let package_name = parse_move_manifest_from_file(
&SourcePackageLayout::try_find_root(&canonical_build).unwrap(),
)?
.package
.name
.to_string();
let pkg = OnDiskCompiledPackage::from_path(
&build_dir
.join(package_name)
.join(CompiledPackageLayout::BuildInfo.path()),
)?
.into_compiled_package()?;
let src_modules = pkg
.all_modules()
.map(|unit| {
let absolute_path = path_to_string(&unit.source_path.canonicalize()?)?;
Ok((absolute_path, module(&unit.unit)?.clone()))
})
.collect::<anyhow::Result<HashMap<_, _>>>()?;
let mut filter = BTreeMap::new();
for (entry, module) in src_modules.into_iter() {
let module_id = module.self_id();
filter
.entry(*module_id.address())
.or_insert_with(BTreeMap::new)
.insert(module_id.name().to_owned(), (entry, module));
}
let coverage_map = CoverageMap::from_trace_file(trace_file)
.to_unified_exec_map()
.into_coverage_map_with_modules(filter);
Ok(coverage_map)
}
fn determine_package_nest_depth(
resolution_graph: &ResolvedGraph,
pkg_dir: &Path,
) -> anyhow::Result<usize> {
let mut depth = 0;
for (_, dep) in resolution_graph.package_table.iter() {
depth = std::cmp::max(
depth,
dep.package_path.strip_prefix(pkg_dir)?.components().count() + 1,
);
}
Ok(depth)
}
fn pad_tmp_path(tmp_dir: &Path, pad_amount: usize) -> anyhow::Result<PathBuf> {
let mut tmp_dir = tmp_dir.to_path_buf();
for i in 0..pad_amount {
tmp_dir.push(format!("{}", i));
}
std::fs::create_dir_all(&tmp_dir)?;
Ok(tmp_dir)
}
fn copy_deps(tmp_dir: &Path, pkg_dir: &Path) -> anyhow::Result<PathBuf> {
let package_resolution = match (BuildConfig {
dev_mode: true,
..Default::default()
})
.resolution_graph_for_package(pkg_dir)
{
Ok(pkg) => pkg,
Err(_) => return Ok(tmp_dir.to_path_buf()),
};
let package_nest_depth = determine_package_nest_depth(&package_resolution, pkg_dir)?;
let tmp_dir = pad_tmp_path(tmp_dir, package_nest_depth)?;
for (_, dep) in package_resolution.package_table.iter() {
let source_dep_path = &dep.package_path;
let dest_dep_path = tmp_dir.join(&dep.package_path.strip_prefix(pkg_dir).unwrap());
if !dest_dep_path.exists() {
fs::create_dir_all(&dest_dep_path)?;
}
simple_copy_dir(&dest_dep_path, source_dep_path)?;
}
Ok(tmp_dir)
}
fn simple_copy_dir(dst: &Path, src: &Path) -> io::Result<()> {
for entry in fs::read_dir(src)? {
let src_entry = entry?;
let src_entry_path = src_entry.path();
let dst_entry_path = dst.join(src_entry.file_name());
if src_entry_path.is_dir() {
fs::create_dir_all(&dst_entry_path)?;
simple_copy_dir(&dst_entry_path, &src_entry_path)?;
} else {
fs::copy(&src_entry_path, &dst_entry_path)?;
}
}
Ok(())
}
pub fn run_one(
args_path: &Path,
cli_binary: &Path,
use_temp_dir: bool,
track_cov: bool,
) -> anyhow::Result<Option<ExecCoverageMapWithModules>> {
let args_file = io::BufReader::new(File::open(args_path)?).lines();
let cli_binary_path = cli_binary.canonicalize()?;
let exe_dir = args_path.parent().unwrap();
let temp_dir = if use_temp_dir {
let dir = tempdir()?;
let padded_dir = copy_deps(dir.path(), exe_dir)?;
simple_copy_dir(&padded_dir, exe_dir)?;
Some((dir, padded_dir))
} else {
None
};
let wks_dir = temp_dir.as_ref().map_or(exe_dir, |t| &t.1);
let storage_dir = wks_dir.join(DEFAULT_STORAGE_DIR);
let build_output = wks_dir
.join(DEFAULT_BUILD_DIR)
.join(CompiledPackageLayout::Root.path());
let cli_command_template = || {
let mut command = Command::new(cli_binary_path.clone());
if let Some(work_dir) = temp_dir.as_ref() {
command.current_dir(&work_dir.1);
} else {
command.current_dir(exe_dir);
}
command
};
if storage_dir.exists() || build_output.exists() {
cli_command_template()
.arg("sandbox")
.arg("clean")
.output()?;
}
let mut output = "".to_string();
let trace_file = if track_cov {
Some(wks_dir.canonicalize()?.join(DEFAULT_TRACE_FILE))
} else {
None
};
env::set_var(COLOR_MODE_ENV_VAR, "NONE");
for args_line in args_file {
let args_line = args_line?;
if let Some(external_cmd) = args_line.strip_prefix(">") {
let external_cmd = external_cmd.trim_start();
let mut cmd_iter = external_cmd.split_ascii_whitespace();
let external_program = cmd_iter.next().expect("empty external command");
let mut command = Command::new(external_program);
command.args(cmd_iter);
if let Some(work_dir) = temp_dir.as_ref() {
command.current_dir(&work_dir.1);
} else {
command.current_dir(exe_dir);
}
let cmd_output = command.output()?;
output += &format!("External Command `{}`:\n", external_cmd);
output += std::str::from_utf8(&cmd_output.stdout)?;
output += std::str::from_utf8(&cmd_output.stderr)?;
continue;
}
if args_line.starts_with('#') {
continue;
}
let args_iter: Vec<&str> = args_line.split_whitespace().collect();
if args_iter.is_empty() {
continue;
}
match &trace_file {
None => {
env::remove_var(MOVE_VM_TRACING_ENV_VAR_NAME);
}
Some(path) => env::set_var(MOVE_VM_TRACING_ENV_VAR_NAME, path.as_os_str()),
}
let cmd_output = cli_command_template().args(args_iter).output()?;
output += &format!("Command `{}`:\n", args_line);
output += std::str::from_utf8(&cmd_output.stdout)?;
output += std::str::from_utf8(&cmd_output.stderr)?;
}
let cov_info = match &trace_file {
None => None,
Some(trace_path) => {
if trace_path.exists() {
Some(collect_coverage(trace_path, &build_output)?)
} else {
eprintln!(
"Trace file {:?} not found: coverage is only available with at least one `run` \
command in the args.txt (after a `clean`, if there is one)",
trace_path
);
None
}
}
};
let run_move_clean = !read_bool_env_var(NO_MOVE_CLEAN);
if run_move_clean {
cli_command_template()
.arg("sandbox")
.arg("clean")
.output()?;
assert!(
!storage_dir.exists(),
"`move clean` failed to eliminate {} directory",
DEFAULT_STORAGE_DIR
);
assert!(
!build_output.exists(),
"`move clean` failed to eliminate {} directory",
DEFAULT_BUILD_DIR
);
if let Some(trace_path) = &trace_file {
if trace_path.exists() {
fs::remove_file(trace_path)?;
}
}
}
if let Some((t, _)) = temp_dir {
t.close()?;
}
let update_baseline = read_env_update_baseline();
let exp_path = args_path.with_extension(EXP_EXT);
if update_baseline {
fs::write(exp_path, &output)?;
return Ok(cov_info);
}
let expected_output = fs::read_to_string(exp_path).unwrap_or_else(|_| "".to_string());
if expected_output != output {
anyhow::bail!(
"Expected output differs from actual output:\n{}",
format_diff(expected_output, output)
)
} else {
Ok(cov_info)
}
}
pub fn run_all(
args_path: &Path,
cli_binary: &Path,
use_temp_dir: bool,
track_cov: bool,
) -> anyhow::Result<()> {
let mut test_total: u64 = 0;
let mut test_passed: u64 = 0;
let mut cov_info = ExecCoverageMapWithModules::empty();
for entry in find_filenames(&[args_path], |fpath| {
fpath.file_name().expect("unexpected file entry path") == TEST_ARGS_FILENAME
})? {
match run_one(Path::new(&entry), cli_binary, use_temp_dir, track_cov) {
Ok(cov_opt) => {
test_passed = test_passed.checked_add(1).unwrap();
if let Some(cov) = cov_opt {
cov_info.merge(cov);
}
}
Err(ex) => eprintln!("Test {} failed with error: {}", entry, ex),
}
test_total = test_total.checked_add(1).unwrap();
}
println!("{} / {} test(s) passed.", test_passed, test_total);
let test_failed = test_total.checked_sub(test_passed).unwrap();
if test_failed != 0 {
anyhow::bail!("{} / {} test(s) failed.", test_failed, test_total)
}
if track_cov {
let mut summary_writer: Box<dyn Write> = Box::new(io::stdout());
for (_, module_summary) in cov_info.into_module_summaries() {
module_summary.summarize_human(&mut summary_writer, true)?;
}
}
Ok(())
}