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
use crate::{DEFAULT_BUILD_DIR, DEFAULT_PACKAGE_DIR, DEFAULT_SOURCE_DIR, DEFAULT_STORAGE_DIR};
use anyhow::anyhow;
use move_binary_format::file_format::CompiledModule;
use move_command_line_common::{
env::read_bool_env_var,
files::{extension_equals, find_filenames, path_to_string, MOVE_COMPILED_EXTENSION},
testing::{format_diff, read_env_update_baseline, EXP_EXT},
};
use move_coverage::coverage_map::{CoverageMap, ExecCoverageMapWithModules};
use move_lang::command_line::COLOR_MODE_ENV_VAR;
use std::{
collections::{BTreeMap, HashMap, HashSet},
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,
storage_dir: &Path,
) -> anyhow::Result<ExecCoverageMapWithModules> {
fn find_compiled_move_filenames(path: &Path) -> anyhow::Result<Vec<String>> {
if path.exists() {
find_filenames(&[path_to_string(path)?], |fpath| {
extension_equals(fpath, MOVE_COMPILED_EXTENSION)
})
} else {
Ok(vec![])
}
}
let pkg_modules: HashSet<_> =
find_compiled_move_filenames(&build_dir.join(DEFAULT_PACKAGE_DIR))?
.into_iter()
.map(|entry| PathBuf::from(entry).file_name().unwrap().to_owned())
.collect();
let src_module_files = find_filenames(&[path_to_string(storage_dir)?], |fpath| {
extension_equals(fpath, MOVE_COMPILED_EXTENSION)
&& !pkg_modules.contains(fpath.file_name().unwrap())
})?;
let src_modules = src_module_files
.iter()
.map(|entry| {
let bytecode_bytes = fs::read(entry)?;
let compiled_module = CompiledModule::deserialize(&bytecode_bytes)
.map_err(|e| anyhow!("Failure deserializing module {:?}: {:?}", entry, e))?;
let module_absolute_path = path_to_string(&PathBuf::from(entry).canonicalize()?)?;
Ok((module_absolute_path, compiled_module))
})
.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)
}
pub fn run_one(
args_path: &Path,
cli_binary: &str,
use_temp_dir: bool,
track_cov: bool,
) -> anyhow::Result<Option<ExecCoverageMapWithModules>> {
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(&dst_entry_path)?;
simple_copy_dir(&dst_entry_path, &src_entry_path)?;
} else {
fs::copy(&src_entry_path, &dst_entry_path)?;
}
}
Ok(())
}
let args_file = io::BufReader::new(File::open(args_path)?).lines();
let cli_binary_path = Path::new(cli_binary).canonicalize()?;
let exe_dir = args_path.parent().unwrap();
let temp_dir = if use_temp_dir {
let dir = tempdir()?;
simple_copy_dir(dir.path(), exe_dir)?;
Some(dir)
} else {
None
};
let wks_dir = temp_dir.as_ref().map_or(exe_dir, |t| t.path());
let storage_dir = wks_dir.join(DEFAULT_STORAGE_DIR);
let build_output = wks_dir.join(DEFAULT_BUILD_DIR);
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.path());
} 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 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, &storage_dir)?)
} 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: &str,
cli_binary: &str,
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.to_owned()], |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(())
}
pub fn create_test_scaffold(path: &str) -> anyhow::Result<()> {
let path = Path::new(path);
if path.exists() {
anyhow::bail!("{:#?} already exists. Remove {:#?} and re-run this command if creating it as a test directory was intentional.", path, path);
}
let dirs = [DEFAULT_SOURCE_DIR, "scripts"];
let files = [(
TEST_ARGS_FILENAME,
Some("# This is a batch file. To write an expected value test that runs `move <command1> <args1>;move <command2> <args2>`, write\n\
# `<command1> <args1>`\n\
# `<command2> <args2>`\n\
# '#' is a comment.",
),
)];
fs::create_dir_all(&path)?;
for dir in &dirs {
fs::create_dir_all(&path.canonicalize()?.join(dir))?;
}
for (file, possible_contents) in &files {
let mut file_handle = fs::File::create(path.canonicalize()?.join(file))?;
if let Some(contents) = possible_contents {
write!(file_handle, "{}", contents)?;
}
}
Ok(())
}