1use std::cell::RefCell;
8use std::collections::{BTreeMap, BTreeSet, HashSet};
9use std::fs;
10use std::path::{Path, PathBuf};
11use std::process::{Command, Stdio};
12use std::time::{Duration, Instant};
13
14use anyhow::{Context, Result, anyhow, bail};
15use serde::Deserialize;
16
17use crate::instrument::{self, LiteralSide, RUNTIME_MOD, Rendered, Site, SiteKind};
18use crate::plan::{self, Mutation, Obs};
19use crate::propagation::{self, Change};
20use crate::report::{self, Finding, Report};
21use crate::scope::{self, Scope};
22use crate::trace::Trace;
23
24pub struct Options {
25 pub dir: PathBuf,
27 pub package: Option<String>,
28 pub verify: bool,
30 pub work_dir: Option<PathBuf>,
32 pub progress: bool,
34 pub since: Option<String>,
36 pub lines: Vec<String>,
38 pub baseline: Option<PathBuf>,
40 pub write_baseline: Option<PathBuf>,
42 pub also_test: Vec<String>,
44 pub dependents: bool,
46 pub effects: bool,
48 pub rebuild: bool,
50 pub opt_level: Option<u8>,
52 pub audit: Option<usize>,
54 pub cargo: CargoConfig,
56 pub jobs: usize,
58 pub all_files: bool,
60 pub doc: bool,
62}
63
64pub use crate::report::CargoConfig;
65
66impl CargoConfig {
67 pub fn flags(&self) -> Vec<String> {
69 let mut flags = vec![];
70 if !self.features.is_empty() {
71 flags.extend(["--features".to_string(), self.features.join(",")]);
72 }
73 for (on, flag) in [
74 (self.all_features, "--all-features"),
75 (self.no_default_features, "--no-default-features"),
76 (self.locked, "--locked"),
77 ] {
78 if on {
79 flags.push(flag.to_string());
80 }
81 }
82 flags
83 }
84}
85
86const NEARBY_LINES: usize = 6;
89const WORK_MARKER: &str = ".tmt-work-dir";
91const STD_ALIAS: &str = "__tmt_std";
93const MAX_REPAIR_ROUNDS: usize = 40;
95const MAX_TEST_FILTERS: usize = 200;
97
98#[derive(Deserialize)]
99struct Metadata {
100 packages: Vec<Package>,
101 workspace_root: PathBuf,
102 target_directory: PathBuf,
103}
104
105#[derive(Deserialize)]
106struct Package {
107 name: String,
108 #[serde(default)]
109 dependencies: Vec<Dependency>,
110 manifest_path: PathBuf,
111 targets: Vec<Target>,
112}
113
114#[derive(Deserialize)]
115struct Dependency {
116 name: String,
117}
118
119#[derive(Deserialize)]
120struct Target {
121 kind: Vec<String>,
122 src_path: PathBuf,
123}
124
125#[derive(Deserialize)]
127struct CargoMessage {
128 reason: String,
129 package_id: Option<String>,
130 target: Option<ArtifactTarget>,
131 profile: Option<Profile>,
132 executable: Option<PathBuf>,
133 message: Option<Diagnostic>,
134}
135
136#[derive(Deserialize)]
137struct ArtifactTarget {
138 name: String,
139}
140
141#[derive(Deserialize)]
142struct Profile {
143 test: bool,
144}
145
146#[derive(Deserialize)]
147struct Diagnostic {
148 level: String,
149 rendered: Option<String>,
150 spans: Vec<DiagnosticSpan>,
151}
152
153#[derive(Deserialize)]
154struct DiagnosticSpan {
155 file_name: String,
156 byte_start: usize,
157 line_start: usize,
158 is_primary: bool,
159}
160
161#[derive(Debug, PartialEq, Clone)]
162struct ErrorSpan {
163 file: String,
164 byte_start: usize,
165 line: usize,
166}
167
168#[derive(Debug, PartialEq)]
171struct CompileError {
172 primary: Vec<ErrorSpan>,
173 secondary: Vec<ErrorSpan>,
174 rendered: String,
175}
176
177#[derive(Debug, Default, PartialEq)]
178struct BuildOutput {
179 test_binaries: Vec<(String, PathBuf, String)>,
181 errors: Vec<CompileError>,
182}
183
184fn dependents_of(package: &str, packages: &[Package]) -> Vec<String> {
186 let mut found: Vec<String> = vec![];
187 let mut frontier = vec![package.to_string()];
188 while let Some(current) = frontier.pop() {
189 for other in packages {
190 if other.name != package
191 && !found.contains(&other.name)
192 && other.dependencies.iter().any(|d| d.name == current)
193 {
194 found.push(other.name.clone());
195 frontier.push(other.name.clone());
196 }
197 }
198 }
199 found.sort();
200 found
201}
202
203fn is_package(id: &str, name: &str) -> bool {
206 let (path, fragment) = id.split_once('#').unwrap_or((id, ""));
207 fragment.split('@').next() == Some(name)
208 || path.rsplit('/').next() == Some(name)
209 || id.split(' ').next() == Some(name)
210}
211
212fn parse_build_output(stdout: &str, packages: &[&str]) -> BuildOutput {
213 let mut out = BuildOutput::default();
214 for line in stdout.lines() {
215 let Ok(msg) = serde_json::from_str::<CargoMessage>(line) else {
216 continue;
217 };
218 match msg.reason.as_str() {
219 "compiler-artifact" => {
220 if let (Some(exe), Some(target), Some(profile), Some(id)) = (
221 msg.executable,
222 msg.target,
223 msg.profile,
224 msg.package_id.as_deref(),
225 ) && profile.test
226 && let Some(package) = packages.iter().find(|name| is_package(id, name))
227 {
228 out.test_binaries
229 .push((target.name, exe, package.to_string()));
230 }
231 }
232 "compiler-message" => {
233 let Some(diag) = msg.message else { continue };
234 if diag.level != "error" {
235 continue;
236 }
237 let span = |s: &DiagnosticSpan| ErrorSpan {
238 file: s.file_name.clone(),
239 byte_start: s.byte_start,
240 line: s.line_start,
241 };
242 let error = CompileError {
243 primary: diag
244 .spans
245 .iter()
246 .filter(|s| s.is_primary)
247 .map(span)
248 .collect(),
249 secondary: diag
250 .spans
251 .iter()
252 .filter(|s| !s.is_primary)
253 .map(span)
254 .collect(),
255 rendered: diag.rendered.unwrap_or_default(),
256 };
257 if !error.primary.is_empty() && !out.errors.contains(&error) {
260 out.errors.push(error);
261 }
262 }
263 _ => {}
264 }
265 }
266 out
267}
268
269struct SourceFile {
270 display: String,
272 path: PathBuf,
274 original: String,
275 sites: Vec<Site>,
276 rebuild_sites: Vec<Site>,
278 places: Vec<(usize, usize, String)>,
281 rendered: Option<Rendered>,
282}
283
284enum Runner {
286 Exe(PathBuf),
288 Doc {
291 copy: PathBuf,
292 target_dir: PathBuf,
293 package: String,
294 opt_level: Option<u8>,
295 flags: Vec<String>,
296 },
297}
298
299struct TestBinary {
300 name: String,
301 cwd: PathBuf,
303 marks: PathBuf,
305 tests: BTreeSet<String>,
307 runner: Runner,
308 baseline: Duration,
310 traced: Duration,
312 trace: Trace,
313}
314
315#[derive(Debug, PartialEq, Clone, Copy)]
316enum Outcome {
317 Pass,
318 Fail,
319 Timeout,
320 Unable,
322}
323
324struct WorkLock(PathBuf);
326
327impl WorkLock {
328 fn take(work: &Path) -> Result<WorkLock> {
329 let path = work.join(".tmt-lock");
330 match fs::OpenOptions::new()
331 .write(true)
332 .create_new(true)
333 .open(&path)
334 {
335 Ok(_) => Ok(WorkLock(path)),
336 Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => bail!(
337 "another tmt run is using {}. If none is running, delete {}.",
338 work.display(),
339 path.display()
340 ),
341 Err(err) => Err(err).with_context(|| format!("creating {}", path.display())),
342 }
343 }
344}
345
346impl Drop for WorkLock {
347 fn drop(&mut self) {
348 let _ = fs::remove_file(&self.0);
349 }
350}
351
352const WRITTEN_LOG: &str = ".tmt-written";
354
355struct WorkCopy {
363 root: PathBuf,
364 log: PathBuf,
365 kept: RefCell<HashSet<PathBuf>>,
367 earlier: HashSet<PathBuf>,
369 visited: RefCell<HashSet<PathBuf>>,
371 written: RefCell<HashSet<PathBuf>>,
373 logged: RefCell<HashSet<PathBuf>>,
375}
376
377impl WorkCopy {
378 fn open(work: &Path, root: &Path) -> WorkCopy {
379 let log = work.join(WRITTEN_LOG);
380 for file in [log.clone(), log.with_extension("new")] {
382 if fs::symlink_metadata(&file).is_ok_and(|found| found.is_symlink()) {
383 let _ = fs::remove_file(&file);
384 }
385 }
386 let earlier: HashSet<PathBuf> = fs::read_to_string(&log)
387 .unwrap_or_default()
388 .lines()
389 .map(Path::new)
390 .filter(|relative| {
392 let mut parts = relative.components();
393 parts.clone().next().is_some()
394 && parts.all(|part| matches!(part, std::path::Component::Normal(_)))
395 })
396 .map(|relative| root.join(relative))
397 .collect();
398 WorkCopy {
399 root: root.to_path_buf(),
400 log,
401 kept: RefCell::default(),
402 logged: RefCell::new(earlier.clone()),
403 earlier,
404 visited: RefCell::default(),
405 written: RefCell::default(),
406 }
407 }
408
409 fn is_kept(&self, path: &Path) -> bool {
410 self.kept.borrow().contains(path) || self.earlier.contains(path)
411 }
412
413 fn original(&self, path: &Path, workspace: &Path) -> Result<Option<String>> {
416 let source = if !self.earlier.contains(path) {
417 path.to_path_buf() } else if !self.visited.borrow().contains(path) {
419 return Ok(None);
420 } else {
421 workspace.join(path.strip_prefix(&self.root).unwrap_or(path))
422 };
423 fs::read_to_string(&source)
424 .map(Some)
425 .with_context(|| format!("reading {}", source.display()))
426 }
427
428 fn write(&self, path: &Path, content: &str) -> Result<()> {
431 if fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) {
432 fs::remove_file(path)?;
433 }
434 let parent = path.parent().and_then(|p| p.canonicalize().ok());
435 let inside = match (parent, self.root.canonicalize()) {
436 (Some(parent), Ok(root)) => parent.starts_with(root),
437 _ => false,
438 };
439 if !inside {
440 bail!(
441 "refusing to write outside the working copy: {}",
442 path.display()
443 );
444 }
445 self.record(path)?;
446 if fs::read_to_string(path).is_ok_and(|existing| existing == content) {
447 return Ok(()); }
449 fs::write(path, content).with_context(|| format!("writing {}", path.display()))
450 }
451
452 fn record(&self, path: &Path) -> Result<()> {
453 self.written.borrow_mut().insert(path.to_path_buf());
454 if self.logged.borrow().contains(path) {
455 return Ok(());
456 }
457 let line = path
458 .strip_prefix(&self.root)
459 .ok()
460 .and_then(Path::to_str)
461 .filter(|text| !text.chars().any(char::is_control));
462 let Some(line) = line else {
463 bail!(
464 "cannot instrument {}: its name cannot be written on a line of the log",
465 path.display()
466 );
467 };
468 use std::io::Write as _;
469 let mut log = fs::OpenOptions::new()
470 .create(true)
471 .append(true)
472 .open(&self.log)
473 .with_context(|| format!("opening {}", self.log.display()))?;
474 writeln!(log, "{line}").with_context(|| format!("writing {}", self.log.display()))?;
475 self.logged.borrow_mut().insert(path.to_path_buf());
476 Ok(())
477 }
478
479 fn settle(&self, workspace: &Path) -> Result<()> {
482 let written = self.written.borrow();
483 for path in self.earlier.difference(&written) {
484 if fs::symlink_metadata(path).is_ok() {
485 fs::remove_file(path).with_context(|| format!("removing {}", path.display()))?;
486 }
487 if self.visited.borrow().contains(path) {
488 let source = workspace.join(path.strip_prefix(&self.root).unwrap_or(path));
489 copy_as_new(&source, path)?;
490 }
491 }
492 let mut lines: Vec<&str> = written
493 .iter()
494 .filter_map(|path| path.strip_prefix(&self.root).ok()?.to_str())
495 .collect();
496 lines.sort_unstable();
497 let fresh = self.log.with_extension("new");
498 fs::write(
499 &fresh,
500 lines
501 .iter()
502 .map(|line| format!("{line}\n"))
503 .collect::<String>(),
504 )?;
505 fs::rename(&fresh, &self.log)?;
506 *self.logged.borrow_mut() = written.clone();
507 Ok(())
508 }
509}
510
511fn sync_file(src: &Path, dst: &Path, state: &WorkCopy) -> Result<()> {
515 state.kept.borrow_mut().insert(dst.to_path_buf());
516 if state.earlier.contains(dst) {
517 state.visited.borrow_mut().insert(dst.to_path_buf());
518 if fs::symlink_metadata(dst).is_ok_and(|m| m.is_file()) {
519 return Ok(());
521 }
522 }
523 let up_to_date = fs::symlink_metadata(dst).is_ok_and(|to| to.is_file()) && same_bytes(src, dst);
527 if up_to_date {
528 return Ok(());
529 }
530 if let Ok(existing) = fs::symlink_metadata(dst) {
531 if existing.is_dir() {
532 fs::remove_dir_all(dst)?;
533 } else {
534 fs::remove_file(dst)?;
535 }
536 }
537 copy_as_new(src, dst)
538}
539
540fn same_bytes(a: &Path, b: &Path) -> bool {
542 fs::read(a)
543 .ok()
544 .zip(fs::read(b).ok())
545 .is_some_and(|(a, b)| a == b)
546}
547
548fn real_dir(dir: &Path, state: &WorkCopy) -> Result<()> {
552 if let Ok(below) = dir.strip_prefix(&state.root) {
553 let mut path = state.root.clone();
554 for part in below.components() {
555 path.push(part);
556 match fs::symlink_metadata(&path) {
557 Ok(found) if !found.is_dir() => fs::remove_file(&path)
558 .with_context(|| format!("removing {}", path.display()))?,
559 _ => {}
560 }
561 }
562 }
563 fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))
564}
565
566fn copy_as_new(src: &Path, dst: &Path) -> Result<()> {
570 fs::copy(src, dst).with_context(|| format!("copying {}", src.display()))?;
571 fs::File::open(dst)
573 .and_then(|file| file.set_modified(std::time::SystemTime::now()))
574 .with_context(|| format!("touching {}", dst.display()))
575}
576
577fn prune(dir: &Path, state: &WorkCopy) -> Result<bool> {
579 let mut empty = true;
580 for entry in fs::read_dir(dir)? {
581 let path = entry?.path();
582 let is_dir = fs::symlink_metadata(&path)?.is_dir();
583 if is_dir {
584 if prune(&path, state)? {
585 fs::remove_dir(&path)?;
586 } else {
587 empty = false;
588 }
589 } else if state.is_kept(&path) {
590 empty = false;
591 } else {
592 fs::remove_file(&path)?;
593 }
594 }
595 Ok(empty)
596}
597
598fn copy_entry(
605 src: &Path,
606 dst: &Path,
607 workspace: &Path,
608 skip: &dyn Fn(&Path) -> bool,
609 state: &WorkCopy,
610) -> Result<()> {
611 let kind = fs::symlink_metadata(src)?.file_type();
612 if kind.is_symlink() {
613 let Ok(target) = src.canonicalize() else {
614 return Ok(()); };
616 if target.is_dir() {
617 let contains_link = src
618 .parent()
619 .is_some_and(|dir| dir.canonicalize().is_ok_and(|dir| dir.starts_with(&target)));
620 if !target.starts_with(workspace) || contains_link || skip(&target) {
621 return Ok(());
622 }
623 return copy_tree(&target, dst, workspace, skip, state);
624 }
625 sync_file(&target, dst, state)?;
626 } else if kind.is_dir() {
627 if !src.join("CACHEDIR.TAG").exists() {
629 copy_tree(src, dst, workspace, skip, state)?;
630 }
631 } else {
632 sync_file(src, dst, state)?;
633 }
634 Ok(())
635}
636
637fn copy_tree(
638 from: &Path,
639 to: &Path,
640 workspace: &Path,
641 skip: &dyn Fn(&Path) -> bool,
642 state: &WorkCopy,
643) -> Result<()> {
644 real_dir(to, state)?;
645 for entry in fs::read_dir(from).with_context(|| format!("reading {}", from.display()))? {
646 let src = entry?.path();
647 if skip(&src) {
648 continue;
649 }
650 let Some(name) = src.file_name() else {
651 continue;
652 };
653 copy_entry(&src, &to.join(name), workspace, skip, state)?;
654 }
655 Ok(())
656}
657
658fn rust_files(dir: &Path, skip: &dyn Fn(&Path) -> bool, out: &mut Vec<PathBuf>) -> Result<()> {
659 let mut entries: Vec<PathBuf> = fs::read_dir(dir)?
660 .map(|e| e.map(|e| e.path()))
661 .collect::<std::io::Result<_>>()?;
662 entries.sort();
663 for path in entries {
664 let Ok(kind) = fs::symlink_metadata(&path).map(|m| m.file_type()) else {
665 continue;
666 };
667 if skip(&path) || kind.is_symlink() {
668 continue;
669 }
670 if kind.is_dir() {
671 rust_files(&path, skip, out)?;
672 } else if path.extension().is_some_and(|e| e == "rs") {
673 out.push(path);
674 }
675 }
676 Ok(())
677}
678
679fn git_visible_files(dir: &Path) -> Result<Option<Vec<PathBuf>>> {
683 let git = |args: &[&str]| {
684 Command::new("git")
685 .arg("-C")
686 .arg(dir)
687 .args(args)
688 .stderr(Stdio::null())
689 .output()
690 };
691 let Ok(inside) = git(&["rev-parse", "--is-inside-work-tree"]) else {
693 return Ok(None);
694 };
695 if !inside.status.success() {
696 return Ok(None);
697 }
698 if git(&["check-ignore", "-q", "."])?.status.success() {
700 return Ok(None);
701 }
702 let listing = git(&[
705 "ls-files",
706 "--cached",
707 "--others",
708 "--exclude-standard",
709 "-z",
710 ])?;
711 if !listing.status.success() {
712 bail!(
713 "git could not list the files of {}; pass --all-files to copy everything",
714 dir.display()
715 );
716 }
717 Ok(Some(
718 listing
719 .stdout
720 .split(|b| *b == 0)
721 .filter(|name| !name.is_empty())
722 .filter_map(|name| std::str::from_utf8(name).ok())
723 .map(PathBuf::from)
724 .collect(),
725 ))
726}
727
728fn copy_git_visible(
731 from: &Path,
732 to: &Path,
733 files: Vec<PathBuf>,
734 workspace: &Path,
735 skip: &dyn Fn(&Path) -> bool,
736 state: &WorkCopy,
737) -> Result<usize> {
738 let mut copied = 0;
739 for relative in files {
740 let (src, dst) = (from.join(&relative), to.join(&relative));
741 if skip(&src)
742 || src
743 .ancestors()
744 .any(|a| a != from && a.starts_with(from) && skip(a))
745 {
746 continue;
747 }
748 let Ok(kind) = fs::symlink_metadata(&src).map(|m| m.file_type()) else {
749 continue; };
751 if let Some(parent) = dst.parent() {
752 real_dir(parent, state)?;
753 }
754 if kind.is_dir() {
755 match git_visible_files(&src)? {
756 Some(inner) => {
757 copied += copy_git_visible(&src, &dst, inner, workspace, skip, state)?
758 }
759 None => copy_tree(&src, &dst, workspace, skip, state)?,
760 }
761 } else {
762 copy_entry(&src, &dst, workspace, skip, state)?;
763 copied += 1;
764 }
765 }
766 Ok(copied)
767}
768
769fn module_paths(file: &Path, module: &instrument::TestModule) -> Vec<PathBuf> {
771 let dir = file.parent().unwrap_or(Path::new("."));
772 if let Some(path) = &module.path {
773 return vec![dir.join(path)];
774 }
775 let name = &module.name;
776 let stem = file.file_stem().and_then(|s| s.to_str()).unwrap_or("");
777 let base = if matches!(stem, "lib" | "main" | "mod") {
778 dir.to_path_buf()
779 } else {
780 dir.join(stem)
781 };
782 vec![base.join(format!("{name}.rs")), base.join(name)]
783}
784
785fn normalize(path: &Path) -> PathBuf {
787 let mut out = PathBuf::new();
788 for component in path.components() {
789 match component {
790 std::path::Component::CurDir => {}
791 std::path::Component::ParentDir => {
792 out.pop();
793 }
794 other => out.push(other),
795 }
796 }
797 out
798}
799
800fn absolutize_path_dependencies(
803 manifest: &str,
804 manifest_dir: &Path,
805 workspace: &Path,
806 copy: &Path,
807) -> Result<Option<String>> {
808 use toml_edit::{DocumentMut, Item, TableLike, value};
809
810 fn fix(deps: &mut dyn TableLike, dirs: (&Path, &Path, &Path), changed: &mut bool) {
811 let (manifest_dir, workspace, copy) = dirs;
812 for (_, dep) in deps.iter_mut() {
813 let Some(dep) = dep.as_table_like_mut() else {
814 continue;
815 };
816 let Some(path) = dep.get("path").and_then(Item::as_str) else {
817 continue;
818 };
819 let absolute = Path::new(path).is_absolute();
820 let target = normalize(&manifest_dir.join(path));
821 let rewritten = match target.strip_prefix(workspace) {
822 Err(_) => target,
824 Ok(inside) if absolute => copy.join(inside),
827 Ok(_) => continue,
828 };
829 dep.insert("path", value(rewritten.to_string_lossy().into_owned()));
830 *changed = true;
831 }
832 }
833 const SECTIONS: [&str; 3] = ["dependencies", "dev-dependencies", "build-dependencies"];
834 fn fix_sections(table: &mut dyn TableLike, dirs: (&Path, &Path, &Path), changed: &mut bool) {
835 for section in SECTIONS {
836 if let Some(deps) = table.get_mut(section).and_then(Item::as_table_like_mut) {
837 fix(deps, dirs, changed);
838 }
839 }
840 }
841
842 let mut doc: DocumentMut = manifest.parse().context("parsing Cargo.toml")?;
843 let mut changed = false;
844 let dirs = (manifest_dir, workspace, copy);
845 fix_sections(doc.as_table_mut(), dirs, &mut changed);
846 if let Some(ws) = doc.get_mut("workspace").and_then(Item::as_table_like_mut) {
847 fix_sections(ws, dirs, &mut changed);
848 }
849 for per_key in ["target", "patch"] {
850 let Some(outer) = doc.get_mut(per_key).and_then(Item::as_table_like_mut) else {
851 continue;
852 };
853 for (_, inner) in outer.iter_mut() {
854 let Some(inner) = inner.as_table_like_mut() else {
855 continue;
856 };
857 if per_key == "target" {
858 fix_sections(inner, dirs, &mut changed);
859 } else {
860 fix(inner, dirs, &mut changed);
861 }
862 }
863 }
864 Ok(changed.then(|| doc.to_string()))
865}
866
867fn test_filter(tests: &BTreeSet<String>, known: &BTreeSet<String>) -> Option<Vec<String>> {
873 if tests.len() > MAX_TEST_FILTERS || !tests.iter().all(|t| known.contains(t)) {
874 None
875 } else {
876 Some(tests.iter().cloned().collect())
877 }
878}
879
880fn parse_test_list(stdout: &str) -> BTreeSet<String> {
882 stdout
883 .lines()
884 .filter_map(|line| line.strip_suffix(": test"))
885 .map(str::to_string)
886 .collect()
887}
888
889fn profile_env(opt_level: Option<u8>) -> Vec<(&'static str, String)> {
892 opt_level.map_or(vec![], |level| {
893 vec![
894 ("CARGO_PROFILE_DEV_OPT_LEVEL", level.to_string()),
895 ("CARGO_PROFILE_TEST_OPT_LEVEL", level.to_string()),
896 ]
897 })
898}
899
900const SLOW_TRACE: Duration = Duration::from_secs(2);
902
903fn mutant_timeout(baseline: Duration) -> Duration {
904 Duration::from_secs(5) + baseline * 5
905}
906
907fn test_threads(cores: usize, sharing: usize) -> usize {
911 (cores / sharing.max(1)).max(2)
912}
913
914fn run_binary(
915 bin: &TestBinary,
916 tests: Option<&[String]>,
917 env: &[(&str, &str)],
918 timeout: Duration,
919 stop_at_first_failure: bool,
920 sharing: usize,
921) -> Result<Outcome> {
922 use std::io::BufRead;
923 use std::sync::Arc;
924 use std::sync::atomic::{AtomicBool, Ordering};
925
926 let cores = std::thread::available_parallelism().map_or(2, |n| n.get());
927 let threads = test_threads(cores, sharing);
928 static RUNS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
929 let unable_mark = reserve_mark(&bin.marks, &RUNS)?;
930
931 let mut cmd = match &bin.runner {
932 Runner::Exe(exe) => {
933 let mut cmd = Command::new(exe);
934 cmd.arg(format!("--test-threads={threads}"));
937 if let Some(tests) = tests {
938 cmd.arg("--exact").args(tests);
939 }
940 cmd.current_dir(&bin.cwd)
941 .env("CARGO_MANIFEST_DIR", &bin.cwd);
942 cmd
943 }
944 Runner::Doc {
945 copy,
946 target_dir,
947 package,
948 opt_level,
949 flags,
950 } => {
951 let mut cmd = Command::new("cargo");
952 cmd.args(["test", "--doc", "-p", package])
953 .args(flags)
954 .current_dir(copy)
955 .env("CARGO_TARGET_DIR", target_dir)
956 .envs(profile_env(*opt_level));
957 cmd
958 }
959 };
960 cmd.env_remove("TMT_TRACE")
961 .env_remove("TMT_MUTANT")
962 .env("TMT_UNABLE", &unable_mark)
963 .envs(env.iter().copied())
964 .stdin(Stdio::null())
965 .stdout(if stop_at_first_failure {
966 Stdio::piped()
967 } else {
968 Stdio::null()
969 })
970 .stderr(Stdio::null());
971 #[cfg(unix)]
973 std::os::unix::process::CommandExt::process_group(&mut cmd, 0);
974 let mut child = cmd
975 .spawn()
976 .with_context(|| format!("starting the tests of `{}`", bin.name))?;
977 let failed = Arc::new(AtomicBool::new(false));
980 let watcher = child.stdout.take().map(|stdout| {
981 let failed = Arc::clone(&failed);
982 std::thread::spawn(move || {
983 for line in std::io::BufReader::new(stdout)
984 .lines()
985 .map_while(|l| l.ok())
986 {
987 if is_failure_line(&line) {
988 failed.store(true, Ordering::SeqCst);
989 }
990 }
991 })
992 });
993 let kill = |child: &mut std::process::Child| {
994 #[cfg(unix)]
995 let _ = Command::new("kill")
996 .args(["-KILL", "--", &format!("-{}", child.id())])
997 .stdout(Stdio::null())
998 .stderr(Stdio::null())
999 .status();
1000 let _ = child.kill();
1001 let _ = child.wait();
1002 };
1003 let started = Instant::now();
1004 let outcome = loop {
1005 if let Some(status) = child.try_wait()? {
1006 break if status.success() {
1007 Outcome::Pass
1008 } else {
1009 Outcome::Fail
1010 };
1011 }
1012 if failed.load(Ordering::SeqCst) {
1013 kill(&mut child);
1014 break Outcome::Fail;
1015 }
1016 if started.elapsed() > timeout {
1017 kill(&mut child);
1018 break Outcome::Timeout;
1019 }
1020 std::thread::sleep(Duration::from_millis(5));
1021 };
1022 if let Some(watcher) = watcher {
1023 let _ = watcher.join();
1024 }
1025 if release_mark(&unable_mark)? {
1029 return Ok(Outcome::Unable);
1030 }
1031 Ok(outcome)
1032}
1033
1034fn marks_dir(work: &Path) -> Result<PathBuf> {
1038 let marks = work.join("marks");
1039 match fs::symlink_metadata(&marks) {
1040 Ok(found) if found.is_dir() => {}
1041 Ok(_) => bail!(
1042 "{} is in the way: the working directory needs a directory of that name, and \
1043 this is not one. Move it, or choose another --work-dir",
1044 marks.display()
1045 ),
1046 Err(_) => {
1047 fs::create_dir(&marks).with_context(|| format!("creating {}", marks.display()))?
1048 }
1049 }
1050 Ok(marks)
1051}
1052
1053fn reserve_mark(dir: &Path, runs: &std::sync::atomic::AtomicUsize) -> Result<PathBuf> {
1062 let dir = std::path::absolute(dir).unwrap_or(dir.to_path_buf());
1065 loop {
1066 let mark = dir.join(format!(
1067 "tmt-unable-{}-{}",
1068 std::process::id(),
1069 runs.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
1070 ));
1071 match fs::OpenOptions::new()
1072 .write(true)
1073 .create_new(true)
1074 .open(&mark)
1075 {
1076 Ok(_) => return Ok(mark),
1077 Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {}
1078 Err(err) => {
1080 return Err(err).with_context(|| format!("creating {}", mark.display()));
1081 }
1082 }
1083 }
1084}
1085
1086fn release_mark(mark: &Path) -> Result<bool> {
1090 match fs::remove_file(mark) {
1091 Ok(()) => Ok(false),
1092 Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(true),
1093 Err(err) => Err(err).with_context(|| {
1094 format!(
1095 "removing {}: cannot tell whether the tests ran the mutant to the end",
1096 mark.display()
1097 )
1098 }),
1099 }
1100}
1101
1102fn is_failure_line(line: &str) -> bool {
1104 line.starts_with("test ") && line.ends_with(" ... FAILED")
1105}
1106
1107fn requested_scope(
1110 options: &Options,
1111 workspace: &Path,
1112 package_dir: &Path,
1113 copy: &Path,
1114) -> Result<Option<Scope>> {
1115 if options.since.is_none() && options.lines.is_empty() {
1116 return Ok(None);
1117 }
1118 let prefix = package_dir.strip_prefix(copy).unwrap_or(Path::new(""));
1120 let lines: Vec<String> = options
1121 .lines
1122 .iter()
1123 .map(|spec| prefix.join(spec).to_string_lossy().into_owned())
1124 .collect();
1125 let mut scope = Scope::parse_lines(&lines)?;
1126 if let Some(revision) = &options.since {
1127 let git = |args: &[&str]| -> Result<String> {
1128 let output = Command::new("git")
1129 .arg("-C")
1130 .arg(workspace)
1131 .args(args)
1132 .output()
1133 .context("running git")?;
1134 if !output.status.success() {
1135 bail!(
1136 "git {} failed: {}",
1137 args.join(" "),
1138 String::from_utf8_lossy(&output.stderr).trim()
1139 );
1140 }
1141 Ok(String::from_utf8_lossy(&output.stdout).into_owned())
1142 };
1143 scope.merge(Scope::from_diff(&git(&[
1145 "diff",
1146 "-U0",
1147 "--no-color",
1148 "--no-ext-diff",
1149 "--relative",
1150 revision,
1151 "--",
1152 ])?));
1153 for file in git(&["ls-files", "--others", "--exclude-standard"])?.lines() {
1154 scope.add_whole_file(file);
1155 }
1156 }
1157 Ok(Some(scope))
1158}
1159
1160fn blame_error(
1164 error: &CompileError,
1165 files: &[SourceFile],
1166 copy: &Path,
1167 disabled: &HashSet<u32>,
1168) -> Vec<u32> {
1169 let enabled = |id: u32| !disabled.contains(&id);
1170 let file_of = |span: &ErrorSpan| {
1171 let path = copy.join(&span.file);
1172 files.iter().find(|f| f.path == path)
1173 };
1174 let innermost = |spans: &[ErrorSpan]| -> Vec<u32> {
1175 let mut ids = vec![];
1176 for span in spans {
1177 if let Some(file) = file_of(span) {
1178 let rendered = file.rendered.as_ref().expect("rendered before building");
1179 match rendered
1181 .inserted_by(span.byte_start)
1182 .filter(|id| enabled(*id))
1183 {
1184 Some(id) => ids.push(id),
1185 None => ids.extend(instrument::blame(
1186 &file.sites,
1187 &enabled,
1188 rendered.to_original(span.byte_start),
1189 )),
1190 }
1191 }
1192 }
1193 ids
1194 };
1195 let widen = |lines: usize| -> Vec<u32> {
1196 let mut ids = vec![];
1197 for span in &error.primary {
1198 if let Some(file) = file_of(span) {
1199 ids.extend(
1200 file.sites
1201 .iter()
1202 .filter(|s| enabled(s.id) && s.line.abs_diff(span.line) <= lines)
1203 .map(|s| s.id),
1204 );
1205 }
1206 }
1207 ids
1208 };
1209 [
1210 innermost(&error.primary),
1211 innermost(&error.secondary),
1212 widen(0),
1213 widen(NEARBY_LINES),
1214 widen(usize::MAX),
1215 ]
1216 .into_iter()
1217 .find(|ids| !ids.is_empty())
1218 .unwrap_or_default()
1219}
1220
1221fn domain_of(
1223 literal: LiteralSide,
1224 bounds: Option<&crate::trace::TypeBounds>,
1225) -> Option<(i128, i128)> {
1226 let bounds = bounds?;
1227 match literal {
1228 LiteralSide::Rhs(k) => Some((bounds.lhs.0.checked_sub(k)?, bounds.lhs.1.checked_sub(k)?)),
1229 LiteralSide::Lhs(k) => Some((k.checked_sub(bounds.rhs.1)?, k.checked_sub(bounds.rhs.0)?)),
1230 LiteralSide::None => None,
1231 }
1232}
1233
1234struct Session {
1235 progress: bool,
1236 package_dir: PathBuf,
1237 binaries: Vec<TestBinary>,
1238}
1239
1240struct Job {
1242 site: u32,
1243 mutation: Mutation,
1244 tests: Vec<(usize, Option<Vec<String>>)>,
1246}
1247
1248#[derive(Debug, Clone, PartialEq)]
1249struct JobResult {
1250 survived: Option<Vec<String>>,
1252 timed_out: bool,
1253 unable: bool,
1255}
1256
1257fn tests_where<T>(
1259 per_test: Option<&BTreeMap<String, T>>,
1260 pick: impl Fn(&T) -> bool,
1261) -> BTreeSet<String> {
1262 per_test
1263 .into_iter()
1264 .flatten()
1265 .filter(|(_, obs)| pick(obs))
1266 .map(|(test, _)| test.clone())
1267 .collect()
1268}
1269
1270type InfectedTests<'a> = Box<dyn Fn(&TestBinary, Mutation) -> BTreeSet<String> + 'a>;
1271type ReachingTests<'a> = Box<dyn Fn(&TestBinary) -> BTreeSet<String> + 'a>;
1272
1273struct PlannedGap {
1275 finding: Finding,
1276 survivors: Vec<Mutation>,
1278 constant_expr: Option<(usize, usize)>,
1282}
1283
1284fn core_range(start: usize, text: &str) -> (usize, usize) {
1286 let (mut from, mut to) = (0, text.len());
1287 loop {
1288 let inner = &text[from..to];
1289 let trimmed = inner.trim();
1290 from += inner.len() - inner.trim_start().len();
1291 to = from + trimmed.len();
1292 let wrapped = trimmed.starts_with('(') && trimmed.ends_with(')') && {
1293 let mut depth = 0usize;
1295 trimmed.char_indices().all(|(i, c)| {
1296 match c {
1297 '(' => depth += 1,
1298 ')' => depth -= 1,
1299 _ => {}
1300 }
1301 depth > 0 || i == trimmed.len() - 1
1302 })
1303 };
1304 if !wrapped {
1305 return (start + from, start + to);
1306 }
1307 from += 1;
1308 to -= 1;
1309 }
1310}
1311
1312struct SitePlan<'a> {
1314 gaps: Vec<PlannedGap>,
1316 cannot_differ: bool,
1319 constant: bool,
1321 run: Vec<Mutation>,
1323 infected: InfectedTests<'a>,
1325 reaching: ReachingTests<'a>,
1327}
1328
1329enum Planned<'a> {
1330 Unreached,
1331 NotEvaluated,
1333 Nothing,
1335 Plan(SitePlan<'a>),
1336}
1337
1338type ConfirmedGap = (Finding, Vec<usize>, Option<(usize, usize)>);
1340
1341struct SiteWork<'a> {
1343 file: &'a str,
1344 site: &'a Site,
1345 gaps: Vec<ConfirmedGap>,
1346 constant: bool,
1347 cannot_differ: bool,
1348 runs: Vec<(Mutation, usize)>,
1349}
1350
1351impl Session {
1352 fn note(&self, text: &str) {
1353 if self.progress {
1354 eprintln!("tmt: {text}");
1355 }
1356 }
1357
1358 fn merged<T: Default + Copy>(
1359 &self,
1360 select: impl Fn(&Trace) -> Option<&BTreeMap<String, T>>,
1361 merge: impl Fn(&mut T, &T),
1362 ) -> T {
1363 let mut all = T::default();
1364 for obs in self
1365 .binaries
1366 .iter()
1367 .filter_map(|b| select(&b.trace))
1368 .flat_map(|t| t.values())
1369 {
1370 merge(&mut all, obs);
1371 }
1372 all
1373 }
1374
1375 fn plan<'a>(&'a self, file: &str, site: &'a Site, verify: bool) -> Planned<'a> {
1376 let id = site.id;
1377 let reach_plan = |mutation: Mutation| SitePlan {
1378 gaps: vec![],
1379 constant: false,
1380 cannot_differ: false,
1381 run: vec![mutation],
1382 infected: Box::new(move |bin, _| bin.trace.reach.get(&id).cloned().unwrap_or_default()),
1383 reaching: Box::new(move |bin| bin.trace.reach.get(&id).cloned().unwrap_or_default()),
1384 };
1385 let reached = self
1386 .binaries
1387 .iter()
1388 .any(|b| b.trace.reach.contains_key(&id));
1389 let opaque = self
1390 .merged(|t| t.arith.get(&id), plan::ArithObs::merge)
1391 .opaque;
1392 Planned::Plan(match &site.kind {
1393 SiteKind::Stmt
1394 | SiteKind::Neg { .. }
1395 | SiteKind::Field { .. }
1396 | SiteKind::Body { .. }
1397 if reached =>
1398 {
1399 reach_plan(Mutation::Delete)
1400 }
1401 SiteKind::Stmt
1402 | SiteKind::Neg { .. }
1403 | SiteKind::Field { .. }
1404 | SiteKind::Body { .. } => return Planned::Unreached,
1405 SiteKind::Guard { can_be_false } => {
1406 let can_be_false = *can_be_false;
1407 let allowed = move |m: &Mutation| can_be_false || *m != Mutation::Const(false);
1408 let merged = self.merged(|t| t.returns.get(&id), plan::ReturnObs::merge);
1409 let guard_plan = plan::plan_return(&merged);
1410 if guard_plan.unreached {
1411 return Planned::Unreached;
1412 }
1413 let gaps = guard_plan
1414 .always
1415 .filter(|always| allowed(&Mutation::Const(*always)))
1416 .map(|always| PlannedGap {
1417 finding: report::guard_gap_finding(file, site, always, verify),
1418 survivors: vec![Mutation::Const(always)],
1419 constant_expr: Some((site.start, site.end)),
1421 })
1422 .into_iter()
1423 .collect();
1424 SitePlan {
1425 constant: false,
1426 cannot_differ: false,
1427 gaps,
1428 run: guard_plan.run.into_iter().filter(allowed).collect(),
1429 infected: Box::new(move |bin, m| {
1430 tests_where(bin.trace.returns.get(&id), |obs| match m {
1431 Mutation::Const(value) => obs.infected_by_const(value),
1432 _ => obs.reached(),
1433 })
1434 }),
1435 reaching: Box::new(move |bin| {
1436 tests_where(bin.trace.returns.get(&id), plan::ReturnObs::reached)
1437 }),
1438 }
1439 }
1440 SiteKind::Arm { .. } if reached => reach_plan(Mutation::Delete),
1441 SiteKind::Arm { .. } => return Planned::Unreached,
1442 SiteKind::Not { .. } if reached => reach_plan(Mutation::DropNot),
1443 SiteKind::Range { .. }
1446 if reached
1447 && self
1448 .binaries
1449 .iter()
1450 .any(|b| b.trace.ranges_at_top.contains(&id)) =>
1451 {
1452 return Planned::NotEvaluated;
1453 }
1454 SiteKind::Range { .. } if reached => reach_plan(Mutation::RangeEnd),
1455 SiteKind::Not { .. } | SiteKind::Range { .. } if opaque => return Planned::Nothing,
1458 SiteKind::Not { .. } | SiteKind::Range { .. } => return Planned::Unreached,
1459 SiteKind::Cmp { op, literal, .. } => {
1460 let op = *op;
1461 let mut merged = Obs::default();
1462 for bin in &self.binaries {
1463 merged.merge(&bin.trace.merged(id));
1464 }
1465 let bounds = self.binaries.iter().find_map(|b| b.trace.bounds.get(&id));
1466 let cmp_plan = plan::plan_cmp(op, &merged, domain_of(*literal, bounds));
1467 let mut gaps = vec![];
1468 let mut constant = false;
1469 match &cmp_plan.gap {
1470 Some(plan::InputGap::Unreached) => return Planned::Unreached,
1471 Some(gap) => {
1472 constant = matches!(gap, plan::InputGap::OneSided { .. });
1473 if let Some(finding) =
1474 report::input_gap_finding(file, site, gap, &merged, verify)
1475 {
1476 gaps.push(PlannedGap {
1477 finding,
1478 survivors: gap.survivors(),
1479 constant_expr: None,
1480 });
1481 }
1482 }
1483 None => {}
1484 }
1485 SitePlan {
1486 gaps,
1487 constant,
1488 cannot_differ: cmp_plan.cannot_differ,
1489 run: cmp_plan.run,
1490 infected: Box::new(move |bin, m| {
1491 tests_where(bin.trace.cmp.get(&id), |obs| plan::infects(op, m, obs))
1492 }),
1493 reaching: Box::new(move |bin| {
1494 tests_where(bin.trace.cmp.get(&id), Obs::reached)
1495 }),
1496 }
1497 }
1498 SiteKind::Logic {
1499 and,
1500 lhs,
1501 rhs,
1502 gap: op_gap,
1503 } => {
1504 let and = *and;
1505 let lhs_range = core_range(site.start, lhs);
1506 let rhs_range = core_range(op_gap.1, rhs);
1507 let merged = self.merged(|t| t.logic.get(&id), plan::LogicObs::merge);
1508 let logic_plan = plan::plan_logic(and, &merged);
1509 if logic_plan.gaps.contains(&plan::LogicGap::Unreached) {
1510 return Planned::Unreached;
1511 }
1512 let gaps: Vec<_> = logic_plan
1513 .gaps
1514 .iter()
1515 .filter_map(|gap| {
1516 let (mutation, operand) = match gap {
1519 plan::LogicGap::RhsNeverDecides => (Mutation::LogicDropRhs, rhs_range),
1520 _ => (Mutation::LogicDropLhs, lhs_range),
1521 };
1522 Some(PlannedGap {
1523 finding: report::logic_gap_finding(file, site, *gap, verify)?,
1524 survivors: vec![mutation],
1525 constant_expr: Some(operand),
1526 })
1527 })
1528 .collect();
1529 SitePlan {
1530 constant: merged.constant_value(and).is_some(),
1531 cannot_differ: false,
1532 gaps,
1533 run: logic_plan.run,
1534 infected: Box::new(move |bin, m| {
1535 tests_where(bin.trace.logic.get(&id), |obs| {
1536 plan::logic_infects(and, m, obs)
1537 })
1538 }),
1539 reaching: Box::new(move |bin| {
1540 tests_where(bin.trace.logic.get(&id), plan::LogicObs::reached)
1541 }),
1542 }
1543 }
1544 SiteKind::Arith { .. } | SiteKind::MinMax { .. } => {
1545 let merged = self.merged(|t| t.arith.get(&id), plan::ArithObs::merge);
1548 let mutations: Vec<(Mutation, plan::ArithObs)> = match &site.kind {
1549 SiteKind::MinMax { .. } => vec![(Mutation::MinMax, merged)],
1550 SiteKind::Arith { op, assign, .. } if op.second(*assign).is_some() => vec![
1551 (Mutation::ArithSwap, merged),
1552 (Mutation::ArithSwap2, merged.second()),
1553 ],
1554 _ => vec![(Mutation::ArithSwap, merged)],
1555 };
1556 let (mut gaps, mut run) = (vec![], vec![]);
1557 for (mutation, seen) in mutations {
1558 match plan::plan_arith(&seen) {
1559 plan::ArithPlan::Unreached => return Planned::Unreached,
1560 plan::ArithPlan::Opaque => return Planned::Nothing,
1562 plan::ArithPlan::NeverDiffers => {
1563 let finding = if mutation == Mutation::MinMax {
1564 report::min_max_gap_finding(file, site, verify)
1565 } else {
1566 report::arith_gap_finding(file, site, mutation, verify)
1567 };
1568 gaps.extend(finding.map(|finding| PlannedGap {
1569 finding,
1570 survivors: vec![mutation],
1571 constant_expr: None,
1572 }));
1573 }
1574 plan::ArithPlan::Run => run.push(mutation),
1575 }
1576 }
1577 SitePlan {
1578 gaps,
1579 constant: false,
1580 cannot_differ: false,
1581 run,
1582 infected: Box::new(move |bin, m| {
1583 tests_where(bin.trace.arith.get(&id), |obs| obs.infected_by(m))
1584 }),
1585 reaching: Box::new(move |bin| {
1586 tests_where(bin.trace.arith.get(&id), |obs| obs.same || obs.differs)
1587 }),
1588 }
1589 }
1590 SiteKind::Return {
1591 sole_expr, option, ..
1592 } => {
1593 let sole_expr = *sole_expr;
1594 let is_option = option.is_some();
1595 let merged = self.merged(|t| t.returns.get(&id), plan::ReturnObs::merge);
1596 let return_plan = if is_option {
1597 plan::plan_option_return(&merged)
1598 } else {
1599 plan::plan_return(&merged)
1600 };
1601 if return_plan.unreached {
1602 return Planned::Unreached;
1603 }
1604 let gaps: Vec<_> = return_plan
1605 .always
1606 .and_then(|always| {
1607 Some(PlannedGap {
1608 finding: report::return_gap_finding(file, site, always, verify)?,
1609 survivors: vec![Mutation::Const(always)],
1610 constant_expr: sole_expr,
1612 })
1613 })
1614 .into_iter()
1615 .collect();
1616 SitePlan {
1617 constant: false,
1618 cannot_differ: false,
1619 gaps,
1620 run: return_plan.run,
1621 infected: Box::new(move |bin, m| {
1622 tests_where(bin.trace.returns.get(&id), |obs| match m {
1623 Mutation::Const(value) => obs.infected_by_const(value),
1624 _ => obs.reached(),
1625 })
1626 }),
1627 reaching: Box::new(move |bin| {
1628 tests_where(bin.trace.returns.get(&id), plan::ReturnObs::reached)
1629 }),
1630 }
1631 }
1632 })
1633 }
1634
1635 fn job(
1636 &self,
1637 site: u32,
1638 mutation: Mutation,
1639 tests_of: &dyn Fn(&TestBinary) -> BTreeSet<String>,
1640 ) -> Job {
1641 let tests = self
1642 .binaries
1643 .iter()
1644 .enumerate()
1645 .filter_map(|(index, bin)| {
1646 let tests = tests_of(bin);
1647 if tests.is_empty() {
1648 return None;
1649 }
1650 let filter = match bin.runner {
1651 Runner::Exe(_) => test_filter(&tests, &bin.tests),
1652 Runner::Doc { .. } => None,
1653 };
1654 Some((index, filter))
1655 })
1656 .collect();
1657 Job {
1658 site,
1659 mutation,
1660 tests,
1661 }
1662 }
1663
1664 fn run_job(&self, job: &Job, sharing: usize) -> Result<JobResult> {
1667 let spec = format!("{}:{}", job.site, job.mutation.encode());
1668 let mut passed = vec![];
1669 let mut tests: Vec<&(usize, Option<Vec<String>>)> = job.tests.iter().collect();
1671 tests.sort_by_key(|(index, _)| self.binaries[*index].baseline);
1672 for (index, filter) in tests {
1673 let bin = &self.binaries[*index];
1674 let outcome = run_binary(
1675 bin,
1676 filter.as_deref(),
1677 &[("TMT_MUTANT", &spec)],
1678 mutant_timeout(bin.baseline),
1679 true,
1680 sharing,
1681 )?;
1682 if outcome != Outcome::Pass {
1683 return Ok(JobResult {
1684 survived: None,
1685 timed_out: outcome == Outcome::Timeout,
1686 unable: outcome == Outcome::Unable,
1687 });
1688 }
1689 match filter {
1690 Some(names) => passed.extend(names.iter().cloned()),
1691 None => passed.push(format!("all tests of `{}`", bin.name)),
1692 }
1693 }
1694 Ok(JobResult {
1695 survived: Some(passed),
1696 timed_out: false,
1697 unable: false,
1698 })
1699 }
1700
1701 fn trace_job(
1704 &self,
1705 job: &Job,
1706 scratch: &Path,
1707 sharing: usize,
1708 ) -> Result<BTreeMap<String, BTreeSet<Change>>> {
1709 let spec = format!("{}:{}", job.site, job.mutation.encode());
1710 let mut all: BTreeMap<String, BTreeSet<Change>> = BTreeMap::new();
1711 for (index, filter) in &job.tests {
1712 let bin = &self.binaries[*index];
1713 let path = scratch.join(format!("effects-{}-{index}.tsv", job.site));
1714 let _ = fs::remove_file(&path);
1715 let trace_env = path.to_string_lossy().into_owned();
1716 let outcome = run_binary(
1717 bin,
1718 filter.as_deref(),
1719 &[("TMT_MUTANT", &spec), ("TMT_TRACE", &trace_env)],
1720 mutant_timeout(bin.traced),
1721 false,
1722 sharing,
1723 )?;
1724 let text = fs::read_to_string(&path).unwrap_or_default();
1725 let _ = fs::remove_file(&path);
1726 if outcome != Outcome::Pass {
1727 continue; }
1729 let mutated = Trace::parse(&text);
1730 let ran: Option<BTreeSet<String>> =
1731 filter.as_ref().map(|names| names.iter().cloned().collect());
1732 for (test, found) in propagation::changes(&bin.trace, &mutated, ran.as_ref(), job.site)
1733 {
1734 all.entry(test).or_default().extend(found);
1735 }
1736 }
1737 Ok(all)
1738 }
1739
1740 fn run_jobs(&self, jobs: &[Job], workers: usize) -> Result<Vec<JobResult>> {
1746 let sharing = workers.clamp(1, jobs.len().max(1));
1747 let mut results = run_pool(jobs.len(), workers, |index| {
1748 self.run_job(&jobs[index], sharing)
1749 })?;
1750 if sharing > 1 {
1751 for (job, result) in jobs.iter().zip(&mut results) {
1752 if result.timed_out {
1753 *result = self.run_job(job, 1)?;
1754 }
1755 }
1756 }
1757 Ok(results)
1758 }
1759}
1760
1761fn run_pool<T: Send>(
1764 count: usize,
1765 workers: usize,
1766 work: impl Fn(usize) -> Result<T> + Sync,
1767) -> Result<Vec<T>> {
1768 let next = std::sync::atomic::AtomicUsize::new(0);
1769 let done: Vec<Vec<(usize, Result<T>)>> = std::thread::scope(|scope| {
1770 let handles: Vec<_> = (0..workers.clamp(1, count.max(1)))
1771 .map(|_| {
1772 scope.spawn(|| {
1773 let mut mine = vec![];
1774 loop {
1775 let index = next.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1777 if index >= count {
1778 return mine;
1779 }
1780 mine.push((index, work(index)));
1781 }
1782 })
1783 })
1784 .collect();
1785 handles
1786 .into_iter()
1787 .map(|h| h.join().expect("worker panicked"))
1788 .collect()
1789 });
1790 let mut slots: Vec<Option<T>> = (0..count).map(|_| None).collect();
1791 for (index, result) in done.into_iter().flatten() {
1792 slots[index] = Some(result?);
1793 }
1794 Ok(slots
1795 .into_iter()
1796 .map(|slot| slot.expect("every job ran"))
1797 .collect())
1798}
1799
1800pub fn run(options: &Options) -> Result<Report> {
1801 let note = |text: &str| {
1802 if options.progress {
1803 eprintln!("tmt: {text}");
1804 }
1805 };
1806 let dir = options
1807 .dir
1808 .canonicalize()
1809 .with_context(|| format!("no such directory: {}", options.dir.display()))?;
1810
1811 let output = Command::new("cargo")
1813 .args(["metadata", "--no-deps", "--format-version", "1"])
1814 .args(options.cargo.flags())
1815 .current_dir(&dir)
1816 .output()
1817 .context("running cargo metadata")?;
1818 if !output.status.success() {
1819 bail!(
1820 "cargo metadata failed:\n{}",
1821 String::from_utf8_lossy(&output.stderr)
1822 );
1823 }
1824 let metadata: Metadata =
1825 serde_json::from_slice(&output.stdout).context("parsing cargo metadata")?;
1826 let package = match &options.package {
1827 Some(name) => metadata.packages.iter().find(|p| &p.name == name),
1828 None => metadata
1829 .packages
1830 .iter()
1831 .find(|p| p.manifest_path.parent() == Some(dir.as_path()))
1832 .or(match &metadata.packages[..] {
1833 [only] => Some(only),
1834 _ => None,
1835 }),
1836 }
1837 .ok_or_else(|| anyhow!("cannot tell which package to analyse; pass --package <name>"))?;
1838 let mut test_packages: Vec<&Package> = vec![package];
1841 for name in &options.also_test {
1842 let other = metadata
1843 .packages
1844 .iter()
1845 .find(|p| &p.name == name)
1846 .ok_or_else(|| anyhow!("--also-test: no package `{name}` in the workspace"))?;
1847 if !test_packages.iter().any(|p| p.name == other.name) {
1848 test_packages.push(other);
1849 }
1850 }
1851 if options.dependents {
1852 for name in dependents_of(&package.name, &metadata.packages) {
1853 if let Some(other) = metadata.packages.iter().find(|p| p.name == name)
1854 && !test_packages.iter().any(|p| p.name == other.name)
1855 {
1856 test_packages.push(other);
1857 }
1858 }
1859 }
1860 let is_kind = |t: &Target, kinds: &[&str]| t.kind.iter().any(|k| kinds.contains(&k.as_str()));
1861 let root_target = package
1862 .targets
1863 .iter()
1864 .find(|t| is_kind(t, &["lib", "rlib", "cdylib", "staticlib", "dylib"]))
1865 .or_else(|| package.targets.iter().find(|t| is_kind(t, &["bin"])))
1866 .ok_or_else(|| anyhow!("package `{}` has no lib or bin target", package.name))?;
1867
1868 let workspace = metadata.workspace_root.canonicalize()?;
1870 let work = match &options.work_dir {
1871 Some(dir) => {
1872 fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
1873 dir.canonicalize()?
1874 }
1875 None => metadata.target_directory.join("tmt"),
1876 };
1877 if workspace.starts_with(&work) {
1880 bail!(
1881 "the work directory {} contains the workspace; choose a directory of its own",
1882 work.display()
1883 );
1884 }
1885 fs::create_dir_all(&work).with_context(|| format!("creating {}", work.display()))?;
1886 let work = work.canonicalize()?;
1887 let copy = work.join("src");
1888 let marker = work.join(WORK_MARKER);
1889 if copy.exists() && !marker.exists() {
1890 bail!(
1891 "{} exists and was not created by tmt; refusing to delete it. \
1892 Choose another --work-dir or remove it yourself.",
1893 copy.display()
1894 );
1895 }
1896 fs::write(
1897 &marker,
1898 "Working directory of tmt (targeted-mutation). Safe to delete.\n",
1899 )?;
1900 let _lock = WorkLock::take(&work)?;
1901 let target_dir = metadata.target_directory.clone();
1902 let skip = |path: &Path| {
1903 path == target_dir
1904 || path == work
1905 || path
1906 .file_name()
1907 .is_some_and(|n| n == ".git" || n == "node_modules")
1908 || (path.parent() == Some(workspace.as_path())
1909 && path.file_name().is_some_and(|n| n == "target"))
1910 };
1911 let state = WorkCopy::open(&work, ©);
1912 fs::create_dir_all(©)?;
1913 let visible = if options.all_files {
1914 None
1915 } else {
1916 git_visible_files(&workspace)?
1917 };
1918 match visible {
1919 Some(files) => {
1922 let copied = copy_git_visible(&workspace, ©, files, &workspace, &skip, &state)?;
1923 note(&format!(
1924 "copied {copied} files (ignored files are left out)"
1925 ));
1926 }
1927 None => copy_tree(&workspace, ©, &workspace, &skip, &state)?,
1928 }
1929 prune(©, &state)?;
1930 let mut manifests: Vec<&Path> = metadata
1932 .packages
1933 .iter()
1934 .map(|p| p.manifest_path.as_path())
1935 .collect();
1936 let root_manifest = metadata.workspace_root.join("Cargo.toml");
1937 manifests.push(&root_manifest);
1938 for manifest in manifests {
1939 let Ok(canonical) = manifest.canonicalize() else {
1940 continue;
1941 };
1942 let (Some(manifest_dir), Ok(relative)) =
1943 (canonical.parent(), canonical.strip_prefix(&workspace))
1944 else {
1945 continue;
1946 };
1947 let text = fs::read_to_string(&canonical)?;
1948 if let Some(rewritten) =
1949 absolutize_path_dependencies(&text, manifest_dir, &workspace, ©)?
1950 {
1951 state.write(©.join(relative), &rewritten)?;
1952 }
1953 }
1954
1955 let in_copy = |path: &Path| -> Result<PathBuf> {
1956 let canonical = path.canonicalize()?;
1957 let relative = canonical
1958 .strip_prefix(&workspace)
1959 .with_context(|| format!("{} is outside the workspace", path.display()))?;
1960 Ok(copy.join(relative))
1961 };
1962 let package_dir = in_copy(
1963 package
1964 .manifest_path
1965 .parent()
1966 .expect("manifest has a parent"),
1967 )?;
1968 let root_file = in_copy(&root_target.src_path)?;
1969 let source_dir = root_file
1970 .parent()
1971 .expect("source file has a parent")
1972 .to_path_buf();
1973
1974 let mut other_roots = HashSet::new();
1976 let mut other_dirs = HashSet::new();
1977 for target in &package.targets {
1978 if target.src_path == root_target.src_path {
1979 continue;
1980 }
1981 let path = in_copy(&target.src_path)?;
1982 if let Some(parent) = path.parent().filter(|p| *p != source_dir) {
1983 other_dirs.insert(parent.to_path_buf());
1984 }
1985 other_roots.insert(path);
1986 }
1987 let mut paths = vec![];
1988 rust_files(
1989 &source_dir,
1990 &|p| {
1991 other_roots.contains(p)
1992 || other_dirs.contains(p)
1993 || p.file_name().is_some_and(|n| n == "target")
1994 },
1995 &mut paths,
1996 )?;
1997 let mut files = vec![];
1998 let mut test_only = HashSet::new();
1999 let mut next_id = 0u32;
2000 for path in paths {
2001 let Some(original) = state.original(&path, &workspace)? else {
2002 continue; };
2004 let display = path
2005 .strip_prefix(&package_dir)
2006 .unwrap_or(&path)
2007 .display()
2008 .to_string();
2009 match instrument::discover(&original, next_id) {
2010 Ok(found) => {
2011 next_id += found.sites.len() as u32;
2012 for module in &found.test_modules {
2013 test_only.extend(module_paths(&path, module));
2014 }
2015 let places = found
2016 .sites
2017 .iter()
2018 .chain(&found.rebuild_sites)
2019 .map(|site| {
2020 let at = report::location("", site);
2021 (at.line, at.column, at.code)
2022 })
2023 .collect();
2024 files.push(SourceFile {
2025 display,
2026 path,
2027 original,
2028 places,
2029 sites: found.sites,
2030 rebuild_sites: found.rebuild_sites,
2031 rendered: None,
2032 });
2033 }
2034 Err(err) => note(&format!("skipping {display}: {err:#}")),
2035 }
2036 }
2037 files.retain(|f| !f.path.ancestors().any(|a| test_only.contains(a)));
2038
2039 let scope = requested_scope(options, &workspace, &package_dir, ©)?;
2041 if let Some(scope) = &scope {
2042 for file in &mut files {
2043 let relative = file
2044 .path
2045 .strip_prefix(©)
2046 .unwrap_or(&file.path)
2047 .to_string_lossy()
2048 .into_owned();
2049 let original = &file.original;
2050 let in_scope = |site: &Site| {
2051 scope.touches(&relative, scope::line_of(original, site.start), scope::line_of(original, site.end))
2052 || scope.touches(&relative, site.line, site.line)
2054 };
2055 file.sites.retain(in_scope);
2056 file.rebuild_sites.retain(in_scope);
2057 }
2058 files.retain(|f| !f.sites.is_empty() || !f.rebuild_sites.is_empty() || f.path == root_file);
2059 }
2060 let total_sites: usize = files
2061 .iter()
2062 .map(|f| f.sites.len() + f.rebuild_sites.len())
2063 .sum();
2064 note(&format!("{} sites in {} files", total_sites, files.len()));
2065
2066 let root_source = state
2067 .original(&root_file, &workspace)?
2068 .with_context(|| format!("{} is missing", root_target.src_path.display()))?;
2069 state.write(
2070 &source_dir.join(format!("{RUNTIME_MOD}.rs")),
2071 crate::RUNTIME_SOURCE,
2072 )?;
2073 let std_alias = format!("extern crate std as {STD_ALIAS};");
2074 let root_suffix = if root_source.contains(&std_alias) {
2075 format!("\n#[doc(hidden)]\nmod {RUNTIME_MOD};\n")
2076 } else {
2077 format!("\n#[doc(hidden)]\n{std_alias}\n#[doc(hidden)]\nmod {RUNTIME_MOD};\n")
2078 };
2079
2080 let mut disabled: HashSet<u32> = HashSet::new();
2082 let build_target = work.join("target");
2083 let cargo_build = || {
2084 Command::new("cargo")
2085 .args(["test", "--no-run", "--message-format=json"])
2086 .args(test_packages.iter().flat_map(|p| ["-p", p.name.as_str()]))
2087 .args(options.cargo.flags())
2088 .current_dir(©)
2089 .env("CARGO_TARGET_DIR", &build_target)
2090 .envs(profile_env(options.opt_level))
2091 .stderr(Stdio::piped())
2092 .output()
2093 .context("running cargo test --no-run")
2094 };
2095 let mut rounds = 0;
2096 let build = loop {
2097 for file in &mut files {
2098 let rendered =
2099 instrument::render(&file.original, &file.sites, &|id| !disabled.contains(&id));
2100 let mut text = rendered.text.clone();
2101 if file.path == root_file {
2102 text.push_str(&root_suffix);
2103 }
2104 state.write(&file.path, &text)?;
2105 file.rendered = Some(rendered);
2106 }
2107 if !files.iter().any(|f| f.path == root_file) {
2108 state.write(&root_file, &format!("{root_source}{root_suffix}"))?;
2109 }
2110 if rounds == 0 {
2111 state.settle(&workspace)?;
2112 }
2113 note(if rounds == 0 {
2114 "building the instrumented crate"
2115 } else {
2116 "rebuilding without the sites that failed to compile"
2117 });
2118 let output = cargo_build()?;
2119 let names: Vec<&str> = test_packages.iter().map(|p| p.name.as_str()).collect();
2120 let build = parse_build_output(&String::from_utf8_lossy(&output.stdout), &names);
2121 if output.status.success() {
2122 break build;
2123 }
2124 if build.errors.is_empty() {
2125 bail!(
2126 "the build failed:\n{}",
2127 String::from_utf8_lossy(&output.stderr)
2128 );
2129 }
2130 rounds += 1;
2131 let before = disabled.len();
2132 let mut unexplained = vec![];
2133 let mut blamed_now: HashSet<u32> = HashSet::new();
2134 for error in &build.errors {
2135 let blamed = blame_error(error, &files, ©, &disabled);
2136 if std::env::var_os("TMT_DEBUG").is_some() {
2137 eprintln!("tmt: debug: blaming {blamed:?} for\n{}", error.rendered);
2138 }
2139 if blamed.is_empty() {
2140 unexplained.push(error);
2141 }
2142 blamed_now.extend(blamed);
2143 }
2144 disabled.extend(blamed_now);
2145 if disabled.len() == before || rounds > MAX_REPAIR_ROUNDS {
2146 let shown = unexplained
2147 .first()
2148 .copied()
2149 .or(build.errors.first())
2150 .map_or("", |e| e.rendered.as_str());
2151 bail!(
2152 "the crate does not build after instrumentation, and the error is not at a probe.\n\
2153 Does `cargo test --no-run` pass on the original?\n{shown}"
2154 );
2155 }
2156 };
2157 if build.test_binaries.is_empty() {
2158 bail!("`{}` has no test binaries", package.name);
2159 }
2160
2161 let mut session = Session {
2163 progress: options.progress,
2164 package_dir,
2165 binaries: vec![],
2166 };
2167 let mut runners: Vec<(String, Runner, PathBuf)> = vec![];
2168 for (name, exe, owner) in build.test_binaries {
2169 let owner_package = test_packages
2170 .iter()
2171 .find(|p| p.name == owner)
2172 .expect("binaries are filtered by these packages");
2173 let cwd = in_copy(
2174 owner_package
2175 .manifest_path
2176 .parent()
2177 .expect("manifest has a parent"),
2178 )?;
2179 let name = if owner == package.name {
2181 name
2182 } else {
2183 format!("{owner}::{name}")
2184 };
2185 runners.push((name, Runner::Exe(exe), cwd));
2186 }
2187 if options.doc && is_kind(root_target, &["lib", "rlib", "proc-macro"]) {
2188 let doc = Runner::Doc {
2189 copy: copy.clone(),
2190 target_dir: build_target.clone(),
2191 package: package.name.clone(),
2192 opt_level: options.opt_level,
2193 flags: options.cargo.flags(),
2194 };
2195 runners.push(("doc tests".to_string(), doc, session.package_dir.clone()));
2196 }
2197 let marks = marks_dir(&work)?;
2202 for (index, (name, runner, cwd)) in runners.into_iter().enumerate() {
2203 let trace_path = work.join(format!("trace-{index}.tsv"));
2204 let _ = fs::remove_file(&trace_path);
2205 let mut bin = TestBinary {
2206 name,
2207 cwd,
2208 marks: marks.clone(),
2209 tests: BTreeSet::new(),
2210 runner,
2211 baseline: Duration::ZERO,
2212 traced: Duration::ZERO,
2213 trace: Trace::default(),
2214 };
2215 session.note(&format!("tracing `{}`", bin.name));
2216 let started = Instant::now();
2217 let trace_env = trace_path.to_string_lossy().into_owned();
2218 let outcome = run_binary(
2219 &bin,
2220 None,
2221 &[("TMT_TRACE", &trace_env)],
2222 Duration::from_secs(3600),
2223 false,
2224 1,
2225 )?;
2226 if outcome != Outcome::Pass {
2227 bail!(
2228 "the tests in `{}` do not pass on the unmutated code; fix them first",
2229 bin.name
2230 );
2231 }
2232 bin.traced = started.elapsed();
2233 bin.baseline = bin.traced;
2234 if bin.traced > SLOW_TRACE {
2237 let started = Instant::now();
2238 match run_binary(&bin, None, &[], bin.traced, false, 1)? {
2239 Outcome::Pass => bin.baseline = started.elapsed(),
2240 Outcome::Fail => bail!(
2242 "the tests of `{}` pass while their run is recorded and fail without: \
2243 they do not always give the same result, and nothing can be concluded \
2244 from running them",
2245 bin.name
2246 ),
2247 Outcome::Timeout | Outcome::Unable => {}
2248 }
2249 }
2250 let text = match fs::read_to_string(&trace_path) {
2253 Ok(text) => text,
2254 Err(err) if err.kind() == std::io::ErrorKind::NotFound => String::new(),
2255 Err(err) => bail!("cannot read the trace of `{}`: {err}", bin.name),
2256 };
2257 bin.trace = Trace::parse(&text);
2258 if bin.trace.malformed_lines > 0 {
2259 bail!(
2260 "the trace of `{}` has {} malformed lines; not drawing conclusions from it",
2261 bin.name,
2262 bin.trace.malformed_lines
2263 );
2264 }
2265 if let Runner::Exe(exe) = &bin.runner {
2266 let listing = Command::new(exe)
2267 .args(["--list", "--format", "terse"])
2268 .current_dir(&bin.cwd)
2269 .stdin(Stdio::null())
2270 .stderr(Stdio::null())
2271 .output()
2272 .with_context(|| format!("listing the tests of `{}`", bin.name))?;
2273 bin.tests = parse_test_list(&String::from_utf8_lossy(&listing.stdout));
2274 }
2275 session.binaries.push(bin);
2276 }
2277
2278 let mut report = Report {
2280 package: package.name.clone(),
2281 sites: total_sites,
2282 analysis: report::Analysis {
2283 package_path: repository_prefix(
2284 package.manifest_path.parent().unwrap_or(Path::new(".")),
2285 ),
2286 since: options.since.clone(),
2287 lines: options.lines.clone(),
2288 tests_of: test_packages.iter().map(|p| p.name.clone()).collect(),
2289 cargo: options.cargo.clone(),
2290 opt_level: options.opt_level,
2291 rebuild: options.rebuild,
2292 verified: options.verify,
2293 doc_tests: options.doc,
2294 },
2295 ..Report::default()
2296 };
2297 for site in files.iter().flat_map(|f| &f.sites) {
2298 if disabled.contains(&site.id) {
2299 match site.kind {
2300 SiteKind::Body { .. } => report.unviable_mutants += 1,
2301 _ if options.rebuild && !instrument::source_mutants(site).is_empty() => {}
2303 _ => report.skipped_sites += 1,
2304 }
2305 }
2306 }
2307 let scratch = work.clone();
2308 let mut jobs: Vec<Job> = vec![];
2309 let mut not_evaluated: HashSet<u32> = HashSet::new();
2312 let mut work: Vec<SiteWork> = vec![];
2313 let mut effect_jobs: Vec<(usize, usize)> = vec![];
2315 for file in &files {
2316 for site in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
2317 let plan = match session.plan(&file.display, site, options.verify) {
2318 Planned::Unreached => {
2319 let at = report::location(&file.display, site);
2321 if report.unreached.last() != Some(&at) {
2322 report.unreached.push(at);
2323 }
2324 continue;
2325 }
2326 Planned::Nothing => continue,
2327 Planned::NotEvaluated => {
2328 not_evaluated.insert(site.id);
2329 continue;
2330 }
2331 Planned::Plan(plan) => plan,
2332 };
2333 let mut add =
2334 |mutation: Mutation, tests_of: &dyn Fn(&TestBinary) -> BTreeSet<String>| {
2335 jobs.push(session.job(site.id, mutation, tests_of));
2336 jobs.len() - 1
2337 };
2338 let gaps = plan
2339 .gaps
2340 .into_iter()
2341 .map(
2342 |PlannedGap {
2343 finding,
2344 survivors,
2345 constant_expr,
2346 }| {
2347 let confirm = if options.verify {
2350 survivors
2351 .into_iter()
2352 .map(|m| add(m, &*plan.reaching))
2353 .collect()
2354 } else {
2355 vec![]
2356 };
2357 (finding, confirm, constant_expr)
2358 },
2359 )
2360 .collect();
2361 let infected = &plan.infected;
2362 let runs = plan
2363 .run
2364 .iter()
2365 .map(|m| (*m, add(*m, &|bin| infected(bin, *m))))
2366 .collect();
2367 work.push(SiteWork {
2368 file: &file.display,
2369 site,
2370 gaps,
2371 constant: plan.constant,
2372 cannot_differ: plan.cannot_differ,
2373 runs,
2374 });
2375 }
2376 }
2377 session.note(&format!(
2378 "running {} mutants on {} thread(s)",
2379 jobs.len(),
2380 options.jobs.max(1)
2381 ));
2382 let mut results = session.run_jobs(&jobs, options.jobs)?;
2383
2384 if let Some(wanted) = options.audit {
2387 let survivors: Vec<usize> = (0..jobs.len())
2388 .filter(|job| results[*job].survived.is_some())
2389 .collect();
2390 let chosen: Vec<usize> = spread(survivors.len(), wanted)
2391 .into_iter()
2392 .map(|nth| survivors[nth])
2393 .collect();
2394 session.note(&format!(
2395 "audit: running {} of {} surviving mutants against all tests",
2396 chosen.len(),
2397 survivors.len()
2398 ));
2399 let against_all: Vec<Job> = chosen
2400 .iter()
2401 .map(|job| Job {
2402 site: jobs[*job].site,
2403 mutation: jobs[*job].mutation,
2404 tests: (0..session.binaries.len()).map(|bin| (bin, None)).collect(),
2405 })
2406 .collect();
2407 let mut audit = report::Audit {
2408 sampled: chosen.len(),
2409 survivors: survivors.len(),
2410 ..report::Audit::default()
2411 };
2412 for (job, again) in chosen
2413 .iter()
2414 .zip(session.run_jobs(&against_all, options.jobs)?)
2415 {
2416 if again.survived.is_none() {
2417 results[*job] = again;
2419 let site = files
2420 .iter()
2421 .find_map(|f| Some((f, f.sites.iter().find(|s| s.id == jobs[*job].site)?)));
2422 if let Some((file, site)) = site {
2423 audit
2424 .disagreements
2425 .push(report::location(&file.display, site));
2426 }
2427 }
2428 }
2429 session.note("audit: recording the tests once more");
2430 for (index, bin) in session.binaries.iter().enumerate() {
2431 let path = scratch.join(format!("trace-{index}-audit.tsv"));
2432 let _ = fs::remove_file(&path);
2433 let trace_env = path.to_string_lossy().into_owned();
2434 let limit = Duration::from_secs(3600);
2435 let outcome = run_binary(bin, None, &[("TMT_TRACE", &trace_env)], limit, false, 1)?;
2436 let again = Trace::parse(&fs::read_to_string(&path).unwrap_or_default());
2437 let _ = fs::remove_file(&path);
2438 let records = bin.trace.differences(&again);
2439 if outcome != Outcome::Pass || records > 0 {
2440 audit.trace_differences.push(report::TraceDifference {
2441 binary: bin.name.clone(),
2442 records,
2443 });
2444 }
2445 }
2446 report.audit = Some(audit);
2447 }
2448 let unable = results.iter().filter(|r| r.unable).count();
2449 not_evaluated.extend(
2450 jobs.iter()
2451 .zip(&results)
2452 .filter(|(_, result)| result.unable)
2453 .map(|(job, _)| job.site),
2454 );
2455 if !options.rebuild {
2456 report.mutants_not_evaluated = not_evaluated.len();
2457 }
2458 report.mutants_run = results.len() - unable;
2459 report.mutants_killed = results.iter().filter(|r| r.survived.is_none()).count() - unable;
2460 report.mutants_timed_out = results.iter().filter(|r| r.timed_out).count();
2461
2462 let confirmed = |w: &SiteWork| {
2465 w.gaps
2466 .iter()
2467 .all(|(_, confirm, _)| confirm.iter().all(|j| results[*j].survived.is_some()))
2468 };
2469 let constants: BTreeSet<(&str, usize, usize)> = work
2470 .iter()
2471 .filter(|w| w.cannot_differ || (w.constant && confirmed(w)))
2472 .map(|w| (w.file, w.site.start, w.site.end))
2473 .collect();
2474 for item in &work {
2475 let at = report::location(item.file, item.site);
2476 for (finding, confirm, constant_expr) in &item.gaps {
2477 let repeats = constant_expr
2480 .is_some_and(|(start, end)| constants.contains(&(item.file, start, end)));
2481 if confirm.iter().any(|j| results[*j].survived.is_none()) {
2482 report.unstable.push(at.clone());
2483 } else if !repeats {
2484 report.findings.push(finding.clone());
2485 }
2486 }
2487 if let SiteKind::Body {
2490 sole_expr: Some((start, end)),
2491 ..
2492 } = item.site.kind
2493 && constants.contains(&(item.file, start, end))
2494 {
2495 continue;
2496 }
2497 let mut survivors = vec![];
2498 let mut passing_tests = BTreeSet::new();
2499 for (mutation, job) in &item.runs {
2500 if let Some(tests) = &results[*job].survived {
2501 survivors.push(report::describe(item.site, *mutation));
2502 passing_tests.extend(tests.iter().cloned());
2503 }
2504 }
2505 if !survivors.is_empty() {
2506 let first = item
2508 .runs
2509 .iter()
2510 .find(|(_, job)| results[*job].survived.is_some());
2511 effect_jobs.push((report.findings.len(), first.expect("a survivor").1));
2512 report.findings.push(Finding::AssertionGap {
2513 at,
2514 survivors,
2515 tests: passing_tests.into_iter().collect(),
2516 effects: vec![],
2517 effects_of: None,
2518 });
2519 }
2520 }
2521
2522 if options.effects && !effect_jobs.is_empty() {
2524 session.note(&format!("tracing {} surviving mutants", effect_jobs.len()));
2525 let sites: BTreeMap<u32, (&str, &Site)> = files
2526 .iter()
2527 .flat_map(|f| f.sites.iter().map(move |s| (s.id, (f.display.as_str(), s))))
2528 .collect();
2529 let traced = run_pool(effect_jobs.len(), options.jobs, |index| {
2530 session.trace_job(
2531 &jobs[effect_jobs[index].1],
2532 &scratch,
2533 options.jobs.clamp(1, effect_jobs.len()),
2534 )
2535 })?;
2536 for ((finding, job), mut changes) in effect_jobs.iter().zip(traced) {
2537 if let Some((mutated_file, mutated)) = sites.get(&jobs[*job].site) {
2540 for found in changes.values_mut() {
2541 found.retain(|change| {
2542 sites.get(&change.site()).is_none_or(|(file, site)| {
2543 file != mutated_file
2544 || site.end <= mutated.start
2545 || mutated.end <= site.start
2546 })
2547 });
2548 }
2549 changes.retain(|_, found| !found.is_empty());
2550 }
2551 if let Finding::AssertionGap {
2552 effects,
2553 effects_of,
2554 ..
2555 } = &mut report.findings[*finding]
2556 {
2557 *effects = describe_effects(&changes, &sites);
2558 *effects_of = sites
2559 .get(&jobs[*job].site)
2560 .map(|(_, site)| report::describe(site, jobs[*job].mutation));
2561 }
2562 }
2563 }
2564
2565 let mut built: Vec<(&SourceFile, &Site, instrument::SourceMutant, Option<usize>)> = vec![];
2569 for file in &files {
2570 let retried = file.sites.iter().filter(|site| {
2573 (disabled.contains(&site.id) && !matches!(site.kind, SiteKind::Body { .. }))
2574 || not_evaluated.contains(&site.id)
2575 });
2576 for site in file.rebuild_sites.iter().chain(retried) {
2577 built.extend(
2578 instrument::source_mutants(site)
2579 .into_iter()
2580 .map(|mutant| (file, site, mutant, None)),
2581 );
2582 }
2583 }
2584 if !options.rebuild {
2585 report.mutants_not_built = built.len();
2586 built.clear();
2587 }
2588 if let (Some(wanted), Some(audit)) = (options.audit, report.audit.as_mut()) {
2591 let mut twins = vec![];
2592 for file in &files {
2593 for site in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
2594 let integers = session.binaries.iter().all(|bin| {
2596 let seen = bin.trace.merged(site.id);
2597 !seen.reached() || seen.valued()
2598 });
2599 let job_of = |mutation: Mutation| {
2600 jobs.iter()
2601 .position(|job| job.site == site.id && job.mutation == mutation)
2602 };
2603 let mut compared = vec![];
2604 for mutant in instrument::source_mutants(site) {
2605 let job = mutations_like(site, &mutant, integers)
2607 .into_iter()
2608 .find_map(job_of);
2609 if let Some(job) = job {
2610 compared.push(job);
2611 twins.push((file, site, mutant, Some(job)));
2612 }
2613 }
2614 if let (SiteKind::Cmp { op, .. }, Some(job)) =
2617 (&site.kind, job_of(Mutation::Negate))
2618 && !compared.contains(&job)
2619 {
2620 let negated = instrument::SourceMutant {
2621 start: site.start,
2622 end: site.end,
2623 replacement: format!("!({})", site.text),
2624 what: op.symbol().to_string(),
2625 into: "!".to_string(),
2626 };
2627 twins.push((file, site, negated, Some(job)));
2628 }
2629 }
2630 }
2631 let chosen = spread(twins.len(), wanted);
2632 audit.rebuilt = chosen.len();
2633 let mut twins: Vec<Option<_>> = twins.into_iter().map(Some).collect();
2634 built.extend(chosen.into_iter().filter_map(|nth| twins[nth].take()));
2635 }
2636 if !built.is_empty() {
2637 session.note(&format!(
2638 "building {} mutants one by one (code a probe cannot be put in, or to compare with the probe)",
2639 built.len()
2640 ));
2641 let instrumented = |file: &SourceFile, text: &str| {
2642 if file.path == root_file {
2643 format!("{text}{root_suffix}")
2644 } else {
2645 text.to_string()
2646 }
2647 };
2648 let mut by_speed: Vec<&TestBinary> = session.binaries.iter().collect();
2651 by_speed.sort_by_key(|bin| bin.baseline);
2652 let mut survivors: Vec<(report::Location, Vec<String>)> = vec![];
2653 for (file, site, mutant, twin) in &built {
2654 let mutated = format!(
2655 "{}{}{}",
2656 &file.original[..mutant.start],
2657 mutant.replacement,
2658 &file.original[mutant.end..]
2659 );
2660 let attempt = || -> Result<Option<Outcome>> {
2662 state.write(&file.path, &instrumented(file, &mutated))?;
2663 if !cargo_build()?.status.success() {
2664 return Ok(None);
2665 }
2666 for bin in &by_speed {
2667 let outcome =
2668 run_binary(bin, None, &[], mutant_timeout(bin.baseline), true, 1)?;
2669 if outcome != Outcome::Pass {
2670 return Ok(Some(outcome));
2671 }
2672 }
2673 Ok(Some(Outcome::Pass))
2674 };
2675 let attempted = attempt();
2676 let rendered = file.rendered.as_ref().expect("rendered before building");
2678 state.write(&file.path, &instrumented(file, &rendered.text))?;
2679 let outcome = attempted?;
2680 if let Some(job) = twin {
2681 let as_probe = results[*job].survived.is_some();
2683 let Some(audit) = report.audit.as_mut() else {
2684 continue;
2685 };
2686 let comparable = outcome.filter(|_| !results[*job].unable);
2688 match comparable {
2689 Some(_) => audit.compared += 1,
2690 None => audit.not_compared += 1,
2691 }
2692 if comparable.is_some_and(|built| (built == Outcome::Pass) != as_probe) {
2693 let verdict = |passes: bool| if passes { "passes" } else { "fails" };
2694 audit.source_disagreements.push(report::SourceDisagreement {
2695 at: report::location(&file.display, site),
2696 mutant: report::describe(site, mutation_of(site, mutant)),
2697 as_probe: verdict(as_probe).to_string(),
2698 built: verdict(!as_probe).to_string(),
2699 });
2700 }
2701 continue;
2702 }
2703 match outcome {
2704 None => report.unviable_mutants += 1,
2705 Some(outcome) => {
2706 report.mutants_run += 1;
2707 report.mutants_killed += (outcome != Outcome::Pass) as usize;
2708 report.mutants_timed_out += (outcome == Outcome::Timeout) as usize;
2709 }
2710 }
2711 let survived = outcome == Some(Outcome::Pass);
2712 if survived {
2713 let at = report::location(&file.display, site);
2714 let text = report::describe(site, mutation_of(site, mutant));
2715 match survivors.last_mut() {
2716 Some((last, texts)) if *last == at => texts.push(text),
2717 _ => survivors.push((at, vec![text])),
2718 }
2719 }
2720 }
2721 report.findings.extend(
2722 survivors
2723 .into_iter()
2724 .map(|(at, survivors)| Finding::Survivor { at, survivors }),
2725 );
2726 }
2727
2728 report.sort_findings();
2729 let places: Vec<FilePlaces> = files
2730 .iter()
2731 .map(|file| FilePlaces {
2732 display: &file.display,
2733 source: &file.original,
2734 places: &file.places,
2735 })
2736 .collect();
2737 name_findings(&mut report.findings, &places);
2738
2739 let ignored: BTreeMap<&str, BTreeMap<usize, String>> = files
2741 .iter()
2742 .map(|f| {
2743 (
2744 f.display.as_str(),
2745 crate::baseline::ignored_lines(&f.original),
2746 )
2747 })
2748 .collect();
2749 let known = match &options.baseline {
2750 Some(path) => Some(crate::baseline::load(path)?),
2751 None => None,
2752 };
2753 let location = |finding: &Finding| (finding.at().file.clone(), finding.at().line);
2754 let before = report.findings.len();
2755 report.findings.retain(|finding| {
2756 let (file, line) = location(finding);
2757 !ignored
2758 .get(file.as_str())
2759 .is_some_and(|lines| lines.contains_key(&line))
2760 });
2761 if let Some(path) = &options.write_baseline {
2762 crate::baseline::write(path, &report.findings)?;
2763 }
2764 report
2765 .findings
2766 .retain(|finding| !known.as_ref().is_some_and(|known| known.knows(finding)));
2767 report.suppressed = before - report.findings.len();
2768 Ok(report)
2769}
2770
2771fn repository_prefix(dir: &Path) -> String {
2775 let shown = Command::new("git")
2776 .arg("-C")
2777 .arg(dir)
2778 .args(["rev-parse", "--show-prefix"])
2779 .stderr(Stdio::null())
2780 .output();
2781 match shown {
2782 Ok(output) if output.status.success() => {
2783 String::from_utf8_lossy(&output.stdout).trim().to_string()
2784 }
2785 _ => String::new(),
2786 }
2787}
2788
2789fn spread(count: usize, wanted: usize) -> Vec<usize> {
2792 let wanted = wanted.min(count);
2793 (0..wanted).map(|nth| nth * count / wanted).collect()
2794}
2795
2796struct FilePlaces<'a> {
2798 display: &'a str,
2799 source: &'a str,
2800 places: &'a [(usize, usize, String)],
2802}
2803
2804fn name_findings(findings: &mut [Finding], files: &[FilePlaces]) {
2809 for file in files {
2810 let items = instrument::named_items(file.source);
2811 let item_at = |line: usize, column: usize| -> String {
2812 instrument::offset_of(file.source, line, column)
2813 .map_or("", |offset| instrument::enclosing_item(&items, offset))
2814 .to_string()
2815 };
2816 let places: BTreeSet<(String, &str, usize, usize)> = file
2818 .places
2819 .iter()
2820 .map(|(line, column, code)| (item_at(*line, *column), code.as_str(), *line, *column))
2821 .collect();
2822 for finding in findings.iter_mut() {
2823 let kind = finding.kind();
2824 let at = finding.at_mut();
2825 if at.file != file.display {
2826 continue;
2827 }
2828 at.item = item_at(at.line, at.column);
2829 let nth = places
2830 .iter()
2831 .filter(|(item, code, line, column)| {
2832 *item == at.item && *code == at.code && (*line, *column) < (at.line, at.column)
2833 })
2834 .count();
2835 at.id = report::finding_id(kind, at, nth);
2836 }
2837 }
2838}
2839
2840fn mutation_of(site: &Site, mutant: &instrument::SourceMutant) -> Mutation {
2842 match &site.kind {
2843 SiteKind::Cmp { .. } => plan::CmpOp::ALL
2844 .into_iter()
2845 .find(|op| op.symbol() == mutant.into)
2846 .map_or(Mutation::Negate, Mutation::Op),
2847 SiteKind::Arith { op, .. } => {
2848 if mutant.into.trim_end_matches('=') == op.swapped().symbol() {
2849 Mutation::ArithSwap
2850 } else {
2851 Mutation::ArithSwap2
2852 }
2853 }
2854 SiteKind::Guard { .. } => Mutation::Const(mutant.into == "true"),
2855 SiteKind::Logic { .. } => Mutation::LogicSwap,
2856 SiteKind::Not { .. } => Mutation::DropNot,
2857 SiteKind::Range { .. } => Mutation::RangeEnd,
2858 _ => Mutation::Delete,
2861 }
2862}
2863
2864fn mutations_like(site: &Site, mutant: &instrument::SourceMutant, integers: bool) -> Vec<Mutation> {
2873 let mut all = vec![mutation_of(site, mutant)];
2874 if let (SiteKind::Cmp { op, .. }, Mutation::Op(into)) = (&site.kind, all[0]) {
2875 let an_order_is_needed = matches!(op, plan::CmpOp::Le | plan::CmpOp::Ge);
2876 if into == op.negated() && (integers || !an_order_is_needed) {
2877 all.push(Mutation::Negate);
2878 }
2879 match (op, into) {
2880 (plan::CmpOp::Lt, plan::CmpOp::Le) | (plan::CmpOp::Ge, plan::CmpOp::Gt) => {
2881 all.push(Mutation::Shift(1))
2882 }
2883 (plan::CmpOp::Gt, plan::CmpOp::Ge) | (plan::CmpOp::Le, plan::CmpOp::Lt) => {
2884 all.push(Mutation::Shift(-1))
2885 }
2886 _ => {}
2887 }
2888 }
2889 all
2890}
2891
2892fn describe_effects(
2895 changes: &BTreeMap<String, BTreeSet<Change>>,
2896 sites: &BTreeMap<u32, (&str, &Site)>,
2897) -> Vec<String> {
2898 let mut by_change: BTreeMap<&Change, Vec<&str>> = BTreeMap::new();
2899 for (test, found) in changes {
2900 for change in found {
2901 by_change.entry(change).or_default().push(test);
2902 }
2903 }
2904 if by_change.is_empty() {
2905 return vec![
2906 "with the mutant, these tests still reach the same code with the same outcomes: they do not use its result, or it is the same for their inputs".to_string(),
2907 ];
2908 }
2909 let mut out = vec![];
2910 for (change, tests) in by_change.iter().take(3) {
2911 let Some((file, site)) = sites.get(&change.site()) else {
2912 continue;
2913 };
2914 let code = report::location(file, site).code;
2915 let at = format!("{file}:{}", site.line);
2916 let who = match tests[..] {
2917 ["?"] => "a test".to_string(),
2918 [one] => format!("`{one}`"),
2919 [first, ..] => format!("`{first}` (and {} more)", tests.len() - 1),
2920 [] => continue,
2921 };
2922 out.push(match change {
2923 Change::Returns { value, .. } => {
2924 format!("with the mutant, {who} gets `{value}` from `{code}` ({at})")
2925 }
2926 Change::NowRuns { .. } => format!("with the mutant, {who} now runs `{code}` ({at})"),
2927 Change::NoLongerRuns { .. } => {
2928 format!("with the mutant, {who} no longer runs `{code}` ({at})")
2929 }
2930 Change::NewOutcome { .. } => {
2931 format!("with the mutant, {who} takes `{code}` ({at}) a way it did not before")
2932 }
2933 });
2934 }
2935 if by_change.len() > 3 {
2936 out.push(format!("(and {} more such changes)", by_change.len() - 3));
2937 }
2938 out
2939}
2940
2941#[cfg(test)]
2942mod tests {
2943 use super::*;
2944 use crate::trace::UNKNOWN_TEST;
2945
2946 #[test]
2947 fn parses_cargo_json_messages() {
2948 let stdout = concat!(
2949 r#"{"reason":"compiler-artifact","package_id":"p 0.1.0","target":{"name":"p","kind":["lib"]},"profile":{"test":false},"executable":null}"#,
2950 "\n",
2951 r#"{"reason":"compiler-artifact","package_id":"p 0.1.0","target":{"name":"p","kind":["lib"]},"profile":{"test":true},"executable":"/t/p-abc"}"#,
2952 "\n",
2953 r#"{"reason":"compiler-artifact","package_id":"dep 1.0.0","target":{"name":"dep","kind":["lib"]},"profile":{"test":true},"executable":"/t/dep-abc"}"#,
2954 "\n",
2955 r#"{"reason":"compiler-message","message":{"level":"warning","rendered":"w","spans":[{"file_name":"src/lib.rs","byte_start":1,"line_start":1,"is_primary":true}]}}"#,
2956 "\n",
2957 r#"{"reason":"compiler-message","message":{"level":"error","rendered":"E0308","spans":[{"file_name":"src/lib.rs","byte_start":40,"line_start":3,"is_primary":true},{"file_name":"src/lib.rs","byte_start":2,"line_start":1,"is_primary":false}]}}"#,
2958 "\n",
2959 r#"{"reason":"compiler-message","message":{"level":"error","rendered":"E0308","spans":[{"file_name":"src/lib.rs","byte_start":40,"line_start":3,"is_primary":true},{"file_name":"src/lib.rs","byte_start":2,"line_start":1,"is_primary":false}]}}"#,
2960 "\n",
2961 r#"{"reason":"compiler-message","message":{"level":"error","rendered":"aborting","spans":[]}}"#,
2962 "\n",
2963 "not json\n",
2964 r#"{"reason":"build-finished","success":false}"#,
2965 "\n",
2966 );
2967 let out = parse_build_output(stdout, &["p", "other"]);
2968 assert_eq!(
2969 out.test_binaries,
2970 [("p".to_string(), PathBuf::from("/t/p-abc"), "p".to_string())]
2971 );
2972 let both = parse_build_output(stdout, &["dep", "p"]);
2974 let owners: Vec<&str> = both.test_binaries.iter().map(|b| b.2.as_str()).collect();
2975 assert_eq!(owners, ["p", "dep"]);
2976 assert_eq!(
2977 out.errors,
2978 [CompileError {
2979 primary: vec![ErrorSpan {
2980 file: "src/lib.rs".into(),
2981 byte_start: 40,
2982 line: 3
2983 }],
2984 secondary: vec![ErrorSpan {
2985 file: "src/lib.rs".into(),
2986 byte_start: 2,
2987 line: 1
2988 }],
2989 rendered: "E0308".into(),
2990 }]
2991 );
2992 }
2993
2994 #[test]
2995 fn package_ids_are_matched_by_name() {
2996 assert!(is_package(
2997 "path+file:///w/target/tmt/src#eligibility@0.0.0",
2998 "eligibility"
2999 ));
3000 assert!(is_package(
3001 "path+file:///w/eligibility#0.1.0",
3002 "eligibility"
3003 ));
3004 assert!(is_package(
3005 "eligibility 0.1.0 (path+file:///w)",
3006 "eligibility"
3007 ));
3008 assert!(!is_package(
3009 "path+file:///w/eligibility#other@0.1.0",
3010 "eligibility-core"
3011 ));
3012 assert!(!is_package(
3013 "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.0",
3014 "eligibility"
3015 ));
3016 }
3017
3018 #[test]
3019 fn test_filter_falls_back_to_the_whole_binary() {
3020 let set = |names: &[&str]| {
3021 names
3022 .iter()
3023 .map(|n| n.to_string())
3024 .collect::<BTreeSet<String>>()
3025 };
3026 let known = set(&["tests::a", "tests::b", "tests::c"]);
3027 assert_eq!(
3028 test_filter(&set(&["tests::a", "tests::b"]), &known),
3029 Some(vec!["tests::a".to_string(), "tests::b".to_string()])
3030 );
3031 assert_eq!(test_filter(&set(&["tests::a", UNKNOWN_TEST]), &known), None);
3033 assert_eq!(test_filter(&set(&["tests::a", "worker"]), &known), None);
3035 assert_eq!(test_filter(&set(&["worker"]), &known), None);
3036
3037 let many: BTreeSet<String> = (0..=MAX_TEST_FILTERS).map(|i| format!("t{i}")).collect();
3038 assert_eq!(test_filter(&many, &many), None);
3039 let limit: BTreeSet<String> = (0..MAX_TEST_FILTERS).map(|i| format!("t{i}")).collect();
3040 assert!(test_filter(&limit, &limit).is_some());
3041 }
3042
3043 #[test]
3044 fn libtest_listing() {
3045 let listing =
3046 "tests::a: test\ntests::nested::b: test\nbench_it: benchmark\n\n2 tests, 1 benchmark\n";
3047 assert_eq!(
3048 parse_test_list(listing).into_iter().collect::<Vec<_>>(),
3049 ["tests::a", "tests::nested::b"]
3050 );
3051 }
3052
3053 #[test]
3054 fn domains_from_type_bounds() {
3055 let u8s = crate::trace::TypeBounds {
3056 lhs: (0, 255),
3057 rhs: (0, 255),
3058 };
3059 assert_eq!(
3060 domain_of(LiteralSide::Rhs(18), Some(&u8s)),
3061 Some((-18, 237))
3062 );
3063 assert_eq!(
3064 domain_of(LiteralSide::Lhs(18), Some(&u8s)),
3065 Some((-237, 18))
3066 );
3067 assert_eq!(domain_of(LiteralSide::None, Some(&u8s)), None);
3068 assert_eq!(domain_of(LiteralSide::Rhs(18), None), None);
3069 let wide = crate::trace::TypeBounds {
3070 lhs: (i128::MIN, 0),
3071 rhs: (0, 0),
3072 };
3073 assert_eq!(
3074 domain_of(LiteralSide::Rhs(1), Some(&wide)),
3075 None,
3076 "overflow is not a domain"
3077 );
3078 }
3079
3080 #[test]
3081 fn out_of_line_module_locations() {
3082 let tests = instrument::TestModule {
3083 name: "tests".into(),
3084 path: None,
3085 };
3086 assert_eq!(
3087 module_paths(Path::new("src/lib.rs"), &tests),
3088 [PathBuf::from("src/tests.rs"), PathBuf::from("src/tests")]
3089 );
3090 assert_eq!(
3091 module_paths(Path::new("src/store.rs"), &tests),
3092 [
3093 PathBuf::from("src/store/tests.rs"),
3094 PathBuf::from("src/store/tests")
3095 ]
3096 );
3097 assert_eq!(
3098 module_paths(Path::new("src/store/mod.rs"), &tests),
3099 [
3100 PathBuf::from("src/store/tests.rs"),
3101 PathBuf::from("src/store/tests")
3102 ]
3103 );
3104 let with_path = instrument::TestModule {
3105 name: "rt".into(),
3106 path: Some("runtime/rt.rs".into()),
3107 };
3108 assert_eq!(
3109 module_paths(Path::new("src/lib.rs"), &with_path),
3110 [PathBuf::from("src/runtime/rt.rs")]
3111 );
3112 }
3113
3114 #[test]
3115 fn path_dependencies_outside_the_workspace_become_absolute() {
3116 let manifest = r#"[package]
3117name = "app"
3118
3119[dependencies]
3120serde = "1"
3121core = { path = "../core" } # inside the workspace: kept
3122outside = { path = "../../outside", version = "1" }
3123
3124[dev-dependencies.helper]
3125path = "../../../far/helper"
3126
3127[target.'cfg(unix)'.dependencies]
3128unix-only = { path = "../../unix" }
3129
3130[patch.crates-io]
3131serde = { path = "../../serde-fork" }
3132"#;
3133 let out = absolutize_path_dependencies(
3134 manifest,
3135 Path::new("/w/ws/app"),
3136 Path::new("/w/ws"),
3137 Path::new("/copy"),
3138 )
3139 .unwrap()
3140 .expect("something to rewrite");
3141 assert!(
3142 out.contains(r#"core = { path = "../core" } # inside the workspace: kept"#),
3143 "{out}"
3144 );
3145 assert!(
3146 out.contains(r#"outside = { path = "/w/outside", version = "1" }"#),
3147 "{out}"
3148 );
3149 assert!(out.contains("path = \"/far/helper\""), "{out}");
3150 assert!(out.contains(r#"unix-only = { path = "/w/unix" }"#), "{out}");
3151 assert!(
3152 out.contains(r#"serde = { path = "/w/serde-fork" }"#),
3153 "{out}"
3154 );
3155 assert!(out.contains("serde = \"1\""), "{out}");
3156
3157 let inside = "[dependencies]\ncore = { path = \"../core\" }\n[workspace.dependencies]\nx = { path = \"x\" }\n";
3158 assert_eq!(
3159 absolutize_path_dependencies(
3160 inside,
3161 Path::new("/w/ws/app"),
3162 Path::new("/w/ws"),
3163 Path::new("/copy")
3164 )
3165 .unwrap(),
3166 None
3167 );
3168 let ws = "[workspace.dependencies]\nshared = { path = \"../shared\" }\n";
3169 let out = absolutize_path_dependencies(
3170 ws,
3171 Path::new("/w/ws"),
3172 Path::new("/w/ws"),
3173 Path::new("/copy"),
3174 )
3175 .unwrap()
3176 .unwrap();
3177 assert!(out.contains(r#"shared = { path = "/w/shared" }"#), "{out}");
3178 assert!(
3179 absolutize_path_dependencies(
3180 "not [ toml",
3181 Path::new("/w"),
3182 Path::new("/w"),
3183 Path::new("/copy")
3184 )
3185 .is_err()
3186 );
3187 assert_eq!(normalize(Path::new("/a/./b/../c")), PathBuf::from("/a/c"));
3188 let absolute = "[dependencies]\nhelper = { path = \"/w/ws/helper\" }\n";
3190 let out = absolutize_path_dependencies(
3191 absolute,
3192 Path::new("/w/ws/app"),
3193 Path::new("/w/ws"),
3194 Path::new("/copy"),
3195 )
3196 .unwrap()
3197 .unwrap();
3198 assert!(
3199 out.contains(r#"helper = { path = "/copy/helper" }"#),
3200 "{out}"
3201 );
3202 }
3203
3204 #[test]
3205 fn pool_runs_every_job_once_and_keeps_the_order() {
3206 use std::sync::atomic::{AtomicUsize, Ordering};
3207 for workers in [0, 1, 2, 3, 8, 100] {
3208 for count in [0, 1, 2, 7, 50] {
3209 let calls: Vec<AtomicUsize> = (0..count).map(|_| AtomicUsize::new(0)).collect();
3210 let results = run_pool(count, workers, |i| {
3211 calls[i].fetch_add(1, Ordering::SeqCst);
3212 std::thread::yield_now();
3213 Ok(i * 10)
3214 })
3215 .unwrap();
3216 assert_eq!(
3217 results,
3218 (0..count).map(|i| i * 10).collect::<Vec<_>>(),
3219 "workers={workers}"
3220 );
3221 assert!(
3222 calls.iter().all(|c| c.load(Ordering::SeqCst) == 1),
3223 "workers={workers} count={count}"
3224 );
3225 }
3226 }
3227 let failed = run_pool(5, 3, |i| {
3228 if i == 3 {
3229 Err(anyhow!("job {i} broke"))
3230 } else {
3231 Ok(i)
3232 }
3233 });
3234 assert_eq!(failed.unwrap_err().to_string(), "job 3 broke");
3235 }
3236
3237 #[test]
3238 fn operand_ranges_ignore_wrapping_parentheses() {
3239 assert_eq!(core_range(10, "a > 0"), (10, 15));
3240 assert_eq!(core_range(10, "(a > 0)"), (11, 16));
3241 assert_eq!(core_range(10, " ( (a > 0) ) "), (14, 19));
3242 assert_eq!(core_range(0, "(a) && (b)"), (0, 10));
3244 assert_eq!(core_range(0, "f(a)"), (0, 4));
3245 assert_eq!(core_range(3, "()"), (4, 4));
3246 assert_eq!(core_range(0, "(a"), (0, 2));
3248 assert_eq!(core_range(0, "a)"), (0, 2));
3249 assert_eq!(core_range(0, ")"), (0, 1));
3250 }
3251
3252 #[test]
3253 fn pool_never_uses_more_threads_than_asked() {
3254 for workers in [1, 2] {
3255 let seen = std::sync::Mutex::new(HashSet::new());
3256 run_pool(6, workers, |_| {
3257 seen.lock().unwrap().insert(std::thread::current().id());
3258 std::thread::sleep(Duration::from_millis(30));
3260 Ok(())
3261 })
3262 .unwrap();
3263 assert_eq!(seen.lock().unwrap().len(), workers);
3264 }
3265 }
3266
3267 #[test]
3268 fn workspace_dependents() {
3269 let package = |name: &str, deps: &[&str]| Package {
3270 name: name.to_string(),
3271 dependencies: deps
3272 .iter()
3273 .map(|d| Dependency {
3274 name: d.to_string(),
3275 })
3276 .collect(),
3277 manifest_path: PathBuf::new(),
3278 targets: vec![],
3279 };
3280 let packages = [
3281 package("core", &["serde"]),
3282 package("mid", &["core"]),
3283 package("app", &["mid", "other"]),
3284 package("other", &[]),
3285 package("cycle", &["app", "core"]),
3286 ];
3287 assert_eq!(dependents_of("core", &packages), ["app", "cycle", "mid"]);
3288 assert_eq!(dependents_of("mid", &packages), ["app", "cycle"]);
3289 assert_eq!(dependents_of("other", &packages), ["app", "cycle"]);
3290 assert!(dependents_of("app", &packages) == ["cycle"]);
3291 assert!(dependents_of("nobody", &packages).is_empty());
3292 let mutual = [package("x", &["y"]), package("y", &["x"])];
3294 assert_eq!(dependents_of("x", &mutual), ["y"]);
3295 }
3296
3297 #[test]
3298 fn failure_lines_of_libtest() {
3299 assert!(is_failure_line("test tests::a ... FAILED"));
3300 assert!(is_failure_line(
3301 "test src/lib.rs - double (line 3) ... FAILED"
3302 ));
3303 assert!(!is_failure_line("test tests::a ... ok"));
3304 assert!(!is_failure_line("test result: FAILED. 1 passed; 1 failed"));
3305 assert!(!is_failure_line("my output says ... FAILED"));
3306 assert!(!is_failure_line(
3307 "test tests::a ... FAILED (but printed by the test)"
3308 ));
3309 }
3310
3311 #[test]
3312 fn effects_in_words() {
3313 let source = "fn f(s: &mut S) -> bool { s.reset(); s.count > 1 }";
3314 let mut found = instrument::discover(source, 0).unwrap().sites;
3315 found.retain(|s| !matches!(s.kind, SiteKind::Body { .. }));
3316 for (id, site) in found.iter_mut().enumerate() {
3317 site.id = id as u32;
3318 }
3319 let sites: BTreeMap<u32, (&str, &Site)> =
3320 found.iter().map(|s| (s.id, ("src/lib.rs", s))).collect();
3321 let texts: Vec<&str> = found.iter().map(|s| s.text.as_str()).collect();
3322 assert_eq!(
3323 texts,
3324 ["fn f(s: &mut S) -> bool", "s.reset();", "s.count > 1"]
3325 );
3326
3327 let set = |list: &[Change]| list.iter().cloned().collect::<BTreeSet<Change>>();
3328 let mut changes = BTreeMap::new();
3329 changes.insert(
3330 "tests::a".to_string(),
3331 set(&[
3332 Change::Returns {
3333 site: 0,
3334 value: true,
3335 },
3336 Change::NowRuns { site: 1 },
3337 ]),
3338 );
3339 changes.insert(
3340 "tests::b".to_string(),
3341 set(&[Change::NowRuns { site: 1 }, Change::NewOutcome { site: 2 }]),
3342 );
3343 changes.insert("?".to_string(), set(&[Change::NoLongerRuns { site: 2 }]));
3344 assert_eq!(
3345 describe_effects(&changes, &sites),
3346 [
3347 "with the mutant, `tests::a` gets `true` from `fn f(s: &mut S) -> bool` (src/lib.rs:1)",
3348 "with the mutant, `tests::a` (and 1 more) now runs `s.reset();` (src/lib.rs:1)",
3349 "with the mutant, a test no longer runs `s.count > 1` (src/lib.rs:1)",
3350 "(and 1 more such changes)",
3351 ]
3352 );
3353 let mut many = BTreeMap::new();
3355 many.insert(
3356 "tests::a".to_string(),
3357 set(&[
3358 Change::NowRuns { site: 0 },
3359 Change::NowRuns { site: 1 },
3360 Change::NowRuns { site: 2 },
3361 Change::NoLongerRuns { site: 0 },
3362 Change::NoLongerRuns { site: 1 },
3363 Change::NoLongerRuns { site: 2 },
3364 ]),
3365 );
3366 assert_eq!(
3367 describe_effects(&many, &sites).last().map(String::as_str),
3368 Some("(and 3 more such changes)")
3369 );
3370 let mut few = BTreeMap::new();
3372 few.insert(
3373 "tests::a".to_string(),
3374 set(&[
3375 Change::NowRuns { site: 1 },
3376 Change::NewOutcome { site: 2 },
3377 Change::Returns {
3378 site: 0,
3379 value: false,
3380 },
3381 ]),
3382 );
3383 assert_eq!(
3384 describe_effects(&few, &sites),
3385 [
3386 "with the mutant, `tests::a` gets `false` from `fn f(s: &mut S) -> bool` (src/lib.rs:1)",
3387 "with the mutant, `tests::a` now runs `s.reset();` (src/lib.rs:1)",
3388 "with the mutant, `tests::a` takes `s.count > 1` (src/lib.rs:1) a way it did not before",
3389 ]
3390 );
3391 assert_eq!(
3392 describe_effects(&BTreeMap::new(), &sites),
3393 [
3394 "with the mutant, these tests still reach the same code with the same outcomes: they do not use its result, or it is the same for their inputs"
3395 ]
3396 );
3397 }
3398
3399 #[test]
3400 fn mutant_timeout_scales_with_the_baseline() {
3401 assert_eq!(mutant_timeout(Duration::ZERO), Duration::from_secs(5));
3402 assert_eq!(
3403 mutant_timeout(Duration::from_secs(2)),
3404 Duration::from_secs(15)
3405 );
3406 }
3407 fn scratch(name: &str) -> PathBuf {
3409 let dir = std::env::temp_dir().join(format!("tmt-{name}-{}", std::process::id()));
3410 let _ = fs::remove_dir_all(&dir);
3411 fs::create_dir_all(dir.join("ws/src")).unwrap();
3412 fs::create_dir_all(dir.join("work/src")).unwrap();
3413 dir.canonicalize().unwrap()
3414 }
3415
3416 fn set_modified(path: &Path, time: std::time::SystemTime) {
3417 fs::File::options()
3418 .write(true)
3419 .open(path)
3420 .unwrap()
3421 .set_modified(time)
3422 .unwrap();
3423 }
3424
3425 fn modified(path: &Path) -> std::time::SystemTime {
3426 fs::metadata(path).unwrap().modified().unwrap()
3427 }
3428
3429 fn copy_run(dir: &Path, selected: &[&str], write: bool) -> WorkCopy {
3432 let (workspace, work) = (dir.join("ws"), dir.join("work"));
3433 let copy = work.join("src");
3434 let state = WorkCopy::open(&work, ©);
3435 copy_tree(&workspace, ©, &workspace, &|_| false, &state).unwrap();
3436 prune(©, &state).unwrap();
3437 for name in selected {
3438 let path = copy.join(name);
3439 let original = state.original(&path, &workspace).unwrap().unwrap();
3440 assert_eq!(original, fs::read_to_string(workspace.join(name)).unwrap());
3441 if write {
3442 state
3443 .write(&path, &format!("instrumented {original}"))
3444 .unwrap();
3445 } else {
3446 state.record(&path).unwrap(); }
3448 }
3449 if write {
3450 state.settle(&workspace).unwrap();
3451 }
3452 state
3453 }
3454
3455 #[test]
3457 fn work_copy_table() {
3458 let table = include_str!("../tests/data/workcopy.pict.tsv");
3459 let hour_ago = std::time::SystemTime::now() - Duration::from_secs(3600);
3460 let mut rows = 0;
3461 for (index, line) in table.lines().skip(1).enumerate() {
3462 let [earlier, source, selected] = line.split('\t').collect::<Vec<_>>()[..] else {
3463 panic!("bad row: {line}");
3464 };
3465 let dir = scratch(&format!("copy-table-{index}"));
3466 let (file, copied) = (dir.join("ws/src/a.rs"), dir.join("work/src/src/a.rs"));
3467 let log = dir.join("work").join(WRITTEN_LOG);
3468 fs::write(&file, "v1").unwrap();
3469 set_modified(&file, hour_ago);
3470 match earlier {
3471 "none" => {}
3472 "plain" => drop(copy_run(&dir, &[], true)),
3473 "written" => drop(copy_run(&dir, &["src/a.rs"], true)),
3474 "logged_only" => drop(copy_run(&dir, &["src/a.rs"], false)),
3475 _ => panic!("{line}"),
3476 }
3477 if copied.exists() {
3478 set_modified(&copied, hour_ago);
3479 }
3480 let before = fs::read_to_string(&copied).ok();
3481 match source {
3482 "same" => {}
3483 "edited" => fs::write(&file, "version 2").unwrap(),
3484 "deleted" => fs::remove_file(&file).unwrap(),
3485 _ => panic!("{line}"),
3486 }
3487 let selected = selected == "yes";
3488 copy_run(&dir, if selected { &["src/a.rs"] } else { &[] }, true);
3489
3490 let wanted = match (source, selected) {
3491 ("deleted", _) => None,
3492 ("same", true) => Some("instrumented v1".to_string()),
3493 ("same", false) => Some("v1".to_string()),
3494 (_, true) => Some("instrumented version 2".to_string()),
3495 (_, false) => Some("version 2".to_string()),
3496 };
3497 assert_eq!(fs::read_to_string(&copied).ok(), wanted, "{line}");
3498 assert_eq!(
3499 fs::read_to_string(&log).unwrap_or_default(),
3500 if selected { "src/a.rs\n" } else { "" },
3501 "{line}"
3502 );
3503 if before == wanted && wanted.is_some() && earlier != "logged_only" {
3506 assert_eq!(modified(&copied), hour_ago, "{line}");
3507 }
3508 if before != wanted && wanted.is_some() {
3511 assert!(
3512 modified(&copied) > hour_ago + Duration::from_secs(1800),
3513 "{line}"
3514 );
3515 }
3516 copy_run(&dir, &[], true);
3518 assert_eq!(
3519 fs::read_to_string(&copied).ok(),
3520 fs::read_to_string(&file).ok(),
3521 "{line}"
3522 );
3523 assert_eq!(fs::read_to_string(&log).unwrap(), "", "{line}");
3524 fs::remove_dir_all(&dir).unwrap();
3525 rows += 1;
3526 }
3527 assert_eq!(rows, 20);
3528 }
3529
3530 #[test]
3531 fn work_copy_keeps_modification_times() {
3532 let dir = scratch("copy-times");
3533 let hour_ago = std::time::SystemTime::now() - Duration::from_secs(3600);
3534 let names = ["src/lib.rs", "src/plain.rs", "src/edited.rs"];
3535 for name in names {
3536 fs::write(dir.join("ws").join(name), format!("// {name}")).unwrap();
3537 set_modified(&dir.join("ws").join(name), hour_ago);
3538 }
3539 let copy = dir.join("work/src");
3540 let runtime = copy.join("src/__tmt_rt.rs");
3541 let run = || {
3542 let state = copy_run(&dir, &[], false);
3543 for name in ["src/lib.rs", "src/edited.rs"] {
3544 let original = state.original(©.join(name), &dir.join("ws")).unwrap();
3545 state
3546 .write(©.join(name), &format!("probe {}", original.unwrap()))
3547 .unwrap();
3548 }
3549 assert_eq!(state.original(&runtime, &dir.join("ws")).ok(), {
3551 if runtime.exists() { Some(None) } else { None }
3552 });
3553 state.write(&runtime, "runtime").unwrap();
3554 state.settle(&dir.join("ws")).unwrap();
3555 };
3556 run();
3557 for name in names.iter().map(|n| copy.join(n)).chain([runtime.clone()]) {
3558 set_modified(&name, hour_ago);
3559 }
3560 fs::write(dir.join("ws/src/edited.rs"), "// edited since").unwrap();
3561 run();
3562 for name in ["src/lib.rs", "src/plain.rs", "src/__tmt_rt.rs"] {
3564 assert_eq!(modified(©.join(name)), hour_ago, "{name}");
3565 }
3566 assert_ne!(modified(©.join("src/edited.rs")), hour_ago);
3567 assert_eq!(
3568 fs::read_to_string(copy.join("src/edited.rs")).unwrap(),
3569 "probe // edited since"
3570 );
3571 assert_eq!(
3572 fs::read_to_string(copy.join("src/lib.rs")).unwrap(),
3573 "probe // src/lib.rs"
3574 );
3575 assert_eq!(
3576 fs::read_to_string(dir.join("work").join(WRITTEN_LOG)).unwrap(),
3577 "src/__tmt_rt.rs\nsrc/edited.rs\nsrc/lib.rs\n"
3578 );
3579 let later = hour_ago + Duration::from_secs(60);
3581 set_modified(&dir.join("ws/src/plain.rs"), later);
3582 run();
3583 assert_eq!(modified(©.join("src/plain.rs")), hour_ago);
3584 let plain = fs::read_to_string(dir.join("ws/src/plain.rs")).unwrap();
3587 fs::write(dir.join("ws/src/plain.rs"), plain.to_uppercase()).unwrap();
3588 set_modified(
3589 &dir.join("ws/src/plain.rs"),
3590 hour_ago - Duration::from_secs(60),
3591 );
3592 run();
3593 assert_eq!(
3594 fs::read_to_string(copy.join("src/plain.rs")).unwrap(),
3595 plain.to_uppercase()
3596 );
3597 assert!(modified(©.join("src/plain.rs")) > later);
3598 fs::remove_dir_all(&dir).unwrap();
3599 }
3600
3601 #[test]
3602 fn work_copy_log_is_not_trusted() {
3603 let dir = scratch("copy-log");
3604 let (workspace, work) = (dir.join("ws"), dir.join("work"));
3605 let copy = work.join("src");
3606 let outside = dir.join("outside.txt");
3607 fs::write(&outside, "keep").unwrap();
3608 fs::write(workspace.join("src/a.rs"), "a").unwrap();
3609 fs::write(
3611 work.join(WRITTEN_LOG),
3612 format!(
3613 "../../outside.txt\n{}\n\nsrc/../../../outside.txt\nsrc/a.rs\n",
3614 outside.display()
3615 ),
3616 )
3617 .unwrap();
3618 let state = WorkCopy::open(&work, ©);
3619 assert_eq!(
3620 state.earlier,
3621 [copy.join("src/a.rs")].into_iter().collect::<HashSet<_>>()
3622 );
3623 copy_tree(&workspace, ©, &workspace, &|_| false, &state).unwrap();
3624 state.settle(&workspace).unwrap();
3625 assert_eq!(fs::read_to_string(&outside).unwrap(), "keep");
3626 assert_eq!(fs::read_to_string(copy.join("src/a.rs")).unwrap(), "a");
3627
3628 let state = WorkCopy::open(&work, ©);
3630 assert!(state.write(&outside, "x").is_err());
3631 assert!(state.write(©.join("src/a\nb.rs"), "x").is_err());
3632 assert!(!copy.join("src/a\nb.rs").exists());
3633 assert_eq!(fs::read_to_string(&outside).unwrap(), "keep");
3634 fs::remove_dir_all(&dir).unwrap();
3635 }
3636 #[test]
3637 fn work_copy_log_follows_every_write() {
3638 let dir = scratch("copy-log-order");
3639 let (workspace, work) = (dir.join("ws"), dir.join("work"));
3640 let copy = work.join("src");
3641 let log = work.join(WRITTEN_LOG);
3642 let names = ["h", "c", "f", "a", "e", "b", "g", "d"].map(|n| format!("src/{n}.rs"));
3643 for name in &names {
3644 fs::write(workspace.join(name), "x").unwrap();
3645 }
3646 let state = copy_run(&dir, &[], false);
3647 state.record(©.join(&names[0])).unwrap();
3649 state.record(©.join(&names[0])).unwrap();
3650 assert_eq!(fs::read_to_string(&log).unwrap(), "src/h.rs\n");
3651 assert_eq!(fs::read_to_string(copy.join(&names[0])).unwrap(), "x");
3652 for name in &names {
3653 state.write(©.join(name), "probe").unwrap();
3654 }
3655 state.settle(&workspace).unwrap();
3656 let mut sorted = names.to_vec();
3657 sorted.sort();
3658 assert_eq!(
3659 fs::read_to_string(&log).unwrap(),
3660 sorted.iter().map(|n| format!("{n}\n")).collect::<String>()
3661 );
3662
3663 let state = copy_run(&dir, &[], false);
3665 state.settle(&workspace).unwrap();
3666 assert_eq!(fs::read_to_string(&log).unwrap(), "");
3667 state.write(©.join(&names[3]), "probe").unwrap();
3668 assert_eq!(fs::read_to_string(&log).unwrap(), "src/a.rs\n");
3669 fs::remove_dir_all(&dir).unwrap();
3670 }
3671
3672 #[test]
3673 fn sync_copies_what_is_not_up_to_date_and_nothing_else() {
3674 let dir = scratch("copy-sync");
3675 let (workspace, work) = (dir.join("ws"), dir.join("work"));
3676 let copy = work.join("src");
3677 let hour_ago = std::time::SystemTime::now() - Duration::from_secs(3600);
3678 for name in [
3679 "same",
3680 "longer",
3681 "newer",
3682 "was_dir",
3683 "was_link",
3684 "short_link",
3685 "twin_link",
3686 "shorter",
3687 ] {
3688 fs::write(workspace.join("src").join(name), "source").unwrap();
3689 set_modified(&workspace.join("src").join(name), hour_ago);
3690 }
3691 let locked = workspace.join("src/locked");
3693 fs::write(&locked, "read only").unwrap();
3694 let mut permissions = fs::metadata(&locked).unwrap().permissions();
3695 permissions.set_readonly(true);
3696 fs::set_permissions(&locked, permissions).unwrap();
3697 fs::create_dir_all(copy.join("src/was_dir/inner")).unwrap();
3698 fs::write(copy.join("src/same"), "SOURCE").unwrap();
3700 fs::write(workspace.join("src/copied"), "as it is").unwrap();
3702 fs::write(copy.join("src/copied"), "as it is").unwrap();
3703 let long_ago = hour_ago - Duration::from_secs(7200);
3704 set_modified(©.join("src/copied"), long_ago);
3705 let elsewhere = dir.join("elsewhere");
3707 fs::create_dir_all(&elsewhere).unwrap();
3708 std::os::unix::fs::symlink(&elsewhere, copy.join("linked")).unwrap();
3709 fs::create_dir_all(workspace.join("linked/deep")).unwrap();
3710 fs::write(workspace.join("linked/deep/z"), "z").unwrap();
3711 fs::write(copy.join("src/longer"), "SOURCE+").unwrap();
3712 fs::write(copy.join("src/newer"), "SOURCE").unwrap();
3713 set_modified(©.join("src/newer"), hour_ago - Duration::from_secs(60));
3714 let outside = dir.join("outside");
3716 fs::write(&outside, "keep").unwrap();
3717 std::os::unix::fs::symlink(&outside, copy.join("src/was_link")).unwrap();
3718 let twin = dir.join("twin");
3720 fs::write(&twin, "source").unwrap();
3721 std::os::unix::fs::symlink(&twin, copy.join("src/twin_link")).unwrap();
3722 fs::write(copy.join("src/shorter"), "sour").unwrap();
3724 std::os::unix::fs::symlink("abcdef", copy.join("src/short_link")).unwrap();
3726 fs::create_dir_all(copy.join("old/deep")).unwrap();
3728 fs::write(copy.join("old/deep/x"), "x").unwrap();
3729 fs::create_dir_all(workspace.join("keep/deep")).unwrap();
3730 fs::write(workspace.join("keep/deep/y"), "y").unwrap();
3731
3732 copy_run(&dir, &[], true);
3733 let read = |name: &str| fs::read_to_string(copy.join(name)).unwrap();
3734 assert_eq!(read("src/locked"), "read only");
3735 assert_eq!(read("src/copied"), "as it is");
3736 assert_eq!(
3737 fs::metadata(copy.join("src/copied"))
3738 .unwrap()
3739 .modified()
3740 .unwrap(),
3741 long_ago
3742 );
3743 assert_eq!(read("linked/deep/z"), "z");
3744 assert!(fs::symlink_metadata(copy.join("linked")).unwrap().is_dir());
3745 assert_eq!(
3746 fs::read_dir(&elsewhere).unwrap().count(),
3747 0,
3748 "nothing written through"
3749 );
3750 for name in [
3751 "src/same",
3752 "src/longer",
3753 "src/newer",
3754 "src/was_dir",
3755 "src/was_link",
3756 "src/short_link",
3757 "src/twin_link",
3758 "src/shorter",
3759 ] {
3760 assert_eq!(read(name), "source", "{name}");
3761 assert!(
3762 fs::symlink_metadata(copy.join(name)).unwrap().is_file(),
3763 "{name}"
3764 );
3765 }
3766 assert!(
3767 fs::symlink_metadata(copy.join("src/was_link"))
3768 .unwrap()
3769 .is_file()
3770 );
3771 assert_eq!(fs::read_to_string(&outside).unwrap(), "keep");
3772 assert!(!copy.join("old").exists());
3773 assert_eq!(read("keep/deep/y"), "y");
3774 fs::remove_dir_all(&dir).unwrap();
3775 }
3776 #[test]
3777 fn a_finding_keeps_its_number_when_the_one_before_it_is_closed() {
3778 let source = "impl S {\n fn f(a: u8, b: u8) -> u8 {\n let x = if a > b { 1 } else { 0 };\n let y = if a > b { 2 } else { 0 };\n x + y\n }\n}\nfn g(a: u8, b: u8) -> bool {\n a > b\n}\n";
3779 let found = instrument::discover(source, 0).unwrap();
3780 let all: Vec<(usize, usize, String)> = found
3781 .sites
3782 .iter()
3783 .map(|site| {
3784 let at = report::location("", site);
3785 (at.line, at.column, at.code)
3786 })
3787 .collect();
3788 let places = [FilePlaces {
3789 display: "src/lib.rs",
3790 source,
3791 places: &all,
3792 }];
3793 let gap = |line: usize, column: usize, file: &str| Finding::InputGap {
3794 at: report::Location {
3795 file: file.to_string(),
3796 line,
3797 column,
3798 code: "a > b".to_string(),
3799 ..report::Location::default()
3800 },
3801 survivors: vec![],
3802 survivor_count: 0,
3803 add_tests: vec![],
3804 observed: None,
3805 verified: true,
3806 };
3807 let name = |finding: &Finding| {
3808 let at = finding.at();
3809 (at.item.clone(), at.id.clone())
3810 };
3811 let mut findings = [
3813 gap(4, 20, "src/lib.rs"),
3814 gap(9, 5, "src/lib.rs"),
3815 gap(9, 5, "src/other.rs"),
3816 ];
3817 name_findings(&mut findings, &places);
3818 assert_eq!(
3819 name(&findings[0]),
3820 (
3821 "S::f".to_string(),
3822 "input_gap|src/lib.rs|S::f|a > b|1".to_string()
3823 )
3824 );
3825 assert_eq!(
3826 name(&findings[1]),
3827 (
3828 "g".to_string(),
3829 "input_gap|src/lib.rs|g|a > b|0".to_string()
3830 )
3831 );
3832 assert_eq!(name(&findings[2]), (String::new(), String::new()));
3834 }
3835
3836 #[test]
3837 fn an_audit_takes_its_sample_evenly_and_the_same_every_time() {
3838 assert_eq!(spread(0, 3), Vec::<usize>::new());
3839 assert_eq!(spread(5, 0), Vec::<usize>::new());
3840 assert_eq!(spread(3, 3), [0, 1, 2]);
3841 assert_eq!(spread(3, 10), [0, 1, 2]);
3842 assert_eq!(spread(10, 1), [0]);
3843 assert_eq!(spread(10, 3), [0, 3, 6]);
3844 assert_eq!(spread(10, 5), [0, 2, 4, 6, 8]);
3845 assert_eq!(spread(4, 3), [0, 1, 2]);
3846 assert_eq!(spread(7, 6), [0, 1, 2, 3, 4, 5]);
3847 }
3848
3849 #[test]
3850 fn a_mutant_of_the_source_is_the_mutation_its_probe_runs() {
3851 assert_ne!(crate::tmt_rt::CANNOT_EVALUATE, 0);
3854 let source = "fn f(a: i32, b: i32, ok: bool, k: Option<i32>, base: O) -> O { \
3855 go(); \
3856 let x = match k { Some(n) if n > 1 => !ok && a < b, _ => -a + b > 0 || ok }; \
3857 for _ in a..b {} for _ in a..=b {} \
3858 O { on: x, ..base } }";
3859 let found = instrument::discover(source, 0).unwrap().sites;
3860 let mut seen = BTreeSet::new();
3861 for site in &found {
3862 for mutant in instrument::source_mutants(site) {
3863 let kind = format!("{:?}", site.kind);
3864 let kind = kind.split([' ', '{', '(']).next().unwrap().to_string();
3865 seen.insert((
3866 kind,
3867 mutant.into.clone(),
3868 format!("{:?}", mutation_of(site, &mutant)),
3869 ));
3870 }
3871 }
3872 let expected = [
3873 ("Arith", "*", "ArithSwap2"),
3874 ("Arith", "-", "ArithSwap"),
3875 ("Arm", "Some(n) if n > 1", "Delete"),
3876 ("Body", "Default::default()", "Delete"),
3877 ("Cmp", "<", "Op(Lt)"),
3878 ("Cmp", "<=", "Op(Le)"),
3879 ("Cmp", "==", "Op(Eq)"),
3880 ("Cmp", ">", "Op(Gt)"),
3881 ("Cmp", ">=", "Op(Ge)"),
3882 ("Field", "on", "Delete"),
3883 ("Guard", "true", "Const(true)"),
3884 ("Logic", "&&", "LogicSwap"),
3885 ("Logic", "||", "LogicSwap"),
3886 ("Neg", "", "Delete"),
3887 ("Not", "", "DropNot"),
3888 ("Range", "..", "RangeEnd"),
3889 ("Range", "..=", "RangeEnd"),
3890 ];
3891 let like = |source: &str, into: &str| -> Vec<Mutation> {
3894 let sites = instrument::discover(source, 0).unwrap().sites;
3895 let site = sites
3896 .iter()
3897 .find(|site| matches!(site.kind, SiteKind::Cmp { .. }))
3898 .unwrap();
3899 let mutant = instrument::source_mutants(site)
3900 .into_iter()
3901 .find(|mutant| mutant.into == into)
3902 .unwrap();
3903 mutations_like(site, &mutant, true)
3904 };
3905 use plan::CmpOp::*;
3906 for (op, into, expected) in [
3907 ("==", "!=", vec![Mutation::Op(Ne), Mutation::Negate]),
3908 ("!=", "==", vec![Mutation::Op(Eq), Mutation::Negate]),
3909 ("<=", ">", vec![Mutation::Op(Gt), Mutation::Negate]),
3910 (">=", "<", vec![Mutation::Op(Lt), Mutation::Negate]),
3911 ("<", "<=", vec![Mutation::Op(Le), Mutation::Shift(1)]),
3912 (">", ">=", vec![Mutation::Op(Ge), Mutation::Shift(-1)]),
3913 ("<", "==", vec![Mutation::Op(Eq)]),
3914 ("<", ">", vec![Mutation::Op(Gt)]),
3915 (">", "==", vec![Mutation::Op(Eq)]),
3916 (">", "<", vec![Mutation::Op(Lt)]),
3917 ] {
3918 let source = format!("fn f(a: i32, b: i32) -> bool {{ a {op} b }}");
3919 assert_eq!(like(&source, into), expected, "{op} as {into}");
3920 }
3921 let unordered = |op: &str, into: &str| -> Vec<Mutation> {
3924 let source = format!("fn f(a: f64, b: f64) -> bool {{ a {op} b }}");
3925 let sites = instrument::discover(&source, 0).unwrap().sites;
3926 let site = sites
3927 .iter()
3928 .find(|site| matches!(site.kind, SiteKind::Cmp { .. }))
3929 .unwrap();
3930 let mutant = instrument::source_mutants(site)
3931 .into_iter()
3932 .find(|mutant| mutant.into == into)
3933 .unwrap();
3934 mutations_like(site, &mutant, false)
3935 };
3936 assert_eq!(unordered(">=", "<"), [Mutation::Op(Lt)]);
3937 assert_eq!(unordered("<=", ">"), [Mutation::Op(Gt)]);
3938 assert_eq!(unordered("==", "!="), [Mutation::Op(Ne), Mutation::Negate]);
3939 for d in -3..=3 {
3941 assert_eq!(
3942 plan::eval_mutated_d(Lt, Mutation::Shift(1), d),
3943 Le.eval_d(d)
3944 );
3945 assert_eq!(
3946 plan::eval_mutated_d(Gt, Mutation::Shift(-1), d),
3947 Ge.eval_d(d)
3948 );
3949 }
3950 let seen: Vec<(&str, &str, &str)> = seen
3951 .iter()
3952 .map(|(kind, into, mutation)| (kind.as_str(), into.as_str(), mutation.as_str()))
3953 .collect();
3954 assert_eq!(seen, expected);
3955 }
3956
3957 #[test]
3958 fn the_mark_of_a_run_is_a_new_file_and_says_one_of_three_things() {
3959 let dir = scratch("unable-mark");
3960 fs::create_dir_all(&dir).unwrap();
3961 let runs = std::sync::atomic::AtomicUsize::new(0);
3962 let name = |n: usize| dir.join(format!("tmt-unable-{}-{n}", std::process::id()));
3963 fs::write(name(0), "not ours").unwrap();
3966 fs::write(name(1), "nor this").unwrap();
3967 let mark = reserve_mark(&dir, &runs).unwrap();
3968 assert_eq!(mark, name(2));
3969 assert!(mark.is_absolute());
3970 assert_eq!(fs::read_to_string(&mark).unwrap(), "");
3971 assert_eq!(fs::read_to_string(name(0)).unwrap(), "not ours");
3972 assert_eq!(fs::read_to_string(name(1)).unwrap(), "nor this");
3973 assert!(!release_mark(&mark).unwrap());
3975 assert!(!mark.exists());
3976 let mark = reserve_mark(&dir, &runs).unwrap();
3978 assert_eq!(mark, name(3));
3979 fs::remove_file(&mark).unwrap();
3980 assert!(release_mark(&mark).unwrap());
3981 let in_the_way = dir.join("a-directory");
3984 fs::create_dir_all(&in_the_way).unwrap();
3985 let refused = format!("{:#}", release_mark(&in_the_way).unwrap_err());
3986 assert!(refused.contains("cannot tell whether"), "{refused}");
3987 assert!(refused.contains("a-directory"), "{refused}");
3988 assert!(in_the_way.is_dir());
3989 let unmade = format!("{:#}", reserve_mark(&name(0), &runs).unwrap_err());
3991 assert!(unmade.contains("creating"), "{unmade}");
3992 assert_eq!(fs::read_to_string(name(0)).unwrap(), "not ours");
3993 fs::remove_dir_all(&dir).unwrap();
3994 }
3995
3996 #[test]
3997 fn the_directory_of_the_marks_is_made_or_used_and_nothing_is_removed_for_it() {
3998 let dir = scratch("marks-dir");
3999 let work = dir.join("work");
4000 assert_eq!(marks_dir(&work).unwrap(), work.join("marks"));
4002 assert!(work.join("marks").is_dir());
4003 fs::write(work.join("marks/left-over"), "x").unwrap();
4004 assert_eq!(marks_dir(&work).unwrap(), work.join("marks"));
4005 assert_eq!(
4006 fs::read_to_string(work.join("marks/left-over")).unwrap(),
4007 "x"
4008 );
4009 let taken = dir.join("taken");
4011 fs::create_dir_all(&taken).unwrap();
4012 fs::write(taken.join("marks"), "grades of the class").unwrap();
4013 let said = format!("{:#}", marks_dir(&taken).unwrap_err());
4014 assert!(
4015 said.contains("is in the way") && said.contains("marks"),
4016 "{said}"
4017 );
4018 assert_eq!(
4019 fs::read_to_string(taken.join("marks")).unwrap(),
4020 "grades of the class"
4021 );
4022 #[cfg(unix)]
4024 {
4025 let linked = dir.join("linked");
4026 let elsewhere = dir.join("elsewhere");
4027 fs::create_dir_all(&linked).unwrap();
4028 fs::create_dir_all(&elsewhere).unwrap();
4029 std::os::unix::fs::symlink(&elsewhere, linked.join("marks")).unwrap();
4030 assert!(marks_dir(&linked).is_err());
4031 assert!(
4032 fs::symlink_metadata(linked.join("marks"))
4033 .unwrap()
4034 .is_symlink()
4035 );
4036 assert_eq!(fs::read_dir(&elsewhere).unwrap().count(), 0);
4037 }
4038 fs::remove_dir_all(&dir).unwrap();
4039 }
4040
4041 #[test]
4042 fn concurrent_runs_share_the_cores() {
4043 assert_eq!(test_threads(16, 1), 16);
4045 assert_eq!(test_threads(16, 4), 4);
4046 assert_eq!(test_threads(18, 4), 4);
4047 assert_eq!(test_threads(16, 8), 2);
4049 assert_eq!(test_threads(16, 9), 2);
4050 assert_eq!(test_threads(4, 16), 2);
4051 assert_eq!(test_threads(1, 1), 2);
4052 assert_eq!(test_threads(8, 0), 8);
4053 }
4054
4055 #[test]
4056 fn cargo_is_told_the_same_everywhere() {
4057 assert!(CargoConfig::default().flags().is_empty());
4058 let some = CargoConfig {
4059 features: vec!["a".to_string(), "dep/b".to_string()],
4060 no_default_features: true,
4061 ..CargoConfig::default()
4062 };
4063 assert_eq!(
4064 some.flags(),
4065 ["--features", "a,dep/b", "--no-default-features"]
4066 );
4067 let all = CargoConfig {
4068 all_features: true,
4069 locked: true,
4070 ..CargoConfig::default()
4071 };
4072 assert_eq!(all.flags(), ["--all-features", "--locked"]);
4073 }
4074
4075 #[test]
4076 fn source_mutants_are_described_like_the_others() {
4077 let source = "fn f(a: i32, b: i32, k: Option<i32>) -> bool { \
4078 match k { Some(n) if n > 1 => !(a < b) || a + b == 0, _ => -a * b > 1 } }";
4079 let found = instrument::discover(source, 0).unwrap().sites;
4080 let described: Vec<String> = found
4081 .iter()
4082 .flat_map(|site| {
4083 instrument::source_mutants(site)
4084 .into_iter()
4085 .map(|mutant| report::describe(site, mutation_of(site, &mutant)))
4086 })
4087 .collect();
4088 assert_eq!(
4089 described,
4090 [
4091 "the body of `f` replaced by `true`",
4092 "the body of `f` replaced by `false`",
4093 "remove the arm `Some(n) if n > 1 => ..`",
4095 "the guard `n > 1` replaced by `true`",
4096 "`n == 1`",
4097 "`n < 1`",
4098 "`n >= 1`",
4099 "`!(a < b) && a + b == 0`",
4100 "`(a < b)`",
4101 "`a == b`",
4102 "`a > b`",
4103 "`a <= b`",
4104 "`a + b != 0`",
4105 "`a - b`",
4106 "`a * b`",
4107 "`-a * b == 1`",
4108 "`-a * b < 1`",
4109 "`-a * b >= 1`",
4110 "`-a / b`",
4111 "`-a + b`",
4112 "`a`",
4113 ]
4114 );
4115 let source = "fn f(k: K) -> u8 { match k { K::A(n) if n > 1 => 1, K::A(_) => 2 } }";
4117 let found = instrument::discover(source, 0).unwrap().sites;
4118 let guard = found
4119 .iter()
4120 .find(|s| matches!(s.kind, SiteKind::Guard { .. }))
4121 .unwrap();
4122 let described: Vec<String> = instrument::source_mutants(guard)
4123 .iter()
4124 .map(|mutant| report::describe(guard, mutation_of(guard, mutant)))
4125 .collect();
4126 assert_eq!(
4127 described,
4128 [
4129 "the guard `n > 1` replaced by `true`",
4130 "the guard `n > 1` replaced by `false`"
4131 ]
4132 );
4133 }
4134}