use std::cell::RefCell;
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use anyhow::{Context, Result, anyhow, bail};
use serde::Deserialize;
use crate::instrument::{self, LiteralSide, RUNTIME_MOD, Rendered, Site, SiteKind};
use crate::plan::{self, Mutation, Obs};
use crate::propagation::{self, Change};
use crate::report::{self, Finding, Report};
use crate::scope::{self, Scope};
use crate::trace::Trace;
pub struct Options {
pub dir: PathBuf,
pub package: Option<String>,
pub verify: bool,
pub work_dir: Option<PathBuf>,
pub progress: bool,
pub since: Option<String>,
pub lines: Vec<String>,
pub baseline: Option<PathBuf>,
pub write_baseline: Option<PathBuf>,
pub also_test: Vec<String>,
pub dependents: bool,
pub effects: bool,
pub rebuild: bool,
pub opt_level: Option<u8>,
pub audit: Option<usize>,
pub cargo: CargoConfig,
pub jobs: usize,
pub all_files: bool,
pub doc: bool,
}
pub use crate::report::CargoConfig;
impl CargoConfig {
pub fn flags(&self) -> Vec<String> {
let mut flags = vec![];
if !self.features.is_empty() {
flags.extend(["--features".to_string(), self.features.join(",")]);
}
for (on, flag) in [
(self.all_features, "--all-features"),
(self.no_default_features, "--no-default-features"),
(self.locked, "--locked"),
] {
if on {
flags.push(flag.to_string());
}
}
flags
}
}
const NEARBY_LINES: usize = 6;
const WORK_MARKER: &str = ".tmt-work-dir";
const STD_ALIAS: &str = "__tmt_std";
const MAX_REPAIR_ROUNDS: usize = 40;
const MAX_TEST_FILTERS: usize = 200;
#[derive(Deserialize)]
struct Metadata {
packages: Vec<Package>,
workspace_root: PathBuf,
target_directory: PathBuf,
}
#[derive(Deserialize)]
struct Package {
name: String,
#[serde(default)]
dependencies: Vec<Dependency>,
manifest_path: PathBuf,
targets: Vec<Target>,
}
#[derive(Deserialize)]
struct Dependency {
name: String,
}
#[derive(Deserialize)]
struct Target {
kind: Vec<String>,
src_path: PathBuf,
}
#[derive(Deserialize)]
struct CargoMessage {
reason: String,
package_id: Option<String>,
target: Option<ArtifactTarget>,
profile: Option<Profile>,
executable: Option<PathBuf>,
message: Option<Diagnostic>,
}
#[derive(Deserialize)]
struct ArtifactTarget {
name: String,
}
#[derive(Deserialize)]
struct Profile {
test: bool,
}
#[derive(Deserialize)]
struct Diagnostic {
level: String,
rendered: Option<String>,
spans: Vec<DiagnosticSpan>,
}
#[derive(Deserialize)]
struct DiagnosticSpan {
file_name: String,
byte_start: usize,
line_start: usize,
is_primary: bool,
}
#[derive(Debug, PartialEq, Clone)]
struct ErrorSpan {
file: String,
byte_start: usize,
line: usize,
}
#[derive(Debug, PartialEq)]
struct CompileError {
primary: Vec<ErrorSpan>,
secondary: Vec<ErrorSpan>,
rendered: String,
}
#[derive(Debug, Default, PartialEq)]
struct BuildOutput {
test_binaries: Vec<(String, PathBuf, String)>,
errors: Vec<CompileError>,
}
fn dependents_of(package: &str, packages: &[Package]) -> Vec<String> {
let mut found: Vec<String> = vec![];
let mut frontier = vec![package.to_string()];
while let Some(current) = frontier.pop() {
for other in packages {
if other.name != package
&& !found.contains(&other.name)
&& other.dependencies.iter().any(|d| d.name == current)
{
found.push(other.name.clone());
frontier.push(other.name.clone());
}
}
}
found.sort();
found
}
fn is_package(id: &str, name: &str) -> bool {
let (path, fragment) = id.split_once('#').unwrap_or((id, ""));
fragment.split('@').next() == Some(name)
|| path.rsplit('/').next() == Some(name)
|| id.split(' ').next() == Some(name)
}
fn parse_build_output(stdout: &str, packages: &[&str]) -> BuildOutput {
let mut out = BuildOutput::default();
for line in stdout.lines() {
let Ok(msg) = serde_json::from_str::<CargoMessage>(line) else {
continue;
};
match msg.reason.as_str() {
"compiler-artifact" => {
if let (Some(exe), Some(target), Some(profile), Some(id)) = (
msg.executable,
msg.target,
msg.profile,
msg.package_id.as_deref(),
) && profile.test
&& let Some(package) = packages.iter().find(|name| is_package(id, name))
{
out.test_binaries
.push((target.name, exe, package.to_string()));
}
}
"compiler-message" => {
let Some(diag) = msg.message else { continue };
if diag.level != "error" {
continue;
}
let span = |s: &DiagnosticSpan| ErrorSpan {
file: s.file_name.clone(),
byte_start: s.byte_start,
line: s.line_start,
};
let error = CompileError {
primary: diag
.spans
.iter()
.filter(|s| s.is_primary)
.map(span)
.collect(),
secondary: diag
.spans
.iter()
.filter(|s| !s.is_primary)
.map(span)
.collect(),
rendered: diag.rendered.unwrap_or_default(),
};
if !error.primary.is_empty() && !out.errors.contains(&error) {
out.errors.push(error);
}
}
_ => {}
}
}
out
}
struct SourceFile {
display: String,
path: PathBuf,
original: String,
sites: Vec<Site>,
rebuild_sites: Vec<Site>,
places: Vec<(usize, usize, String)>,
rendered: Option<Rendered>,
}
enum Runner {
Exe(PathBuf),
Doc {
copy: PathBuf,
target_dir: PathBuf,
package: String,
opt_level: Option<u8>,
flags: Vec<String>,
},
}
struct TestBinary {
name: String,
cwd: PathBuf,
marks: PathBuf,
tests: BTreeSet<String>,
runner: Runner,
baseline: Duration,
traced: Duration,
trace: Trace,
}
#[derive(Debug, PartialEq, Clone, Copy)]
enum Outcome {
Pass,
Fail,
Timeout,
Unable,
}
struct WorkLock(PathBuf);
impl WorkLock {
fn take(work: &Path) -> Result<WorkLock> {
let path = work.join(".tmt-lock");
match fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)
{
Ok(_) => Ok(WorkLock(path)),
Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => bail!(
"another tmt run is using {}. If none is running, delete {}.",
work.display(),
path.display()
),
Err(err) => Err(err).with_context(|| format!("creating {}", path.display())),
}
}
}
impl Drop for WorkLock {
fn drop(&mut self) {
let _ = fs::remove_file(&self.0);
}
}
const WRITTEN_LOG: &str = ".tmt-written";
struct WorkCopy {
root: PathBuf,
log: PathBuf,
kept: RefCell<HashSet<PathBuf>>,
earlier: HashSet<PathBuf>,
visited: RefCell<HashSet<PathBuf>>,
written: RefCell<HashSet<PathBuf>>,
logged: RefCell<HashSet<PathBuf>>,
}
impl WorkCopy {
fn open(work: &Path, root: &Path) -> WorkCopy {
let log = work.join(WRITTEN_LOG);
for file in [log.clone(), log.with_extension("new")] {
if fs::symlink_metadata(&file).is_ok_and(|found| found.is_symlink()) {
let _ = fs::remove_file(&file);
}
}
let earlier: HashSet<PathBuf> = fs::read_to_string(&log)
.unwrap_or_default()
.lines()
.map(Path::new)
.filter(|relative| {
let mut parts = relative.components();
parts.clone().next().is_some()
&& parts.all(|part| matches!(part, std::path::Component::Normal(_)))
})
.map(|relative| root.join(relative))
.collect();
WorkCopy {
root: root.to_path_buf(),
log,
kept: RefCell::default(),
logged: RefCell::new(earlier.clone()),
earlier,
visited: RefCell::default(),
written: RefCell::default(),
}
}
fn is_kept(&self, path: &Path) -> bool {
self.kept.borrow().contains(path) || self.earlier.contains(path)
}
fn original(&self, path: &Path, workspace: &Path) -> Result<Option<String>> {
let source = if !self.earlier.contains(path) {
path.to_path_buf() } else if !self.visited.borrow().contains(path) {
return Ok(None);
} else {
workspace.join(path.strip_prefix(&self.root).unwrap_or(path))
};
fs::read_to_string(&source)
.map(Some)
.with_context(|| format!("reading {}", source.display()))
}
fn write(&self, path: &Path, content: &str) -> Result<()> {
if fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) {
fs::remove_file(path)?;
}
let parent = path.parent().and_then(|p| p.canonicalize().ok());
let inside = match (parent, self.root.canonicalize()) {
(Some(parent), Ok(root)) => parent.starts_with(root),
_ => false,
};
if !inside {
bail!(
"refusing to write outside the working copy: {}",
path.display()
);
}
self.record(path)?;
if fs::read_to_string(path).is_ok_and(|existing| existing == content) {
return Ok(()); }
fs::write(path, content).with_context(|| format!("writing {}", path.display()))
}
fn record(&self, path: &Path) -> Result<()> {
self.written.borrow_mut().insert(path.to_path_buf());
if self.logged.borrow().contains(path) {
return Ok(());
}
let line = path
.strip_prefix(&self.root)
.ok()
.and_then(Path::to_str)
.filter(|text| !text.chars().any(char::is_control));
let Some(line) = line else {
bail!(
"cannot instrument {}: its name cannot be written on a line of the log",
path.display()
);
};
use std::io::Write as _;
let mut log = fs::OpenOptions::new()
.create(true)
.append(true)
.open(&self.log)
.with_context(|| format!("opening {}", self.log.display()))?;
writeln!(log, "{line}").with_context(|| format!("writing {}", self.log.display()))?;
self.logged.borrow_mut().insert(path.to_path_buf());
Ok(())
}
fn settle(&self, workspace: &Path) -> Result<()> {
let written = self.written.borrow();
for path in self.earlier.difference(&written) {
if fs::symlink_metadata(path).is_ok() {
fs::remove_file(path).with_context(|| format!("removing {}", path.display()))?;
}
if self.visited.borrow().contains(path) {
let source = workspace.join(path.strip_prefix(&self.root).unwrap_or(path));
copy_as_new(&source, path)?;
}
}
let mut lines: Vec<&str> = written
.iter()
.filter_map(|path| path.strip_prefix(&self.root).ok()?.to_str())
.collect();
lines.sort_unstable();
let fresh = self.log.with_extension("new");
fs::write(
&fresh,
lines
.iter()
.map(|line| format!("{line}\n"))
.collect::<String>(),
)?;
fs::rename(&fresh, &self.log)?;
*self.logged.borrow_mut() = written.clone();
Ok(())
}
}
fn sync_file(src: &Path, dst: &Path, state: &WorkCopy) -> Result<()> {
state.kept.borrow_mut().insert(dst.to_path_buf());
if state.earlier.contains(dst) {
state.visited.borrow_mut().insert(dst.to_path_buf());
if fs::symlink_metadata(dst).is_ok_and(|m| m.is_file()) {
return Ok(());
}
}
let up_to_date = fs::symlink_metadata(dst).is_ok_and(|to| to.is_file()) && same_bytes(src, dst);
if up_to_date {
return Ok(());
}
if let Ok(existing) = fs::symlink_metadata(dst) {
if existing.is_dir() {
fs::remove_dir_all(dst)?;
} else {
fs::remove_file(dst)?;
}
}
copy_as_new(src, dst)
}
fn same_bytes(a: &Path, b: &Path) -> bool {
fs::read(a)
.ok()
.zip(fs::read(b).ok())
.is_some_and(|(a, b)| a == b)
}
fn real_dir(dir: &Path, state: &WorkCopy) -> Result<()> {
if let Ok(below) = dir.strip_prefix(&state.root) {
let mut path = state.root.clone();
for part in below.components() {
path.push(part);
match fs::symlink_metadata(&path) {
Ok(found) if !found.is_dir() => fs::remove_file(&path)
.with_context(|| format!("removing {}", path.display()))?,
_ => {}
}
}
}
fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))
}
fn copy_as_new(src: &Path, dst: &Path) -> Result<()> {
fs::copy(src, dst).with_context(|| format!("copying {}", src.display()))?;
fs::File::open(dst)
.and_then(|file| file.set_modified(std::time::SystemTime::now()))
.with_context(|| format!("touching {}", dst.display()))
}
fn prune(dir: &Path, state: &WorkCopy) -> Result<bool> {
let mut empty = true;
for entry in fs::read_dir(dir)? {
let path = entry?.path();
let is_dir = fs::symlink_metadata(&path)?.is_dir();
if is_dir {
if prune(&path, state)? {
fs::remove_dir(&path)?;
} else {
empty = false;
}
} else if state.is_kept(&path) {
empty = false;
} else {
fs::remove_file(&path)?;
}
}
Ok(empty)
}
fn copy_entry(
src: &Path,
dst: &Path,
workspace: &Path,
skip: &dyn Fn(&Path) -> bool,
state: &WorkCopy,
) -> Result<()> {
let kind = fs::symlink_metadata(src)?.file_type();
if kind.is_symlink() {
let Ok(target) = src.canonicalize() else {
return Ok(()); };
if target.is_dir() {
let contains_link = src
.parent()
.is_some_and(|dir| dir.canonicalize().is_ok_and(|dir| dir.starts_with(&target)));
if !target.starts_with(workspace) || contains_link || skip(&target) {
return Ok(());
}
return copy_tree(&target, dst, workspace, skip, state);
}
sync_file(&target, dst, state)?;
} else if kind.is_dir() {
if !src.join("CACHEDIR.TAG").exists() {
copy_tree(src, dst, workspace, skip, state)?;
}
} else {
sync_file(src, dst, state)?;
}
Ok(())
}
fn copy_tree(
from: &Path,
to: &Path,
workspace: &Path,
skip: &dyn Fn(&Path) -> bool,
state: &WorkCopy,
) -> Result<()> {
real_dir(to, state)?;
for entry in fs::read_dir(from).with_context(|| format!("reading {}", from.display()))? {
let src = entry?.path();
if skip(&src) {
continue;
}
let Some(name) = src.file_name() else {
continue;
};
copy_entry(&src, &to.join(name), workspace, skip, state)?;
}
Ok(())
}
fn rust_files(dir: &Path, skip: &dyn Fn(&Path) -> bool, out: &mut Vec<PathBuf>) -> Result<()> {
let mut entries: Vec<PathBuf> = fs::read_dir(dir)?
.map(|e| e.map(|e| e.path()))
.collect::<std::io::Result<_>>()?;
entries.sort();
for path in entries {
let Ok(kind) = fs::symlink_metadata(&path).map(|m| m.file_type()) else {
continue;
};
if skip(&path) || kind.is_symlink() {
continue;
}
if kind.is_dir() {
rust_files(&path, skip, out)?;
} else if path.extension().is_some_and(|e| e == "rs") {
out.push(path);
}
}
Ok(())
}
fn git_visible_files(dir: &Path) -> Result<Option<Vec<PathBuf>>> {
let git = |args: &[&str]| {
Command::new("git")
.arg("-C")
.arg(dir)
.args(args)
.stderr(Stdio::null())
.output()
};
let Ok(inside) = git(&["rev-parse", "--is-inside-work-tree"]) else {
return Ok(None);
};
if !inside.status.success() {
return Ok(None);
}
if git(&["check-ignore", "-q", "."])?.status.success() {
return Ok(None);
}
let listing = git(&[
"ls-files",
"--cached",
"--others",
"--exclude-standard",
"-z",
])?;
if !listing.status.success() {
bail!(
"git could not list the files of {}; pass --all-files to copy everything",
dir.display()
);
}
Ok(Some(
listing
.stdout
.split(|b| *b == 0)
.filter(|name| !name.is_empty())
.filter_map(|name| std::str::from_utf8(name).ok())
.map(PathBuf::from)
.collect(),
))
}
fn copy_git_visible(
from: &Path,
to: &Path,
files: Vec<PathBuf>,
workspace: &Path,
skip: &dyn Fn(&Path) -> bool,
state: &WorkCopy,
) -> Result<usize> {
let mut copied = 0;
for relative in files {
let (src, dst) = (from.join(&relative), to.join(&relative));
if skip(&src)
|| src
.ancestors()
.any(|a| a != from && a.starts_with(from) && skip(a))
{
continue;
}
let Ok(kind) = fs::symlink_metadata(&src).map(|m| m.file_type()) else {
continue; };
if let Some(parent) = dst.parent() {
real_dir(parent, state)?;
}
if kind.is_dir() {
match git_visible_files(&src)? {
Some(inner) => {
copied += copy_git_visible(&src, &dst, inner, workspace, skip, state)?
}
None => copy_tree(&src, &dst, workspace, skip, state)?,
}
} else {
copy_entry(&src, &dst, workspace, skip, state)?;
copied += 1;
}
}
Ok(copied)
}
fn module_paths(file: &Path, module: &instrument::TestModule) -> Vec<PathBuf> {
let dir = file.parent().unwrap_or(Path::new("."));
if let Some(path) = &module.path {
return vec![dir.join(path)];
}
let name = &module.name;
let stem = file.file_stem().and_then(|s| s.to_str()).unwrap_or("");
let base = if matches!(stem, "lib" | "main" | "mod") {
dir.to_path_buf()
} else {
dir.join(stem)
};
vec![base.join(format!("{name}.rs")), base.join(name)]
}
fn normalize(path: &Path) -> PathBuf {
let mut out = PathBuf::new();
for component in path.components() {
match component {
std::path::Component::CurDir => {}
std::path::Component::ParentDir => {
out.pop();
}
other => out.push(other),
}
}
out
}
fn absolutize_path_dependencies(
manifest: &str,
manifest_dir: &Path,
workspace: &Path,
copy: &Path,
) -> Result<Option<String>> {
use toml_edit::{DocumentMut, Item, TableLike, value};
fn fix(deps: &mut dyn TableLike, dirs: (&Path, &Path, &Path), changed: &mut bool) {
let (manifest_dir, workspace, copy) = dirs;
for (_, dep) in deps.iter_mut() {
let Some(dep) = dep.as_table_like_mut() else {
continue;
};
let Some(path) = dep.get("path").and_then(Item::as_str) else {
continue;
};
let absolute = Path::new(path).is_absolute();
let target = normalize(&manifest_dir.join(path));
let rewritten = match target.strip_prefix(workspace) {
Err(_) => target,
Ok(inside) if absolute => copy.join(inside),
Ok(_) => continue,
};
dep.insert("path", value(rewritten.to_string_lossy().into_owned()));
*changed = true;
}
}
const SECTIONS: [&str; 3] = ["dependencies", "dev-dependencies", "build-dependencies"];
fn fix_sections(table: &mut dyn TableLike, dirs: (&Path, &Path, &Path), changed: &mut bool) {
for section in SECTIONS {
if let Some(deps) = table.get_mut(section).and_then(Item::as_table_like_mut) {
fix(deps, dirs, changed);
}
}
}
let mut doc: DocumentMut = manifest.parse().context("parsing Cargo.toml")?;
let mut changed = false;
let dirs = (manifest_dir, workspace, copy);
fix_sections(doc.as_table_mut(), dirs, &mut changed);
if let Some(ws) = doc.get_mut("workspace").and_then(Item::as_table_like_mut) {
fix_sections(ws, dirs, &mut changed);
}
for per_key in ["target", "patch"] {
let Some(outer) = doc.get_mut(per_key).and_then(Item::as_table_like_mut) else {
continue;
};
for (_, inner) in outer.iter_mut() {
let Some(inner) = inner.as_table_like_mut() else {
continue;
};
if per_key == "target" {
fix_sections(inner, dirs, &mut changed);
} else {
fix(inner, dirs, &mut changed);
}
}
}
Ok(changed.then(|| doc.to_string()))
}
fn test_filter(tests: &BTreeSet<String>, known: &BTreeSet<String>) -> Option<Vec<String>> {
if tests.len() > MAX_TEST_FILTERS || !tests.iter().all(|t| known.contains(t)) {
None
} else {
Some(tests.iter().cloned().collect())
}
}
fn parse_test_list(stdout: &str) -> BTreeSet<String> {
stdout
.lines()
.filter_map(|line| line.strip_suffix(": test"))
.map(str::to_string)
.collect()
}
fn profile_env(opt_level: Option<u8>) -> Vec<(&'static str, String)> {
opt_level.map_or(vec![], |level| {
vec![
("CARGO_PROFILE_DEV_OPT_LEVEL", level.to_string()),
("CARGO_PROFILE_TEST_OPT_LEVEL", level.to_string()),
]
})
}
const SLOW_TRACE: Duration = Duration::from_secs(2);
fn mutant_timeout(baseline: Duration) -> Duration {
Duration::from_secs(5) + baseline * 5
}
fn test_threads(cores: usize, sharing: usize) -> usize {
(cores / sharing.max(1)).max(2)
}
fn run_binary(
bin: &TestBinary,
tests: Option<&[String]>,
env: &[(&str, &str)],
timeout: Duration,
stop_at_first_failure: bool,
sharing: usize,
) -> Result<Outcome> {
use std::io::BufRead;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
let cores = std::thread::available_parallelism().map_or(2, |n| n.get());
let threads = test_threads(cores, sharing);
static RUNS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let unable_mark = reserve_mark(&bin.marks, &RUNS)?;
let mut cmd = match &bin.runner {
Runner::Exe(exe) => {
let mut cmd = Command::new(exe);
cmd.arg(format!("--test-threads={threads}"));
if let Some(tests) = tests {
cmd.arg("--exact").args(tests);
}
cmd.current_dir(&bin.cwd)
.env("CARGO_MANIFEST_DIR", &bin.cwd);
cmd
}
Runner::Doc {
copy,
target_dir,
package,
opt_level,
flags,
} => {
let mut cmd = Command::new("cargo");
cmd.args(["test", "--doc", "-p", package])
.args(flags)
.current_dir(copy)
.env("CARGO_TARGET_DIR", target_dir)
.envs(profile_env(*opt_level));
cmd
}
};
cmd.env_remove("TMT_TRACE")
.env_remove("TMT_MUTANT")
.env("TMT_UNABLE", &unable_mark)
.envs(env.iter().copied())
.stdin(Stdio::null())
.stdout(if stop_at_first_failure {
Stdio::piped()
} else {
Stdio::null()
})
.stderr(Stdio::null());
#[cfg(unix)]
std::os::unix::process::CommandExt::process_group(&mut cmd, 0);
let mut child = cmd
.spawn()
.with_context(|| format!("starting the tests of `{}`", bin.name))?;
let failed = Arc::new(AtomicBool::new(false));
let watcher = child.stdout.take().map(|stdout| {
let failed = Arc::clone(&failed);
std::thread::spawn(move || {
for line in std::io::BufReader::new(stdout)
.lines()
.map_while(|l| l.ok())
{
if is_failure_line(&line) {
failed.store(true, Ordering::SeqCst);
}
}
})
});
let kill = |child: &mut std::process::Child| {
#[cfg(unix)]
let _ = Command::new("kill")
.args(["-KILL", "--", &format!("-{}", child.id())])
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
let _ = child.kill();
let _ = child.wait();
};
let started = Instant::now();
let outcome = loop {
if let Some(status) = child.try_wait()? {
break if status.success() {
Outcome::Pass
} else {
Outcome::Fail
};
}
if failed.load(Ordering::SeqCst) {
kill(&mut child);
break Outcome::Fail;
}
if started.elapsed() > timeout {
kill(&mut child);
break Outcome::Timeout;
}
std::thread::sleep(Duration::from_millis(5));
};
if let Some(watcher) = watcher {
let _ = watcher.join();
}
if release_mark(&unable_mark)? {
return Ok(Outcome::Unable);
}
Ok(outcome)
}
fn marks_dir(work: &Path) -> Result<PathBuf> {
let marks = work.join("marks");
match fs::symlink_metadata(&marks) {
Ok(found) if found.is_dir() => {}
Ok(_) => bail!(
"{} is in the way: the working directory needs a directory of that name, and \
this is not one. Move it, or choose another --work-dir",
marks.display()
),
Err(_) => {
fs::create_dir(&marks).with_context(|| format!("creating {}", marks.display()))?
}
}
Ok(marks)
}
fn reserve_mark(dir: &Path, runs: &std::sync::atomic::AtomicUsize) -> Result<PathBuf> {
let dir = std::path::absolute(dir).unwrap_or(dir.to_path_buf());
loop {
let mark = dir.join(format!(
"tmt-unable-{}-{}",
std::process::id(),
runs.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
));
match fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&mark)
{
Ok(_) => return Ok(mark),
Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {}
Err(err) => {
return Err(err).with_context(|| format!("creating {}", mark.display()));
}
}
}
}
fn release_mark(mark: &Path) -> Result<bool> {
match fs::remove_file(mark) {
Ok(()) => Ok(false),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(true),
Err(err) => Err(err).with_context(|| {
format!(
"removing {}: cannot tell whether the tests ran the mutant to the end",
mark.display()
)
}),
}
}
fn is_failure_line(line: &str) -> bool {
line.starts_with("test ") && line.ends_with(" ... FAILED")
}
fn requested_scope(
options: &Options,
workspace: &Path,
package_dir: &Path,
copy: &Path,
) -> Result<Option<Scope>> {
if options.since.is_none() && options.lines.is_empty() {
return Ok(None);
}
let prefix = package_dir.strip_prefix(copy).unwrap_or(Path::new(""));
let lines: Vec<String> = options
.lines
.iter()
.map(|spec| prefix.join(spec).to_string_lossy().into_owned())
.collect();
let mut scope = Scope::parse_lines(&lines)?;
if let Some(revision) = &options.since {
let git = |args: &[&str]| -> Result<String> {
let output = Command::new("git")
.arg("-C")
.arg(workspace)
.args(args)
.output()
.context("running git")?;
if !output.status.success() {
bail!(
"git {} failed: {}",
args.join(" "),
String::from_utf8_lossy(&output.stderr).trim()
);
}
Ok(String::from_utf8_lossy(&output.stdout).into_owned())
};
scope.merge(Scope::from_diff(&git(&[
"diff",
"-U0",
"--no-color",
"--no-ext-diff",
"--relative",
revision,
"--",
])?));
for file in git(&["ls-files", "--others", "--exclude-standard"])?.lines() {
scope.add_whole_file(file);
}
}
Ok(Some(scope))
}
fn blame_error(
error: &CompileError,
files: &[SourceFile],
copy: &Path,
disabled: &HashSet<u32>,
) -> Vec<u32> {
let enabled = |id: u32| !disabled.contains(&id);
let file_of = |span: &ErrorSpan| {
let path = copy.join(&span.file);
files.iter().find(|f| f.path == path)
};
let innermost = |spans: &[ErrorSpan]| -> Vec<u32> {
let mut ids = vec![];
for span in spans {
if let Some(file) = file_of(span) {
let rendered = file.rendered.as_ref().expect("rendered before building");
match rendered
.inserted_by(span.byte_start)
.filter(|id| enabled(*id))
{
Some(id) => ids.push(id),
None => ids.extend(instrument::blame(
&file.sites,
&enabled,
rendered.to_original(span.byte_start),
)),
}
}
}
ids
};
let widen = |lines: usize| -> Vec<u32> {
let mut ids = vec![];
for span in &error.primary {
if let Some(file) = file_of(span) {
ids.extend(
file.sites
.iter()
.filter(|s| enabled(s.id) && s.line.abs_diff(span.line) <= lines)
.map(|s| s.id),
);
}
}
ids
};
[
innermost(&error.primary),
innermost(&error.secondary),
widen(0),
widen(NEARBY_LINES),
widen(usize::MAX),
]
.into_iter()
.find(|ids| !ids.is_empty())
.unwrap_or_default()
}
fn domain_of(
literal: LiteralSide,
bounds: Option<&crate::trace::TypeBounds>,
) -> Option<(i128, i128)> {
let bounds = bounds?;
match literal {
LiteralSide::Rhs(k) => Some((bounds.lhs.0.checked_sub(k)?, bounds.lhs.1.checked_sub(k)?)),
LiteralSide::Lhs(k) => Some((k.checked_sub(bounds.rhs.1)?, k.checked_sub(bounds.rhs.0)?)),
LiteralSide::None => None,
}
}
struct Session {
progress: bool,
package_dir: PathBuf,
binaries: Vec<TestBinary>,
}
struct Job {
site: u32,
mutation: Mutation,
tests: Vec<(usize, Option<Vec<String>>)>,
}
#[derive(Debug, Clone, PartialEq)]
struct JobResult {
survived: Option<Vec<String>>,
timed_out: bool,
unable: bool,
}
fn tests_where<T>(
per_test: Option<&BTreeMap<String, T>>,
pick: impl Fn(&T) -> bool,
) -> BTreeSet<String> {
per_test
.into_iter()
.flatten()
.filter(|(_, obs)| pick(obs))
.map(|(test, _)| test.clone())
.collect()
}
type InfectedTests<'a> = Box<dyn Fn(&TestBinary, Mutation) -> BTreeSet<String> + 'a>;
type ReachingTests<'a> = Box<dyn Fn(&TestBinary) -> BTreeSet<String> + 'a>;
struct PlannedGap {
finding: Finding,
survivors: Vec<Mutation>,
constant_expr: Option<(usize, usize)>,
}
fn core_range(start: usize, text: &str) -> (usize, usize) {
let (mut from, mut to) = (0, text.len());
loop {
let inner = &text[from..to];
let trimmed = inner.trim();
from += inner.len() - inner.trim_start().len();
to = from + trimmed.len();
let wrapped = trimmed.starts_with('(') && trimmed.ends_with(')') && {
let mut depth = 0usize;
trimmed.char_indices().all(|(i, c)| {
match c {
'(' => depth += 1,
')' => depth -= 1,
_ => {}
}
depth > 0 || i == trimmed.len() - 1
})
};
if !wrapped {
return (start + from, start + to);
}
from += 1;
to -= 1;
}
}
struct SitePlan<'a> {
gaps: Vec<PlannedGap>,
cannot_differ: bool,
constant: bool,
run: Vec<Mutation>,
infected: InfectedTests<'a>,
reaching: ReachingTests<'a>,
}
enum Planned<'a> {
Unreached,
NotEvaluated,
Nothing,
Plan(SitePlan<'a>),
}
type ConfirmedGap = (Finding, Vec<usize>, Option<(usize, usize)>);
struct SiteWork<'a> {
file: &'a str,
site: &'a Site,
gaps: Vec<ConfirmedGap>,
constant: bool,
cannot_differ: bool,
runs: Vec<(Mutation, usize)>,
}
impl Session {
fn note(&self, text: &str) {
if self.progress {
eprintln!("tmt: {text}");
}
}
fn merged<T: Default + Copy>(
&self,
select: impl Fn(&Trace) -> Option<&BTreeMap<String, T>>,
merge: impl Fn(&mut T, &T),
) -> T {
let mut all = T::default();
for obs in self
.binaries
.iter()
.filter_map(|b| select(&b.trace))
.flat_map(|t| t.values())
{
merge(&mut all, obs);
}
all
}
fn plan<'a>(&'a self, file: &str, site: &'a Site, verify: bool) -> Planned<'a> {
let id = site.id;
let reach_plan = |mutation: Mutation| SitePlan {
gaps: vec![],
constant: false,
cannot_differ: false,
run: vec![mutation],
infected: Box::new(move |bin, _| bin.trace.reach.get(&id).cloned().unwrap_or_default()),
reaching: Box::new(move |bin| bin.trace.reach.get(&id).cloned().unwrap_or_default()),
};
let reached = self
.binaries
.iter()
.any(|b| b.trace.reach.contains_key(&id));
let opaque = self
.merged(|t| t.arith.get(&id), plan::ArithObs::merge)
.opaque;
Planned::Plan(match &site.kind {
SiteKind::Stmt
| SiteKind::Neg { .. }
| SiteKind::Field { .. }
| SiteKind::Body { .. }
if reached =>
{
reach_plan(Mutation::Delete)
}
SiteKind::Stmt
| SiteKind::Neg { .. }
| SiteKind::Field { .. }
| SiteKind::Body { .. } => return Planned::Unreached,
SiteKind::Guard { can_be_false } => {
let can_be_false = *can_be_false;
let allowed = move |m: &Mutation| can_be_false || *m != Mutation::Const(false);
let merged = self.merged(|t| t.returns.get(&id), plan::ReturnObs::merge);
let guard_plan = plan::plan_return(&merged);
if guard_plan.unreached {
return Planned::Unreached;
}
let gaps = guard_plan
.always
.filter(|always| allowed(&Mutation::Const(*always)))
.map(|always| PlannedGap {
finding: report::guard_gap_finding(file, site, always, verify),
survivors: vec![Mutation::Const(always)],
constant_expr: Some((site.start, site.end)),
})
.into_iter()
.collect();
SitePlan {
constant: false,
cannot_differ: false,
gaps,
run: guard_plan.run.into_iter().filter(allowed).collect(),
infected: Box::new(move |bin, m| {
tests_where(bin.trace.returns.get(&id), |obs| match m {
Mutation::Const(value) => obs.infected_by_const(value),
_ => obs.reached(),
})
}),
reaching: Box::new(move |bin| {
tests_where(bin.trace.returns.get(&id), plan::ReturnObs::reached)
}),
}
}
SiteKind::Arm { .. } if reached => reach_plan(Mutation::Delete),
SiteKind::Arm { .. } => return Planned::Unreached,
SiteKind::Not { .. } if reached => reach_plan(Mutation::DropNot),
SiteKind::Range { .. }
if reached
&& self
.binaries
.iter()
.any(|b| b.trace.ranges_at_top.contains(&id)) =>
{
return Planned::NotEvaluated;
}
SiteKind::Range { .. } if reached => reach_plan(Mutation::RangeEnd),
SiteKind::Not { .. } | SiteKind::Range { .. } if opaque => return Planned::Nothing,
SiteKind::Not { .. } | SiteKind::Range { .. } => return Planned::Unreached,
SiteKind::Cmp { op, literal, .. } => {
let op = *op;
let mut merged = Obs::default();
for bin in &self.binaries {
merged.merge(&bin.trace.merged(id));
}
let bounds = self.binaries.iter().find_map(|b| b.trace.bounds.get(&id));
let cmp_plan = plan::plan_cmp(op, &merged, domain_of(*literal, bounds));
let mut gaps = vec![];
let mut constant = false;
match &cmp_plan.gap {
Some(plan::InputGap::Unreached) => return Planned::Unreached,
Some(gap) => {
constant = matches!(gap, plan::InputGap::OneSided { .. });
if let Some(finding) =
report::input_gap_finding(file, site, gap, &merged, verify)
{
gaps.push(PlannedGap {
finding,
survivors: gap.survivors(),
constant_expr: None,
});
}
}
None => {}
}
SitePlan {
gaps,
constant,
cannot_differ: cmp_plan.cannot_differ,
run: cmp_plan.run,
infected: Box::new(move |bin, m| {
tests_where(bin.trace.cmp.get(&id), |obs| plan::infects(op, m, obs))
}),
reaching: Box::new(move |bin| {
tests_where(bin.trace.cmp.get(&id), Obs::reached)
}),
}
}
SiteKind::Logic {
and,
lhs,
rhs,
gap: op_gap,
} => {
let and = *and;
let lhs_range = core_range(site.start, lhs);
let rhs_range = core_range(op_gap.1, rhs);
let merged = self.merged(|t| t.logic.get(&id), plan::LogicObs::merge);
let logic_plan = plan::plan_logic(and, &merged);
if logic_plan.gaps.contains(&plan::LogicGap::Unreached) {
return Planned::Unreached;
}
let gaps: Vec<_> = logic_plan
.gaps
.iter()
.filter_map(|gap| {
let (mutation, operand) = match gap {
plan::LogicGap::RhsNeverDecides => (Mutation::LogicDropRhs, rhs_range),
_ => (Mutation::LogicDropLhs, lhs_range),
};
Some(PlannedGap {
finding: report::logic_gap_finding(file, site, *gap, verify)?,
survivors: vec![mutation],
constant_expr: Some(operand),
})
})
.collect();
SitePlan {
constant: merged.constant_value(and).is_some(),
cannot_differ: false,
gaps,
run: logic_plan.run,
infected: Box::new(move |bin, m| {
tests_where(bin.trace.logic.get(&id), |obs| {
plan::logic_infects(and, m, obs)
})
}),
reaching: Box::new(move |bin| {
tests_where(bin.trace.logic.get(&id), plan::LogicObs::reached)
}),
}
}
SiteKind::Arith { .. } | SiteKind::MinMax { .. } => {
let merged = self.merged(|t| t.arith.get(&id), plan::ArithObs::merge);
let mutations: Vec<(Mutation, plan::ArithObs)> = match &site.kind {
SiteKind::MinMax { .. } => vec![(Mutation::MinMax, merged)],
SiteKind::Arith { op, assign, .. } if op.second(*assign).is_some() => vec![
(Mutation::ArithSwap, merged),
(Mutation::ArithSwap2, merged.second()),
],
_ => vec![(Mutation::ArithSwap, merged)],
};
let (mut gaps, mut run) = (vec![], vec![]);
for (mutation, seen) in mutations {
match plan::plan_arith(&seen) {
plan::ArithPlan::Unreached => return Planned::Unreached,
plan::ArithPlan::Opaque => return Planned::Nothing,
plan::ArithPlan::NeverDiffers => {
let finding = if mutation == Mutation::MinMax {
report::min_max_gap_finding(file, site, verify)
} else {
report::arith_gap_finding(file, site, mutation, verify)
};
gaps.extend(finding.map(|finding| PlannedGap {
finding,
survivors: vec![mutation],
constant_expr: None,
}));
}
plan::ArithPlan::Run => run.push(mutation),
}
}
SitePlan {
gaps,
constant: false,
cannot_differ: false,
run,
infected: Box::new(move |bin, m| {
tests_where(bin.trace.arith.get(&id), |obs| obs.infected_by(m))
}),
reaching: Box::new(move |bin| {
tests_where(bin.trace.arith.get(&id), |obs| obs.same || obs.differs)
}),
}
}
SiteKind::Return {
sole_expr, option, ..
} => {
let sole_expr = *sole_expr;
let is_option = option.is_some();
let merged = self.merged(|t| t.returns.get(&id), plan::ReturnObs::merge);
let return_plan = if is_option {
plan::plan_option_return(&merged)
} else {
plan::plan_return(&merged)
};
if return_plan.unreached {
return Planned::Unreached;
}
let gaps: Vec<_> = return_plan
.always
.and_then(|always| {
Some(PlannedGap {
finding: report::return_gap_finding(file, site, always, verify)?,
survivors: vec![Mutation::Const(always)],
constant_expr: sole_expr,
})
})
.into_iter()
.collect();
SitePlan {
constant: false,
cannot_differ: false,
gaps,
run: return_plan.run,
infected: Box::new(move |bin, m| {
tests_where(bin.trace.returns.get(&id), |obs| match m {
Mutation::Const(value) => obs.infected_by_const(value),
_ => obs.reached(),
})
}),
reaching: Box::new(move |bin| {
tests_where(bin.trace.returns.get(&id), plan::ReturnObs::reached)
}),
}
}
})
}
fn job(
&self,
site: u32,
mutation: Mutation,
tests_of: &dyn Fn(&TestBinary) -> BTreeSet<String>,
) -> Job {
let tests = self
.binaries
.iter()
.enumerate()
.filter_map(|(index, bin)| {
let tests = tests_of(bin);
if tests.is_empty() {
return None;
}
let filter = match bin.runner {
Runner::Exe(_) => test_filter(&tests, &bin.tests),
Runner::Doc { .. } => None,
};
Some((index, filter))
})
.collect();
Job {
site,
mutation,
tests,
}
}
fn run_job(&self, job: &Job, sharing: usize) -> Result<JobResult> {
let spec = format!("{}:{}", job.site, job.mutation.encode());
let mut passed = vec![];
let mut tests: Vec<&(usize, Option<Vec<String>>)> = job.tests.iter().collect();
tests.sort_by_key(|(index, _)| self.binaries[*index].baseline);
for (index, filter) in tests {
let bin = &self.binaries[*index];
let outcome = run_binary(
bin,
filter.as_deref(),
&[("TMT_MUTANT", &spec)],
mutant_timeout(bin.baseline),
true,
sharing,
)?;
if outcome != Outcome::Pass {
return Ok(JobResult {
survived: None,
timed_out: outcome == Outcome::Timeout,
unable: outcome == Outcome::Unable,
});
}
match filter {
Some(names) => passed.extend(names.iter().cloned()),
None => passed.push(format!("all tests of `{}`", bin.name)),
}
}
Ok(JobResult {
survived: Some(passed),
timed_out: false,
unable: false,
})
}
fn trace_job(
&self,
job: &Job,
scratch: &Path,
sharing: usize,
) -> Result<BTreeMap<String, BTreeSet<Change>>> {
let spec = format!("{}:{}", job.site, job.mutation.encode());
let mut all: BTreeMap<String, BTreeSet<Change>> = BTreeMap::new();
for (index, filter) in &job.tests {
let bin = &self.binaries[*index];
let path = scratch.join(format!("effects-{}-{index}.tsv", job.site));
let _ = fs::remove_file(&path);
let trace_env = path.to_string_lossy().into_owned();
let outcome = run_binary(
bin,
filter.as_deref(),
&[("TMT_MUTANT", &spec), ("TMT_TRACE", &trace_env)],
mutant_timeout(bin.traced),
false,
sharing,
)?;
let text = fs::read_to_string(&path).unwrap_or_default();
let _ = fs::remove_file(&path);
if outcome != Outcome::Pass {
continue; }
let mutated = Trace::parse(&text);
let ran: Option<BTreeSet<String>> =
filter.as_ref().map(|names| names.iter().cloned().collect());
for (test, found) in propagation::changes(&bin.trace, &mutated, ran.as_ref(), job.site)
{
all.entry(test).or_default().extend(found);
}
}
Ok(all)
}
fn run_jobs(&self, jobs: &[Job], workers: usize) -> Result<Vec<JobResult>> {
let sharing = workers.clamp(1, jobs.len().max(1));
let mut results = run_pool(jobs.len(), workers, |index| {
self.run_job(&jobs[index], sharing)
})?;
if sharing > 1 {
for (job, result) in jobs.iter().zip(&mut results) {
if result.timed_out {
*result = self.run_job(job, 1)?;
}
}
}
Ok(results)
}
}
fn run_pool<T: Send>(
count: usize,
workers: usize,
work: impl Fn(usize) -> Result<T> + Sync,
) -> Result<Vec<T>> {
let next = std::sync::atomic::AtomicUsize::new(0);
let done: Vec<Vec<(usize, Result<T>)>> = std::thread::scope(|scope| {
let handles: Vec<_> = (0..workers.clamp(1, count.max(1)))
.map(|_| {
scope.spawn(|| {
let mut mine = vec![];
loop {
let index = next.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
if index >= count {
return mine;
}
mine.push((index, work(index)));
}
})
})
.collect();
handles
.into_iter()
.map(|h| h.join().expect("worker panicked"))
.collect()
});
let mut slots: Vec<Option<T>> = (0..count).map(|_| None).collect();
for (index, result) in done.into_iter().flatten() {
slots[index] = Some(result?);
}
Ok(slots
.into_iter()
.map(|slot| slot.expect("every job ran"))
.collect())
}
pub fn run(options: &Options) -> Result<Report> {
let note = |text: &str| {
if options.progress {
eprintln!("tmt: {text}");
}
};
let dir = options
.dir
.canonicalize()
.with_context(|| format!("no such directory: {}", options.dir.display()))?;
let output = Command::new("cargo")
.args(["metadata", "--no-deps", "--format-version", "1"])
.args(options.cargo.flags())
.current_dir(&dir)
.output()
.context("running cargo metadata")?;
if !output.status.success() {
bail!(
"cargo metadata failed:\n{}",
String::from_utf8_lossy(&output.stderr)
);
}
let metadata: Metadata =
serde_json::from_slice(&output.stdout).context("parsing cargo metadata")?;
let package = match &options.package {
Some(name) => metadata.packages.iter().find(|p| &p.name == name),
None => metadata
.packages
.iter()
.find(|p| p.manifest_path.parent() == Some(dir.as_path()))
.or(match &metadata.packages[..] {
[only] => Some(only),
_ => None,
}),
}
.ok_or_else(|| anyhow!("cannot tell which package to analyse; pass --package <name>"))?;
let mut test_packages: Vec<&Package> = vec![package];
for name in &options.also_test {
let other = metadata
.packages
.iter()
.find(|p| &p.name == name)
.ok_or_else(|| anyhow!("--also-test: no package `{name}` in the workspace"))?;
if !test_packages.iter().any(|p| p.name == other.name) {
test_packages.push(other);
}
}
if options.dependents {
for name in dependents_of(&package.name, &metadata.packages) {
if let Some(other) = metadata.packages.iter().find(|p| p.name == name)
&& !test_packages.iter().any(|p| p.name == other.name)
{
test_packages.push(other);
}
}
}
let is_kind = |t: &Target, kinds: &[&str]| t.kind.iter().any(|k| kinds.contains(&k.as_str()));
let root_target = package
.targets
.iter()
.find(|t| is_kind(t, &["lib", "rlib", "cdylib", "staticlib", "dylib"]))
.or_else(|| package.targets.iter().find(|t| is_kind(t, &["bin"])))
.ok_or_else(|| anyhow!("package `{}` has no lib or bin target", package.name))?;
let workspace = metadata.workspace_root.canonicalize()?;
let work = match &options.work_dir {
Some(dir) => {
fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
dir.canonicalize()?
}
None => metadata.target_directory.join("tmt"),
};
if workspace.starts_with(&work) {
bail!(
"the work directory {} contains the workspace; choose a directory of its own",
work.display()
);
}
fs::create_dir_all(&work).with_context(|| format!("creating {}", work.display()))?;
let work = work.canonicalize()?;
let copy = work.join("src");
let marker = work.join(WORK_MARKER);
if copy.exists() && !marker.exists() {
bail!(
"{} exists and was not created by tmt; refusing to delete it. \
Choose another --work-dir or remove it yourself.",
copy.display()
);
}
fs::write(
&marker,
"Working directory of tmt (targeted-mutation). Safe to delete.\n",
)?;
let _lock = WorkLock::take(&work)?;
let target_dir = metadata.target_directory.clone();
let skip = |path: &Path| {
path == target_dir
|| path == work
|| path
.file_name()
.is_some_and(|n| n == ".git" || n == "node_modules")
|| (path.parent() == Some(workspace.as_path())
&& path.file_name().is_some_and(|n| n == "target"))
};
let state = WorkCopy::open(&work, ©);
fs::create_dir_all(©)?;
let visible = if options.all_files {
None
} else {
git_visible_files(&workspace)?
};
match visible {
Some(files) => {
let copied = copy_git_visible(&workspace, ©, files, &workspace, &skip, &state)?;
note(&format!(
"copied {copied} files (ignored files are left out)"
));
}
None => copy_tree(&workspace, ©, &workspace, &skip, &state)?,
}
prune(©, &state)?;
let mut manifests: Vec<&Path> = metadata
.packages
.iter()
.map(|p| p.manifest_path.as_path())
.collect();
let root_manifest = metadata.workspace_root.join("Cargo.toml");
manifests.push(&root_manifest);
for manifest in manifests {
let Ok(canonical) = manifest.canonicalize() else {
continue;
};
let (Some(manifest_dir), Ok(relative)) =
(canonical.parent(), canonical.strip_prefix(&workspace))
else {
continue;
};
let text = fs::read_to_string(&canonical)?;
if let Some(rewritten) =
absolutize_path_dependencies(&text, manifest_dir, &workspace, ©)?
{
state.write(©.join(relative), &rewritten)?;
}
}
let in_copy = |path: &Path| -> Result<PathBuf> {
let canonical = path.canonicalize()?;
let relative = canonical
.strip_prefix(&workspace)
.with_context(|| format!("{} is outside the workspace", path.display()))?;
Ok(copy.join(relative))
};
let package_dir = in_copy(
package
.manifest_path
.parent()
.expect("manifest has a parent"),
)?;
let root_file = in_copy(&root_target.src_path)?;
let source_dir = root_file
.parent()
.expect("source file has a parent")
.to_path_buf();
let mut other_roots = HashSet::new();
let mut other_dirs = HashSet::new();
for target in &package.targets {
if target.src_path == root_target.src_path {
continue;
}
let path = in_copy(&target.src_path)?;
if let Some(parent) = path.parent().filter(|p| *p != source_dir) {
other_dirs.insert(parent.to_path_buf());
}
other_roots.insert(path);
}
let mut paths = vec![];
rust_files(
&source_dir,
&|p| {
other_roots.contains(p)
|| other_dirs.contains(p)
|| p.file_name().is_some_and(|n| n == "target")
},
&mut paths,
)?;
let mut files = vec![];
let mut test_only = HashSet::new();
let mut next_id = 0u32;
for path in paths {
let Some(original) = state.original(&path, &workspace)? else {
continue; };
let display = path
.strip_prefix(&package_dir)
.unwrap_or(&path)
.display()
.to_string();
match instrument::discover(&original, next_id) {
Ok(found) => {
next_id += found.sites.len() as u32;
for module in &found.test_modules {
test_only.extend(module_paths(&path, module));
}
let places = found
.sites
.iter()
.chain(&found.rebuild_sites)
.map(|site| {
let at = report::location("", site);
(at.line, at.column, at.code)
})
.collect();
files.push(SourceFile {
display,
path,
original,
places,
sites: found.sites,
rebuild_sites: found.rebuild_sites,
rendered: None,
});
}
Err(err) => note(&format!("skipping {display}: {err:#}")),
}
}
files.retain(|f| !f.path.ancestors().any(|a| test_only.contains(a)));
let scope = requested_scope(options, &workspace, &package_dir, ©)?;
if let Some(scope) = &scope {
for file in &mut files {
let relative = file
.path
.strip_prefix(©)
.unwrap_or(&file.path)
.to_string_lossy()
.into_owned();
let original = &file.original;
let in_scope = |site: &Site| {
scope.touches(&relative, scope::line_of(original, site.start), scope::line_of(original, site.end))
|| scope.touches(&relative, site.line, site.line)
};
file.sites.retain(in_scope);
file.rebuild_sites.retain(in_scope);
}
files.retain(|f| !f.sites.is_empty() || !f.rebuild_sites.is_empty() || f.path == root_file);
}
let total_sites: usize = files
.iter()
.map(|f| f.sites.len() + f.rebuild_sites.len())
.sum();
note(&format!("{} sites in {} files", total_sites, files.len()));
let root_source = state
.original(&root_file, &workspace)?
.with_context(|| format!("{} is missing", root_target.src_path.display()))?;
state.write(
&source_dir.join(format!("{RUNTIME_MOD}.rs")),
crate::RUNTIME_SOURCE,
)?;
let std_alias = format!("extern crate std as {STD_ALIAS};");
let root_suffix = if root_source.contains(&std_alias) {
format!("\n#[doc(hidden)]\nmod {RUNTIME_MOD};\n")
} else {
format!("\n#[doc(hidden)]\n{std_alias}\n#[doc(hidden)]\nmod {RUNTIME_MOD};\n")
};
let mut disabled: HashSet<u32> = HashSet::new();
let build_target = work.join("target");
let cargo_build = || {
Command::new("cargo")
.args(["test", "--no-run", "--message-format=json"])
.args(test_packages.iter().flat_map(|p| ["-p", p.name.as_str()]))
.args(options.cargo.flags())
.current_dir(©)
.env("CARGO_TARGET_DIR", &build_target)
.envs(profile_env(options.opt_level))
.stderr(Stdio::piped())
.output()
.context("running cargo test --no-run")
};
let mut rounds = 0;
let build = loop {
for file in &mut files {
let rendered =
instrument::render(&file.original, &file.sites, &|id| !disabled.contains(&id));
let mut text = rendered.text.clone();
if file.path == root_file {
text.push_str(&root_suffix);
}
state.write(&file.path, &text)?;
file.rendered = Some(rendered);
}
if !files.iter().any(|f| f.path == root_file) {
state.write(&root_file, &format!("{root_source}{root_suffix}"))?;
}
if rounds == 0 {
state.settle(&workspace)?;
}
note(if rounds == 0 {
"building the instrumented crate"
} else {
"rebuilding without the sites that failed to compile"
});
let output = cargo_build()?;
let names: Vec<&str> = test_packages.iter().map(|p| p.name.as_str()).collect();
let build = parse_build_output(&String::from_utf8_lossy(&output.stdout), &names);
if output.status.success() {
break build;
}
if build.errors.is_empty() {
bail!(
"the build failed:\n{}",
String::from_utf8_lossy(&output.stderr)
);
}
rounds += 1;
let before = disabled.len();
let mut unexplained = vec![];
let mut blamed_now: HashSet<u32> = HashSet::new();
for error in &build.errors {
let blamed = blame_error(error, &files, ©, &disabled);
if std::env::var_os("TMT_DEBUG").is_some() {
eprintln!("tmt: debug: blaming {blamed:?} for\n{}", error.rendered);
}
if blamed.is_empty() {
unexplained.push(error);
}
blamed_now.extend(blamed);
}
disabled.extend(blamed_now);
if disabled.len() == before || rounds > MAX_REPAIR_ROUNDS {
let shown = unexplained
.first()
.copied()
.or(build.errors.first())
.map_or("", |e| e.rendered.as_str());
bail!(
"the crate does not build after instrumentation, and the error is not at a probe.\n\
Does `cargo test --no-run` pass on the original?\n{shown}"
);
}
};
if build.test_binaries.is_empty() {
bail!("`{}` has no test binaries", package.name);
}
let mut session = Session {
progress: options.progress,
package_dir,
binaries: vec![],
};
let mut runners: Vec<(String, Runner, PathBuf)> = vec![];
for (name, exe, owner) in build.test_binaries {
let owner_package = test_packages
.iter()
.find(|p| p.name == owner)
.expect("binaries are filtered by these packages");
let cwd = in_copy(
owner_package
.manifest_path
.parent()
.expect("manifest has a parent"),
)?;
let name = if owner == package.name {
name
} else {
format!("{owner}::{name}")
};
runners.push((name, Runner::Exe(exe), cwd));
}
if options.doc && is_kind(root_target, &["lib", "rlib", "proc-macro"]) {
let doc = Runner::Doc {
copy: copy.clone(),
target_dir: build_target.clone(),
package: package.name.clone(),
opt_level: options.opt_level,
flags: options.cargo.flags(),
};
runners.push(("doc tests".to_string(), doc, session.package_dir.clone()));
}
let marks = marks_dir(&work)?;
for (index, (name, runner, cwd)) in runners.into_iter().enumerate() {
let trace_path = work.join(format!("trace-{index}.tsv"));
let _ = fs::remove_file(&trace_path);
let mut bin = TestBinary {
name,
cwd,
marks: marks.clone(),
tests: BTreeSet::new(),
runner,
baseline: Duration::ZERO,
traced: Duration::ZERO,
trace: Trace::default(),
};
session.note(&format!("tracing `{}`", bin.name));
let started = Instant::now();
let trace_env = trace_path.to_string_lossy().into_owned();
let outcome = run_binary(
&bin,
None,
&[("TMT_TRACE", &trace_env)],
Duration::from_secs(3600),
false,
1,
)?;
if outcome != Outcome::Pass {
bail!(
"the tests in `{}` do not pass on the unmutated code; fix them first",
bin.name
);
}
bin.traced = started.elapsed();
bin.baseline = bin.traced;
if bin.traced > SLOW_TRACE {
let started = Instant::now();
match run_binary(&bin, None, &[], bin.traced, false, 1)? {
Outcome::Pass => bin.baseline = started.elapsed(),
Outcome::Fail => bail!(
"the tests of `{}` pass while their run is recorded and fail without: \
they do not always give the same result, and nothing can be concluded \
from running them",
bin.name
),
Outcome::Timeout | Outcome::Unable => {}
}
}
let text = match fs::read_to_string(&trace_path) {
Ok(text) => text,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => String::new(),
Err(err) => bail!("cannot read the trace of `{}`: {err}", bin.name),
};
bin.trace = Trace::parse(&text);
if bin.trace.malformed_lines > 0 {
bail!(
"the trace of `{}` has {} malformed lines; not drawing conclusions from it",
bin.name,
bin.trace.malformed_lines
);
}
if let Runner::Exe(exe) = &bin.runner {
let listing = Command::new(exe)
.args(["--list", "--format", "terse"])
.current_dir(&bin.cwd)
.stdin(Stdio::null())
.stderr(Stdio::null())
.output()
.with_context(|| format!("listing the tests of `{}`", bin.name))?;
bin.tests = parse_test_list(&String::from_utf8_lossy(&listing.stdout));
}
session.binaries.push(bin);
}
let mut report = Report {
package: package.name.clone(),
sites: total_sites,
analysis: report::Analysis {
package_path: repository_prefix(
package.manifest_path.parent().unwrap_or(Path::new(".")),
),
since: options.since.clone(),
lines: options.lines.clone(),
tests_of: test_packages.iter().map(|p| p.name.clone()).collect(),
cargo: options.cargo.clone(),
opt_level: options.opt_level,
rebuild: options.rebuild,
verified: options.verify,
doc_tests: options.doc,
},
..Report::default()
};
for site in files.iter().flat_map(|f| &f.sites) {
if disabled.contains(&site.id) {
match site.kind {
SiteKind::Body { .. } => report.unviable_mutants += 1,
_ if options.rebuild && !instrument::source_mutants(site).is_empty() => {}
_ => report.skipped_sites += 1,
}
}
}
let scratch = work.clone();
let mut jobs: Vec<Job> = vec![];
let mut not_evaluated: HashSet<u32> = HashSet::new();
let mut work: Vec<SiteWork> = vec![];
let mut effect_jobs: Vec<(usize, usize)> = vec![];
for file in &files {
for site in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
let plan = match session.plan(&file.display, site, options.verify) {
Planned::Unreached => {
let at = report::location(&file.display, site);
if report.unreached.last() != Some(&at) {
report.unreached.push(at);
}
continue;
}
Planned::Nothing => continue,
Planned::NotEvaluated => {
not_evaluated.insert(site.id);
continue;
}
Planned::Plan(plan) => plan,
};
let mut add =
|mutation: Mutation, tests_of: &dyn Fn(&TestBinary) -> BTreeSet<String>| {
jobs.push(session.job(site.id, mutation, tests_of));
jobs.len() - 1
};
let gaps = plan
.gaps
.into_iter()
.map(
|PlannedGap {
finding,
survivors,
constant_expr,
}| {
let confirm = if options.verify {
survivors
.into_iter()
.map(|m| add(m, &*plan.reaching))
.collect()
} else {
vec![]
};
(finding, confirm, constant_expr)
},
)
.collect();
let infected = &plan.infected;
let runs = plan
.run
.iter()
.map(|m| (*m, add(*m, &|bin| infected(bin, *m))))
.collect();
work.push(SiteWork {
file: &file.display,
site,
gaps,
constant: plan.constant,
cannot_differ: plan.cannot_differ,
runs,
});
}
}
session.note(&format!(
"running {} mutants on {} thread(s)",
jobs.len(),
options.jobs.max(1)
));
let mut results = session.run_jobs(&jobs, options.jobs)?;
if let Some(wanted) = options.audit {
let survivors: Vec<usize> = (0..jobs.len())
.filter(|job| results[*job].survived.is_some())
.collect();
let chosen: Vec<usize> = spread(survivors.len(), wanted)
.into_iter()
.map(|nth| survivors[nth])
.collect();
session.note(&format!(
"audit: running {} of {} surviving mutants against all tests",
chosen.len(),
survivors.len()
));
let against_all: Vec<Job> = chosen
.iter()
.map(|job| Job {
site: jobs[*job].site,
mutation: jobs[*job].mutation,
tests: (0..session.binaries.len()).map(|bin| (bin, None)).collect(),
})
.collect();
let mut audit = report::Audit {
sampled: chosen.len(),
survivors: survivors.len(),
..report::Audit::default()
};
for (job, again) in chosen
.iter()
.zip(session.run_jobs(&against_all, options.jobs)?)
{
if again.survived.is_none() {
results[*job] = again;
let site = files
.iter()
.find_map(|f| Some((f, f.sites.iter().find(|s| s.id == jobs[*job].site)?)));
if let Some((file, site)) = site {
audit
.disagreements
.push(report::location(&file.display, site));
}
}
}
session.note("audit: recording the tests once more");
for (index, bin) in session.binaries.iter().enumerate() {
let path = scratch.join(format!("trace-{index}-audit.tsv"));
let _ = fs::remove_file(&path);
let trace_env = path.to_string_lossy().into_owned();
let limit = Duration::from_secs(3600);
let outcome = run_binary(bin, None, &[("TMT_TRACE", &trace_env)], limit, false, 1)?;
let again = Trace::parse(&fs::read_to_string(&path).unwrap_or_default());
let _ = fs::remove_file(&path);
let records = bin.trace.differences(&again);
if outcome != Outcome::Pass || records > 0 {
audit.trace_differences.push(report::TraceDifference {
binary: bin.name.clone(),
records,
});
}
}
report.audit = Some(audit);
}
let unable = results.iter().filter(|r| r.unable).count();
not_evaluated.extend(
jobs.iter()
.zip(&results)
.filter(|(_, result)| result.unable)
.map(|(job, _)| job.site),
);
if !options.rebuild {
report.mutants_not_evaluated = not_evaluated.len();
}
report.mutants_run = results.len() - unable;
report.mutants_killed = results.iter().filter(|r| r.survived.is_none()).count() - unable;
report.mutants_timed_out = results.iter().filter(|r| r.timed_out).count();
let confirmed = |w: &SiteWork| {
w.gaps
.iter()
.all(|(_, confirm, _)| confirm.iter().all(|j| results[*j].survived.is_some()))
};
let constants: BTreeSet<(&str, usize, usize)> = work
.iter()
.filter(|w| w.cannot_differ || (w.constant && confirmed(w)))
.map(|w| (w.file, w.site.start, w.site.end))
.collect();
for item in &work {
let at = report::location(item.file, item.site);
for (finding, confirm, constant_expr) in &item.gaps {
let repeats = constant_expr
.is_some_and(|(start, end)| constants.contains(&(item.file, start, end)));
if confirm.iter().any(|j| results[*j].survived.is_none()) {
report.unstable.push(at.clone());
} else if !repeats {
report.findings.push(finding.clone());
}
}
if let SiteKind::Body {
sole_expr: Some((start, end)),
..
} = item.site.kind
&& constants.contains(&(item.file, start, end))
{
continue;
}
let mut survivors = vec![];
let mut passing_tests = BTreeSet::new();
for (mutation, job) in &item.runs {
if let Some(tests) = &results[*job].survived {
survivors.push(report::describe(item.site, *mutation));
passing_tests.extend(tests.iter().cloned());
}
}
if !survivors.is_empty() {
let first = item
.runs
.iter()
.find(|(_, job)| results[*job].survived.is_some());
effect_jobs.push((report.findings.len(), first.expect("a survivor").1));
report.findings.push(Finding::AssertionGap {
at,
survivors,
tests: passing_tests.into_iter().collect(),
effects: vec![],
effects_of: None,
});
}
}
if options.effects && !effect_jobs.is_empty() {
session.note(&format!("tracing {} surviving mutants", effect_jobs.len()));
let sites: BTreeMap<u32, (&str, &Site)> = files
.iter()
.flat_map(|f| f.sites.iter().map(move |s| (s.id, (f.display.as_str(), s))))
.collect();
let traced = run_pool(effect_jobs.len(), options.jobs, |index| {
session.trace_job(
&jobs[effect_jobs[index].1],
&scratch,
options.jobs.clamp(1, effect_jobs.len()),
)
})?;
for ((finding, job), mut changes) in effect_jobs.iter().zip(traced) {
if let Some((mutated_file, mutated)) = sites.get(&jobs[*job].site) {
for found in changes.values_mut() {
found.retain(|change| {
sites.get(&change.site()).is_none_or(|(file, site)| {
file != mutated_file
|| site.end <= mutated.start
|| mutated.end <= site.start
})
});
}
changes.retain(|_, found| !found.is_empty());
}
if let Finding::AssertionGap {
effects,
effects_of,
..
} = &mut report.findings[*finding]
{
*effects = describe_effects(&changes, &sites);
*effects_of = sites
.get(&jobs[*job].site)
.map(|(_, site)| report::describe(site, jobs[*job].mutation));
}
}
}
let mut built: Vec<(&SourceFile, &Site, instrument::SourceMutant, Option<usize>)> = vec![];
for file in &files {
let retried = file.sites.iter().filter(|site| {
(disabled.contains(&site.id) && !matches!(site.kind, SiteKind::Body { .. }))
|| not_evaluated.contains(&site.id)
});
for site in file.rebuild_sites.iter().chain(retried) {
built.extend(
instrument::source_mutants(site)
.into_iter()
.map(|mutant| (file, site, mutant, None)),
);
}
}
if !options.rebuild {
report.mutants_not_built = built.len();
built.clear();
}
if let (Some(wanted), Some(audit)) = (options.audit, report.audit.as_mut()) {
let mut twins = vec![];
for file in &files {
for site in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
let integers = session.binaries.iter().all(|bin| {
let seen = bin.trace.merged(site.id);
!seen.reached() || seen.valued()
});
let job_of = |mutation: Mutation| {
jobs.iter()
.position(|job| job.site == site.id && job.mutation == mutation)
};
let mut compared = vec![];
for mutant in instrument::source_mutants(site) {
let job = mutations_like(site, &mutant, integers)
.into_iter()
.find_map(job_of);
if let Some(job) = job {
compared.push(job);
twins.push((file, site, mutant, Some(job)));
}
}
if let (SiteKind::Cmp { op, .. }, Some(job)) =
(&site.kind, job_of(Mutation::Negate))
&& !compared.contains(&job)
{
let negated = instrument::SourceMutant {
start: site.start,
end: site.end,
replacement: format!("!({})", site.text),
what: op.symbol().to_string(),
into: "!".to_string(),
};
twins.push((file, site, negated, Some(job)));
}
}
}
let chosen = spread(twins.len(), wanted);
audit.rebuilt = chosen.len();
let mut twins: Vec<Option<_>> = twins.into_iter().map(Some).collect();
built.extend(chosen.into_iter().filter_map(|nth| twins[nth].take()));
}
if !built.is_empty() {
session.note(&format!(
"building {} mutants one by one (code a probe cannot be put in, or to compare with the probe)",
built.len()
));
let instrumented = |file: &SourceFile, text: &str| {
if file.path == root_file {
format!("{text}{root_suffix}")
} else {
text.to_string()
}
};
let mut by_speed: Vec<&TestBinary> = session.binaries.iter().collect();
by_speed.sort_by_key(|bin| bin.baseline);
let mut survivors: Vec<(report::Location, Vec<String>)> = vec![];
for (file, site, mutant, twin) in &built {
let mutated = format!(
"{}{}{}",
&file.original[..mutant.start],
mutant.replacement,
&file.original[mutant.end..]
);
let attempt = || -> Result<Option<Outcome>> {
state.write(&file.path, &instrumented(file, &mutated))?;
if !cargo_build()?.status.success() {
return Ok(None);
}
for bin in &by_speed {
let outcome =
run_binary(bin, None, &[], mutant_timeout(bin.baseline), true, 1)?;
if outcome != Outcome::Pass {
return Ok(Some(outcome));
}
}
Ok(Some(Outcome::Pass))
};
let attempted = attempt();
let rendered = file.rendered.as_ref().expect("rendered before building");
state.write(&file.path, &instrumented(file, &rendered.text))?;
let outcome = attempted?;
if let Some(job) = twin {
let as_probe = results[*job].survived.is_some();
let Some(audit) = report.audit.as_mut() else {
continue;
};
let comparable = outcome.filter(|_| !results[*job].unable);
match comparable {
Some(_) => audit.compared += 1,
None => audit.not_compared += 1,
}
if comparable.is_some_and(|built| (built == Outcome::Pass) != as_probe) {
let verdict = |passes: bool| if passes { "passes" } else { "fails" };
audit.source_disagreements.push(report::SourceDisagreement {
at: report::location(&file.display, site),
mutant: report::describe(site, mutation_of(site, mutant)),
as_probe: verdict(as_probe).to_string(),
built: verdict(!as_probe).to_string(),
});
}
continue;
}
match outcome {
None => report.unviable_mutants += 1,
Some(outcome) => {
report.mutants_run += 1;
report.mutants_killed += (outcome != Outcome::Pass) as usize;
report.mutants_timed_out += (outcome == Outcome::Timeout) as usize;
}
}
let survived = outcome == Some(Outcome::Pass);
if survived {
let at = report::location(&file.display, site);
let text = report::describe(site, mutation_of(site, mutant));
match survivors.last_mut() {
Some((last, texts)) if *last == at => texts.push(text),
_ => survivors.push((at, vec![text])),
}
}
}
report.findings.extend(
survivors
.into_iter()
.map(|(at, survivors)| Finding::Survivor { at, survivors }),
);
}
report.sort_findings();
let places: Vec<FilePlaces> = files
.iter()
.map(|file| FilePlaces {
display: &file.display,
source: &file.original,
places: &file.places,
})
.collect();
name_findings(&mut report.findings, &places);
let ignored: BTreeMap<&str, BTreeMap<usize, String>> = files
.iter()
.map(|f| {
(
f.display.as_str(),
crate::baseline::ignored_lines(&f.original),
)
})
.collect();
let known = match &options.baseline {
Some(path) => Some(crate::baseline::load(path)?),
None => None,
};
let location = |finding: &Finding| (finding.at().file.clone(), finding.at().line);
let before = report.findings.len();
report.findings.retain(|finding| {
let (file, line) = location(finding);
!ignored
.get(file.as_str())
.is_some_and(|lines| lines.contains_key(&line))
});
if let Some(path) = &options.write_baseline {
crate::baseline::write(path, &report.findings)?;
}
report
.findings
.retain(|finding| !known.as_ref().is_some_and(|known| known.knows(finding)));
report.suppressed = before - report.findings.len();
Ok(report)
}
fn repository_prefix(dir: &Path) -> String {
let shown = Command::new("git")
.arg("-C")
.arg(dir)
.args(["rev-parse", "--show-prefix"])
.stderr(Stdio::null())
.output();
match shown {
Ok(output) if output.status.success() => {
String::from_utf8_lossy(&output.stdout).trim().to_string()
}
_ => String::new(),
}
}
fn spread(count: usize, wanted: usize) -> Vec<usize> {
let wanted = wanted.min(count);
(0..wanted).map(|nth| nth * count / wanted).collect()
}
struct FilePlaces<'a> {
display: &'a str,
source: &'a str,
places: &'a [(usize, usize, String)],
}
fn name_findings(findings: &mut [Finding], files: &[FilePlaces]) {
for file in files {
let items = instrument::named_items(file.source);
let item_at = |line: usize, column: usize| -> String {
instrument::offset_of(file.source, line, column)
.map_or("", |offset| instrument::enclosing_item(&items, offset))
.to_string()
};
let places: BTreeSet<(String, &str, usize, usize)> = file
.places
.iter()
.map(|(line, column, code)| (item_at(*line, *column), code.as_str(), *line, *column))
.collect();
for finding in findings.iter_mut() {
let kind = finding.kind();
let at = finding.at_mut();
if at.file != file.display {
continue;
}
at.item = item_at(at.line, at.column);
let nth = places
.iter()
.filter(|(item, code, line, column)| {
*item == at.item && *code == at.code && (*line, *column) < (at.line, at.column)
})
.count();
at.id = report::finding_id(kind, at, nth);
}
}
}
fn mutation_of(site: &Site, mutant: &instrument::SourceMutant) -> Mutation {
match &site.kind {
SiteKind::Cmp { .. } => plan::CmpOp::ALL
.into_iter()
.find(|op| op.symbol() == mutant.into)
.map_or(Mutation::Negate, Mutation::Op),
SiteKind::Arith { op, .. } => {
if mutant.into.trim_end_matches('=') == op.swapped().symbol() {
Mutation::ArithSwap
} else {
Mutation::ArithSwap2
}
}
SiteKind::Guard { .. } => Mutation::Const(mutant.into == "true"),
SiteKind::Logic { .. } => Mutation::LogicSwap,
SiteKind::Not { .. } => Mutation::DropNot,
SiteKind::Range { .. } => Mutation::RangeEnd,
_ => Mutation::Delete,
}
}
fn mutations_like(site: &Site, mutant: &instrument::SourceMutant, integers: bool) -> Vec<Mutation> {
let mut all = vec![mutation_of(site, mutant)];
if let (SiteKind::Cmp { op, .. }, Mutation::Op(into)) = (&site.kind, all[0]) {
let an_order_is_needed = matches!(op, plan::CmpOp::Le | plan::CmpOp::Ge);
if into == op.negated() && (integers || !an_order_is_needed) {
all.push(Mutation::Negate);
}
match (op, into) {
(plan::CmpOp::Lt, plan::CmpOp::Le) | (plan::CmpOp::Ge, plan::CmpOp::Gt) => {
all.push(Mutation::Shift(1))
}
(plan::CmpOp::Gt, plan::CmpOp::Ge) | (plan::CmpOp::Le, plan::CmpOp::Lt) => {
all.push(Mutation::Shift(-1))
}
_ => {}
}
}
all
}
fn describe_effects(
changes: &BTreeMap<String, BTreeSet<Change>>,
sites: &BTreeMap<u32, (&str, &Site)>,
) -> Vec<String> {
let mut by_change: BTreeMap<&Change, Vec<&str>> = BTreeMap::new();
for (test, found) in changes {
for change in found {
by_change.entry(change).or_default().push(test);
}
}
if by_change.is_empty() {
return vec![
"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(),
];
}
let mut out = vec![];
for (change, tests) in by_change.iter().take(3) {
let Some((file, site)) = sites.get(&change.site()) else {
continue;
};
let code = report::location(file, site).code;
let at = format!("{file}:{}", site.line);
let who = match tests[..] {
["?"] => "a test".to_string(),
[one] => format!("`{one}`"),
[first, ..] => format!("`{first}` (and {} more)", tests.len() - 1),
[] => continue,
};
out.push(match change {
Change::Returns { value, .. } => {
format!("with the mutant, {who} gets `{value}` from `{code}` ({at})")
}
Change::NowRuns { .. } => format!("with the mutant, {who} now runs `{code}` ({at})"),
Change::NoLongerRuns { .. } => {
format!("with the mutant, {who} no longer runs `{code}` ({at})")
}
Change::NewOutcome { .. } => {
format!("with the mutant, {who} takes `{code}` ({at}) a way it did not before")
}
});
}
if by_change.len() > 3 {
out.push(format!("(and {} more such changes)", by_change.len() - 3));
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::trace::UNKNOWN_TEST;
#[test]
fn parses_cargo_json_messages() {
let stdout = concat!(
r#"{"reason":"compiler-artifact","package_id":"p 0.1.0","target":{"name":"p","kind":["lib"]},"profile":{"test":false},"executable":null}"#,
"\n",
r#"{"reason":"compiler-artifact","package_id":"p 0.1.0","target":{"name":"p","kind":["lib"]},"profile":{"test":true},"executable":"/t/p-abc"}"#,
"\n",
r#"{"reason":"compiler-artifact","package_id":"dep 1.0.0","target":{"name":"dep","kind":["lib"]},"profile":{"test":true},"executable":"/t/dep-abc"}"#,
"\n",
r#"{"reason":"compiler-message","message":{"level":"warning","rendered":"w","spans":[{"file_name":"src/lib.rs","byte_start":1,"line_start":1,"is_primary":true}]}}"#,
"\n",
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}]}}"#,
"\n",
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}]}}"#,
"\n",
r#"{"reason":"compiler-message","message":{"level":"error","rendered":"aborting","spans":[]}}"#,
"\n",
"not json\n",
r#"{"reason":"build-finished","success":false}"#,
"\n",
);
let out = parse_build_output(stdout, &["p", "other"]);
assert_eq!(
out.test_binaries,
[("p".to_string(), PathBuf::from("/t/p-abc"), "p".to_string())]
);
let both = parse_build_output(stdout, &["dep", "p"]);
let owners: Vec<&str> = both.test_binaries.iter().map(|b| b.2.as_str()).collect();
assert_eq!(owners, ["p", "dep"]);
assert_eq!(
out.errors,
[CompileError {
primary: vec![ErrorSpan {
file: "src/lib.rs".into(),
byte_start: 40,
line: 3
}],
secondary: vec![ErrorSpan {
file: "src/lib.rs".into(),
byte_start: 2,
line: 1
}],
rendered: "E0308".into(),
}]
);
}
#[test]
fn package_ids_are_matched_by_name() {
assert!(is_package(
"path+file:///w/target/tmt/src#eligibility@0.0.0",
"eligibility"
));
assert!(is_package(
"path+file:///w/eligibility#0.1.0",
"eligibility"
));
assert!(is_package(
"eligibility 0.1.0 (path+file:///w)",
"eligibility"
));
assert!(!is_package(
"path+file:///w/eligibility#other@0.1.0",
"eligibility-core"
));
assert!(!is_package(
"registry+https://github.com/rust-lang/crates.io-index#serde@1.0.0",
"eligibility"
));
}
#[test]
fn test_filter_falls_back_to_the_whole_binary() {
let set = |names: &[&str]| {
names
.iter()
.map(|n| n.to_string())
.collect::<BTreeSet<String>>()
};
let known = set(&["tests::a", "tests::b", "tests::c"]);
assert_eq!(
test_filter(&set(&["tests::a", "tests::b"]), &known),
Some(vec!["tests::a".to_string(), "tests::b".to_string()])
);
assert_eq!(test_filter(&set(&["tests::a", UNKNOWN_TEST]), &known), None);
assert_eq!(test_filter(&set(&["tests::a", "worker"]), &known), None);
assert_eq!(test_filter(&set(&["worker"]), &known), None);
let many: BTreeSet<String> = (0..=MAX_TEST_FILTERS).map(|i| format!("t{i}")).collect();
assert_eq!(test_filter(&many, &many), None);
let limit: BTreeSet<String> = (0..MAX_TEST_FILTERS).map(|i| format!("t{i}")).collect();
assert!(test_filter(&limit, &limit).is_some());
}
#[test]
fn libtest_listing() {
let listing =
"tests::a: test\ntests::nested::b: test\nbench_it: benchmark\n\n2 tests, 1 benchmark\n";
assert_eq!(
parse_test_list(listing).into_iter().collect::<Vec<_>>(),
["tests::a", "tests::nested::b"]
);
}
#[test]
fn domains_from_type_bounds() {
let u8s = crate::trace::TypeBounds {
lhs: (0, 255),
rhs: (0, 255),
};
assert_eq!(
domain_of(LiteralSide::Rhs(18), Some(&u8s)),
Some((-18, 237))
);
assert_eq!(
domain_of(LiteralSide::Lhs(18), Some(&u8s)),
Some((-237, 18))
);
assert_eq!(domain_of(LiteralSide::None, Some(&u8s)), None);
assert_eq!(domain_of(LiteralSide::Rhs(18), None), None);
let wide = crate::trace::TypeBounds {
lhs: (i128::MIN, 0),
rhs: (0, 0),
};
assert_eq!(
domain_of(LiteralSide::Rhs(1), Some(&wide)),
None,
"overflow is not a domain"
);
}
#[test]
fn out_of_line_module_locations() {
let tests = instrument::TestModule {
name: "tests".into(),
path: None,
};
assert_eq!(
module_paths(Path::new("src/lib.rs"), &tests),
[PathBuf::from("src/tests.rs"), PathBuf::from("src/tests")]
);
assert_eq!(
module_paths(Path::new("src/store.rs"), &tests),
[
PathBuf::from("src/store/tests.rs"),
PathBuf::from("src/store/tests")
]
);
assert_eq!(
module_paths(Path::new("src/store/mod.rs"), &tests),
[
PathBuf::from("src/store/tests.rs"),
PathBuf::from("src/store/tests")
]
);
let with_path = instrument::TestModule {
name: "rt".into(),
path: Some("runtime/rt.rs".into()),
};
assert_eq!(
module_paths(Path::new("src/lib.rs"), &with_path),
[PathBuf::from("src/runtime/rt.rs")]
);
}
#[test]
fn path_dependencies_outside_the_workspace_become_absolute() {
let manifest = r#"[package]
name = "app"
[dependencies]
serde = "1"
core = { path = "../core" } # inside the workspace: kept
outside = { path = "../../outside", version = "1" }
[dev-dependencies.helper]
path = "../../../far/helper"
[target.'cfg(unix)'.dependencies]
unix-only = { path = "../../unix" }
[patch.crates-io]
serde = { path = "../../serde-fork" }
"#;
let out = absolutize_path_dependencies(
manifest,
Path::new("/w/ws/app"),
Path::new("/w/ws"),
Path::new("/copy"),
)
.unwrap()
.expect("something to rewrite");
assert!(
out.contains(r#"core = { path = "../core" } # inside the workspace: kept"#),
"{out}"
);
assert!(
out.contains(r#"outside = { path = "/w/outside", version = "1" }"#),
"{out}"
);
assert!(out.contains("path = \"/far/helper\""), "{out}");
assert!(out.contains(r#"unix-only = { path = "/w/unix" }"#), "{out}");
assert!(
out.contains(r#"serde = { path = "/w/serde-fork" }"#),
"{out}"
);
assert!(out.contains("serde = \"1\""), "{out}");
let inside = "[dependencies]\ncore = { path = \"../core\" }\n[workspace.dependencies]\nx = { path = \"x\" }\n";
assert_eq!(
absolutize_path_dependencies(
inside,
Path::new("/w/ws/app"),
Path::new("/w/ws"),
Path::new("/copy")
)
.unwrap(),
None
);
let ws = "[workspace.dependencies]\nshared = { path = \"../shared\" }\n";
let out = absolutize_path_dependencies(
ws,
Path::new("/w/ws"),
Path::new("/w/ws"),
Path::new("/copy"),
)
.unwrap()
.unwrap();
assert!(out.contains(r#"shared = { path = "/w/shared" }"#), "{out}");
assert!(
absolutize_path_dependencies(
"not [ toml",
Path::new("/w"),
Path::new("/w"),
Path::new("/copy")
)
.is_err()
);
assert_eq!(normalize(Path::new("/a/./b/../c")), PathBuf::from("/a/c"));
let absolute = "[dependencies]\nhelper = { path = \"/w/ws/helper\" }\n";
let out = absolutize_path_dependencies(
absolute,
Path::new("/w/ws/app"),
Path::new("/w/ws"),
Path::new("/copy"),
)
.unwrap()
.unwrap();
assert!(
out.contains(r#"helper = { path = "/copy/helper" }"#),
"{out}"
);
}
#[test]
fn pool_runs_every_job_once_and_keeps_the_order() {
use std::sync::atomic::{AtomicUsize, Ordering};
for workers in [0, 1, 2, 3, 8, 100] {
for count in [0, 1, 2, 7, 50] {
let calls: Vec<AtomicUsize> = (0..count).map(|_| AtomicUsize::new(0)).collect();
let results = run_pool(count, workers, |i| {
calls[i].fetch_add(1, Ordering::SeqCst);
std::thread::yield_now();
Ok(i * 10)
})
.unwrap();
assert_eq!(
results,
(0..count).map(|i| i * 10).collect::<Vec<_>>(),
"workers={workers}"
);
assert!(
calls.iter().all(|c| c.load(Ordering::SeqCst) == 1),
"workers={workers} count={count}"
);
}
}
let failed = run_pool(5, 3, |i| {
if i == 3 {
Err(anyhow!("job {i} broke"))
} else {
Ok(i)
}
});
assert_eq!(failed.unwrap_err().to_string(), "job 3 broke");
}
#[test]
fn operand_ranges_ignore_wrapping_parentheses() {
assert_eq!(core_range(10, "a > 0"), (10, 15));
assert_eq!(core_range(10, "(a > 0)"), (11, 16));
assert_eq!(core_range(10, " ( (a > 0) ) "), (14, 19));
assert_eq!(core_range(0, "(a) && (b)"), (0, 10));
assert_eq!(core_range(0, "f(a)"), (0, 4));
assert_eq!(core_range(3, "()"), (4, 4));
assert_eq!(core_range(0, "(a"), (0, 2));
assert_eq!(core_range(0, "a)"), (0, 2));
assert_eq!(core_range(0, ")"), (0, 1));
}
#[test]
fn pool_never_uses_more_threads_than_asked() {
for workers in [1, 2] {
let seen = std::sync::Mutex::new(HashSet::new());
run_pool(6, workers, |_| {
seen.lock().unwrap().insert(std::thread::current().id());
std::thread::sleep(Duration::from_millis(30));
Ok(())
})
.unwrap();
assert_eq!(seen.lock().unwrap().len(), workers);
}
}
#[test]
fn workspace_dependents() {
let package = |name: &str, deps: &[&str]| Package {
name: name.to_string(),
dependencies: deps
.iter()
.map(|d| Dependency {
name: d.to_string(),
})
.collect(),
manifest_path: PathBuf::new(),
targets: vec![],
};
let packages = [
package("core", &["serde"]),
package("mid", &["core"]),
package("app", &["mid", "other"]),
package("other", &[]),
package("cycle", &["app", "core"]),
];
assert_eq!(dependents_of("core", &packages), ["app", "cycle", "mid"]);
assert_eq!(dependents_of("mid", &packages), ["app", "cycle"]);
assert_eq!(dependents_of("other", &packages), ["app", "cycle"]);
assert!(dependents_of("app", &packages) == ["cycle"]);
assert!(dependents_of("nobody", &packages).is_empty());
let mutual = [package("x", &["y"]), package("y", &["x"])];
assert_eq!(dependents_of("x", &mutual), ["y"]);
}
#[test]
fn failure_lines_of_libtest() {
assert!(is_failure_line("test tests::a ... FAILED"));
assert!(is_failure_line(
"test src/lib.rs - double (line 3) ... FAILED"
));
assert!(!is_failure_line("test tests::a ... ok"));
assert!(!is_failure_line("test result: FAILED. 1 passed; 1 failed"));
assert!(!is_failure_line("my output says ... FAILED"));
assert!(!is_failure_line(
"test tests::a ... FAILED (but printed by the test)"
));
}
#[test]
fn effects_in_words() {
let source = "fn f(s: &mut S) -> bool { s.reset(); s.count > 1 }";
let mut found = instrument::discover(source, 0).unwrap().sites;
found.retain(|s| !matches!(s.kind, SiteKind::Body { .. }));
for (id, site) in found.iter_mut().enumerate() {
site.id = id as u32;
}
let sites: BTreeMap<u32, (&str, &Site)> =
found.iter().map(|s| (s.id, ("src/lib.rs", s))).collect();
let texts: Vec<&str> = found.iter().map(|s| s.text.as_str()).collect();
assert_eq!(
texts,
["fn f(s: &mut S) -> bool", "s.reset();", "s.count > 1"]
);
let set = |list: &[Change]| list.iter().cloned().collect::<BTreeSet<Change>>();
let mut changes = BTreeMap::new();
changes.insert(
"tests::a".to_string(),
set(&[
Change::Returns {
site: 0,
value: true,
},
Change::NowRuns { site: 1 },
]),
);
changes.insert(
"tests::b".to_string(),
set(&[Change::NowRuns { site: 1 }, Change::NewOutcome { site: 2 }]),
);
changes.insert("?".to_string(), set(&[Change::NoLongerRuns { site: 2 }]));
assert_eq!(
describe_effects(&changes, &sites),
[
"with the mutant, `tests::a` gets `true` from `fn f(s: &mut S) -> bool` (src/lib.rs:1)",
"with the mutant, `tests::a` (and 1 more) now runs `s.reset();` (src/lib.rs:1)",
"with the mutant, a test no longer runs `s.count > 1` (src/lib.rs:1)",
"(and 1 more such changes)",
]
);
let mut many = BTreeMap::new();
many.insert(
"tests::a".to_string(),
set(&[
Change::NowRuns { site: 0 },
Change::NowRuns { site: 1 },
Change::NowRuns { site: 2 },
Change::NoLongerRuns { site: 0 },
Change::NoLongerRuns { site: 1 },
Change::NoLongerRuns { site: 2 },
]),
);
assert_eq!(
describe_effects(&many, &sites).last().map(String::as_str),
Some("(and 3 more such changes)")
);
let mut few = BTreeMap::new();
few.insert(
"tests::a".to_string(),
set(&[
Change::NowRuns { site: 1 },
Change::NewOutcome { site: 2 },
Change::Returns {
site: 0,
value: false,
},
]),
);
assert_eq!(
describe_effects(&few, &sites),
[
"with the mutant, `tests::a` gets `false` from `fn f(s: &mut S) -> bool` (src/lib.rs:1)",
"with the mutant, `tests::a` now runs `s.reset();` (src/lib.rs:1)",
"with the mutant, `tests::a` takes `s.count > 1` (src/lib.rs:1) a way it did not before",
]
);
assert_eq!(
describe_effects(&BTreeMap::new(), &sites),
[
"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"
]
);
}
#[test]
fn mutant_timeout_scales_with_the_baseline() {
assert_eq!(mutant_timeout(Duration::ZERO), Duration::from_secs(5));
assert_eq!(
mutant_timeout(Duration::from_secs(2)),
Duration::from_secs(15)
);
}
fn scratch(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("tmt-{name}-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(dir.join("ws/src")).unwrap();
fs::create_dir_all(dir.join("work/src")).unwrap();
dir.canonicalize().unwrap()
}
fn set_modified(path: &Path, time: std::time::SystemTime) {
fs::File::options()
.write(true)
.open(path)
.unwrap()
.set_modified(time)
.unwrap();
}
fn modified(path: &Path) -> std::time::SystemTime {
fs::metadata(path).unwrap().modified().unwrap()
}
fn copy_run(dir: &Path, selected: &[&str], write: bool) -> WorkCopy {
let (workspace, work) = (dir.join("ws"), dir.join("work"));
let copy = work.join("src");
let state = WorkCopy::open(&work, ©);
copy_tree(&workspace, ©, &workspace, &|_| false, &state).unwrap();
prune(©, &state).unwrap();
for name in selected {
let path = copy.join(name);
let original = state.original(&path, &workspace).unwrap().unwrap();
assert_eq!(original, fs::read_to_string(workspace.join(name)).unwrap());
if write {
state
.write(&path, &format!("instrumented {original}"))
.unwrap();
} else {
state.record(&path).unwrap(); }
}
if write {
state.settle(&workspace).unwrap();
}
state
}
#[test]
fn work_copy_table() {
let table = include_str!("../tests/data/workcopy.pict.tsv");
let hour_ago = std::time::SystemTime::now() - Duration::from_secs(3600);
let mut rows = 0;
for (index, line) in table.lines().skip(1).enumerate() {
let [earlier, source, selected] = line.split('\t').collect::<Vec<_>>()[..] else {
panic!("bad row: {line}");
};
let dir = scratch(&format!("copy-table-{index}"));
let (file, copied) = (dir.join("ws/src/a.rs"), dir.join("work/src/src/a.rs"));
let log = dir.join("work").join(WRITTEN_LOG);
fs::write(&file, "v1").unwrap();
set_modified(&file, hour_ago);
match earlier {
"none" => {}
"plain" => drop(copy_run(&dir, &[], true)),
"written" => drop(copy_run(&dir, &["src/a.rs"], true)),
"logged_only" => drop(copy_run(&dir, &["src/a.rs"], false)),
_ => panic!("{line}"),
}
if copied.exists() {
set_modified(&copied, hour_ago);
}
let before = fs::read_to_string(&copied).ok();
match source {
"same" => {}
"edited" => fs::write(&file, "version 2").unwrap(),
"deleted" => fs::remove_file(&file).unwrap(),
_ => panic!("{line}"),
}
let selected = selected == "yes";
copy_run(&dir, if selected { &["src/a.rs"] } else { &[] }, true);
let wanted = match (source, selected) {
("deleted", _) => None,
("same", true) => Some("instrumented v1".to_string()),
("same", false) => Some("v1".to_string()),
(_, true) => Some("instrumented version 2".to_string()),
(_, false) => Some("version 2".to_string()),
};
assert_eq!(fs::read_to_string(&copied).ok(), wanted, "{line}");
assert_eq!(
fs::read_to_string(&log).unwrap_or_default(),
if selected { "src/a.rs\n" } else { "" },
"{line}"
);
if before == wanted && wanted.is_some() && earlier != "logged_only" {
assert_eq!(modified(&copied), hour_ago, "{line}");
}
if before != wanted && wanted.is_some() {
assert!(
modified(&copied) > hour_ago + Duration::from_secs(1800),
"{line}"
);
}
copy_run(&dir, &[], true);
assert_eq!(
fs::read_to_string(&copied).ok(),
fs::read_to_string(&file).ok(),
"{line}"
);
assert_eq!(fs::read_to_string(&log).unwrap(), "", "{line}");
fs::remove_dir_all(&dir).unwrap();
rows += 1;
}
assert_eq!(rows, 20);
}
#[test]
fn work_copy_keeps_modification_times() {
let dir = scratch("copy-times");
let hour_ago = std::time::SystemTime::now() - Duration::from_secs(3600);
let names = ["src/lib.rs", "src/plain.rs", "src/edited.rs"];
for name in names {
fs::write(dir.join("ws").join(name), format!("// {name}")).unwrap();
set_modified(&dir.join("ws").join(name), hour_ago);
}
let copy = dir.join("work/src");
let runtime = copy.join("src/__tmt_rt.rs");
let run = || {
let state = copy_run(&dir, &[], false);
for name in ["src/lib.rs", "src/edited.rs"] {
let original = state.original(©.join(name), &dir.join("ws")).unwrap();
state
.write(©.join(name), &format!("probe {}", original.unwrap()))
.unwrap();
}
assert_eq!(state.original(&runtime, &dir.join("ws")).ok(), {
if runtime.exists() { Some(None) } else { None }
});
state.write(&runtime, "runtime").unwrap();
state.settle(&dir.join("ws")).unwrap();
};
run();
for name in names.iter().map(|n| copy.join(n)).chain([runtime.clone()]) {
set_modified(&name, hour_ago);
}
fs::write(dir.join("ws/src/edited.rs"), "// edited since").unwrap();
run();
for name in ["src/lib.rs", "src/plain.rs", "src/__tmt_rt.rs"] {
assert_eq!(modified(©.join(name)), hour_ago, "{name}");
}
assert_ne!(modified(©.join("src/edited.rs")), hour_ago);
assert_eq!(
fs::read_to_string(copy.join("src/edited.rs")).unwrap(),
"probe // edited since"
);
assert_eq!(
fs::read_to_string(copy.join("src/lib.rs")).unwrap(),
"probe // src/lib.rs"
);
assert_eq!(
fs::read_to_string(dir.join("work").join(WRITTEN_LOG)).unwrap(),
"src/__tmt_rt.rs\nsrc/edited.rs\nsrc/lib.rs\n"
);
let later = hour_ago + Duration::from_secs(60);
set_modified(&dir.join("ws/src/plain.rs"), later);
run();
assert_eq!(modified(©.join("src/plain.rs")), hour_ago);
let plain = fs::read_to_string(dir.join("ws/src/plain.rs")).unwrap();
fs::write(dir.join("ws/src/plain.rs"), plain.to_uppercase()).unwrap();
set_modified(
&dir.join("ws/src/plain.rs"),
hour_ago - Duration::from_secs(60),
);
run();
assert_eq!(
fs::read_to_string(copy.join("src/plain.rs")).unwrap(),
plain.to_uppercase()
);
assert!(modified(©.join("src/plain.rs")) > later);
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn work_copy_log_is_not_trusted() {
let dir = scratch("copy-log");
let (workspace, work) = (dir.join("ws"), dir.join("work"));
let copy = work.join("src");
let outside = dir.join("outside.txt");
fs::write(&outside, "keep").unwrap();
fs::write(workspace.join("src/a.rs"), "a").unwrap();
fs::write(
work.join(WRITTEN_LOG),
format!(
"../../outside.txt\n{}\n\nsrc/../../../outside.txt\nsrc/a.rs\n",
outside.display()
),
)
.unwrap();
let state = WorkCopy::open(&work, ©);
assert_eq!(
state.earlier,
[copy.join("src/a.rs")].into_iter().collect::<HashSet<_>>()
);
copy_tree(&workspace, ©, &workspace, &|_| false, &state).unwrap();
state.settle(&workspace).unwrap();
assert_eq!(fs::read_to_string(&outside).unwrap(), "keep");
assert_eq!(fs::read_to_string(copy.join("src/a.rs")).unwrap(), "a");
let state = WorkCopy::open(&work, ©);
assert!(state.write(&outside, "x").is_err());
assert!(state.write(©.join("src/a\nb.rs"), "x").is_err());
assert!(!copy.join("src/a\nb.rs").exists());
assert_eq!(fs::read_to_string(&outside).unwrap(), "keep");
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn work_copy_log_follows_every_write() {
let dir = scratch("copy-log-order");
let (workspace, work) = (dir.join("ws"), dir.join("work"));
let copy = work.join("src");
let log = work.join(WRITTEN_LOG);
let names = ["h", "c", "f", "a", "e", "b", "g", "d"].map(|n| format!("src/{n}.rs"));
for name in &names {
fs::write(workspace.join(name), "x").unwrap();
}
let state = copy_run(&dir, &[], false);
state.record(©.join(&names[0])).unwrap();
state.record(©.join(&names[0])).unwrap();
assert_eq!(fs::read_to_string(&log).unwrap(), "src/h.rs\n");
assert_eq!(fs::read_to_string(copy.join(&names[0])).unwrap(), "x");
for name in &names {
state.write(©.join(name), "probe").unwrap();
}
state.settle(&workspace).unwrap();
let mut sorted = names.to_vec();
sorted.sort();
assert_eq!(
fs::read_to_string(&log).unwrap(),
sorted.iter().map(|n| format!("{n}\n")).collect::<String>()
);
let state = copy_run(&dir, &[], false);
state.settle(&workspace).unwrap();
assert_eq!(fs::read_to_string(&log).unwrap(), "");
state.write(©.join(&names[3]), "probe").unwrap();
assert_eq!(fs::read_to_string(&log).unwrap(), "src/a.rs\n");
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn sync_copies_what_is_not_up_to_date_and_nothing_else() {
let dir = scratch("copy-sync");
let (workspace, work) = (dir.join("ws"), dir.join("work"));
let copy = work.join("src");
let hour_ago = std::time::SystemTime::now() - Duration::from_secs(3600);
for name in [
"same",
"longer",
"newer",
"was_dir",
"was_link",
"short_link",
"twin_link",
"shorter",
] {
fs::write(workspace.join("src").join(name), "source").unwrap();
set_modified(&workspace.join("src").join(name), hour_ago);
}
let locked = workspace.join("src/locked");
fs::write(&locked, "read only").unwrap();
let mut permissions = fs::metadata(&locked).unwrap().permissions();
permissions.set_readonly(true);
fs::set_permissions(&locked, permissions).unwrap();
fs::create_dir_all(copy.join("src/was_dir/inner")).unwrap();
fs::write(copy.join("src/same"), "SOURCE").unwrap();
fs::write(workspace.join("src/copied"), "as it is").unwrap();
fs::write(copy.join("src/copied"), "as it is").unwrap();
let long_ago = hour_ago - Duration::from_secs(7200);
set_modified(©.join("src/copied"), long_ago);
let elsewhere = dir.join("elsewhere");
fs::create_dir_all(&elsewhere).unwrap();
std::os::unix::fs::symlink(&elsewhere, copy.join("linked")).unwrap();
fs::create_dir_all(workspace.join("linked/deep")).unwrap();
fs::write(workspace.join("linked/deep/z"), "z").unwrap();
fs::write(copy.join("src/longer"), "SOURCE+").unwrap();
fs::write(copy.join("src/newer"), "SOURCE").unwrap();
set_modified(©.join("src/newer"), hour_ago - Duration::from_secs(60));
let outside = dir.join("outside");
fs::write(&outside, "keep").unwrap();
std::os::unix::fs::symlink(&outside, copy.join("src/was_link")).unwrap();
let twin = dir.join("twin");
fs::write(&twin, "source").unwrap();
std::os::unix::fs::symlink(&twin, copy.join("src/twin_link")).unwrap();
fs::write(copy.join("src/shorter"), "sour").unwrap();
std::os::unix::fs::symlink("abcdef", copy.join("src/short_link")).unwrap();
fs::create_dir_all(copy.join("old/deep")).unwrap();
fs::write(copy.join("old/deep/x"), "x").unwrap();
fs::create_dir_all(workspace.join("keep/deep")).unwrap();
fs::write(workspace.join("keep/deep/y"), "y").unwrap();
copy_run(&dir, &[], true);
let read = |name: &str| fs::read_to_string(copy.join(name)).unwrap();
assert_eq!(read("src/locked"), "read only");
assert_eq!(read("src/copied"), "as it is");
assert_eq!(
fs::metadata(copy.join("src/copied"))
.unwrap()
.modified()
.unwrap(),
long_ago
);
assert_eq!(read("linked/deep/z"), "z");
assert!(fs::symlink_metadata(copy.join("linked")).unwrap().is_dir());
assert_eq!(
fs::read_dir(&elsewhere).unwrap().count(),
0,
"nothing written through"
);
for name in [
"src/same",
"src/longer",
"src/newer",
"src/was_dir",
"src/was_link",
"src/short_link",
"src/twin_link",
"src/shorter",
] {
assert_eq!(read(name), "source", "{name}");
assert!(
fs::symlink_metadata(copy.join(name)).unwrap().is_file(),
"{name}"
);
}
assert!(
fs::symlink_metadata(copy.join("src/was_link"))
.unwrap()
.is_file()
);
assert_eq!(fs::read_to_string(&outside).unwrap(), "keep");
assert!(!copy.join("old").exists());
assert_eq!(read("keep/deep/y"), "y");
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn a_finding_keeps_its_number_when_the_one_before_it_is_closed() {
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";
let found = instrument::discover(source, 0).unwrap();
let all: Vec<(usize, usize, String)> = found
.sites
.iter()
.map(|site| {
let at = report::location("", site);
(at.line, at.column, at.code)
})
.collect();
let places = [FilePlaces {
display: "src/lib.rs",
source,
places: &all,
}];
let gap = |line: usize, column: usize, file: &str| Finding::InputGap {
at: report::Location {
file: file.to_string(),
line,
column,
code: "a > b".to_string(),
..report::Location::default()
},
survivors: vec![],
survivor_count: 0,
add_tests: vec![],
observed: None,
verified: true,
};
let name = |finding: &Finding| {
let at = finding.at();
(at.item.clone(), at.id.clone())
};
let mut findings = [
gap(4, 20, "src/lib.rs"),
gap(9, 5, "src/lib.rs"),
gap(9, 5, "src/other.rs"),
];
name_findings(&mut findings, &places);
assert_eq!(
name(&findings[0]),
(
"S::f".to_string(),
"input_gap|src/lib.rs|S::f|a > b|1".to_string()
)
);
assert_eq!(
name(&findings[1]),
(
"g".to_string(),
"input_gap|src/lib.rs|g|a > b|0".to_string()
)
);
assert_eq!(name(&findings[2]), (String::new(), String::new()));
}
#[test]
fn an_audit_takes_its_sample_evenly_and_the_same_every_time() {
assert_eq!(spread(0, 3), Vec::<usize>::new());
assert_eq!(spread(5, 0), Vec::<usize>::new());
assert_eq!(spread(3, 3), [0, 1, 2]);
assert_eq!(spread(3, 10), [0, 1, 2]);
assert_eq!(spread(10, 1), [0]);
assert_eq!(spread(10, 3), [0, 3, 6]);
assert_eq!(spread(10, 5), [0, 2, 4, 6, 8]);
assert_eq!(spread(4, 3), [0, 1, 2]);
assert_eq!(spread(7, 6), [0, 1, 2, 3, 4, 5]);
}
#[test]
fn a_mutant_of_the_source_is_the_mutation_its_probe_runs() {
assert_ne!(crate::tmt_rt::CANNOT_EVALUATE, 0);
let source = "fn f(a: i32, b: i32, ok: bool, k: Option<i32>, base: O) -> O { \
go(); \
let x = match k { Some(n) if n > 1 => !ok && a < b, _ => -a + b > 0 || ok }; \
for _ in a..b {} for _ in a..=b {} \
O { on: x, ..base } }";
let found = instrument::discover(source, 0).unwrap().sites;
let mut seen = BTreeSet::new();
for site in &found {
for mutant in instrument::source_mutants(site) {
let kind = format!("{:?}", site.kind);
let kind = kind.split([' ', '{', '(']).next().unwrap().to_string();
seen.insert((
kind,
mutant.into.clone(),
format!("{:?}", mutation_of(site, &mutant)),
));
}
}
let expected = [
("Arith", "*", "ArithSwap2"),
("Arith", "-", "ArithSwap"),
("Arm", "Some(n) if n > 1", "Delete"),
("Body", "Default::default()", "Delete"),
("Cmp", "<", "Op(Lt)"),
("Cmp", "<=", "Op(Le)"),
("Cmp", "==", "Op(Eq)"),
("Cmp", ">", "Op(Gt)"),
("Cmp", ">=", "Op(Ge)"),
("Field", "on", "Delete"),
("Guard", "true", "Const(true)"),
("Logic", "&&", "LogicSwap"),
("Logic", "||", "LogicSwap"),
("Neg", "", "Delete"),
("Not", "", "DropNot"),
("Range", "..", "RangeEnd"),
("Range", "..=", "RangeEnd"),
];
let like = |source: &str, into: &str| -> Vec<Mutation> {
let sites = instrument::discover(source, 0).unwrap().sites;
let site = sites
.iter()
.find(|site| matches!(site.kind, SiteKind::Cmp { .. }))
.unwrap();
let mutant = instrument::source_mutants(site)
.into_iter()
.find(|mutant| mutant.into == into)
.unwrap();
mutations_like(site, &mutant, true)
};
use plan::CmpOp::*;
for (op, into, expected) in [
("==", "!=", vec![Mutation::Op(Ne), Mutation::Negate]),
("!=", "==", vec![Mutation::Op(Eq), Mutation::Negate]),
("<=", ">", vec![Mutation::Op(Gt), Mutation::Negate]),
(">=", "<", vec![Mutation::Op(Lt), Mutation::Negate]),
("<", "<=", vec![Mutation::Op(Le), Mutation::Shift(1)]),
(">", ">=", vec![Mutation::Op(Ge), Mutation::Shift(-1)]),
("<", "==", vec![Mutation::Op(Eq)]),
("<", ">", vec![Mutation::Op(Gt)]),
(">", "==", vec![Mutation::Op(Eq)]),
(">", "<", vec![Mutation::Op(Lt)]),
] {
let source = format!("fn f(a: i32, b: i32) -> bool {{ a {op} b }}");
assert_eq!(like(&source, into), expected, "{op} as {into}");
}
let unordered = |op: &str, into: &str| -> Vec<Mutation> {
let source = format!("fn f(a: f64, b: f64) -> bool {{ a {op} b }}");
let sites = instrument::discover(&source, 0).unwrap().sites;
let site = sites
.iter()
.find(|site| matches!(site.kind, SiteKind::Cmp { .. }))
.unwrap();
let mutant = instrument::source_mutants(site)
.into_iter()
.find(|mutant| mutant.into == into)
.unwrap();
mutations_like(site, &mutant, false)
};
assert_eq!(unordered(">=", "<"), [Mutation::Op(Lt)]);
assert_eq!(unordered("<=", ">"), [Mutation::Op(Gt)]);
assert_eq!(unordered("==", "!="), [Mutation::Op(Ne), Mutation::Negate]);
for d in -3..=3 {
assert_eq!(
plan::eval_mutated_d(Lt, Mutation::Shift(1), d),
Le.eval_d(d)
);
assert_eq!(
plan::eval_mutated_d(Gt, Mutation::Shift(-1), d),
Ge.eval_d(d)
);
}
let seen: Vec<(&str, &str, &str)> = seen
.iter()
.map(|(kind, into, mutation)| (kind.as_str(), into.as_str(), mutation.as_str()))
.collect();
assert_eq!(seen, expected);
}
#[test]
fn the_mark_of_a_run_is_a_new_file_and_says_one_of_three_things() {
let dir = scratch("unable-mark");
fs::create_dir_all(&dir).unwrap();
let runs = std::sync::atomic::AtomicUsize::new(0);
let name = |n: usize| dir.join(format!("tmt-unable-{}-{n}", std::process::id()));
fs::write(name(0), "not ours").unwrap();
fs::write(name(1), "nor this").unwrap();
let mark = reserve_mark(&dir, &runs).unwrap();
assert_eq!(mark, name(2));
assert!(mark.is_absolute());
assert_eq!(fs::read_to_string(&mark).unwrap(), "");
assert_eq!(fs::read_to_string(name(0)).unwrap(), "not ours");
assert_eq!(fs::read_to_string(name(1)).unwrap(), "nor this");
assert!(!release_mark(&mark).unwrap());
assert!(!mark.exists());
let mark = reserve_mark(&dir, &runs).unwrap();
assert_eq!(mark, name(3));
fs::remove_file(&mark).unwrap();
assert!(release_mark(&mark).unwrap());
let in_the_way = dir.join("a-directory");
fs::create_dir_all(&in_the_way).unwrap();
let refused = format!("{:#}", release_mark(&in_the_way).unwrap_err());
assert!(refused.contains("cannot tell whether"), "{refused}");
assert!(refused.contains("a-directory"), "{refused}");
assert!(in_the_way.is_dir());
let unmade = format!("{:#}", reserve_mark(&name(0), &runs).unwrap_err());
assert!(unmade.contains("creating"), "{unmade}");
assert_eq!(fs::read_to_string(name(0)).unwrap(), "not ours");
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn the_directory_of_the_marks_is_made_or_used_and_nothing_is_removed_for_it() {
let dir = scratch("marks-dir");
let work = dir.join("work");
assert_eq!(marks_dir(&work).unwrap(), work.join("marks"));
assert!(work.join("marks").is_dir());
fs::write(work.join("marks/left-over"), "x").unwrap();
assert_eq!(marks_dir(&work).unwrap(), work.join("marks"));
assert_eq!(
fs::read_to_string(work.join("marks/left-over")).unwrap(),
"x"
);
let taken = dir.join("taken");
fs::create_dir_all(&taken).unwrap();
fs::write(taken.join("marks"), "grades of the class").unwrap();
let said = format!("{:#}", marks_dir(&taken).unwrap_err());
assert!(
said.contains("is in the way") && said.contains("marks"),
"{said}"
);
assert_eq!(
fs::read_to_string(taken.join("marks")).unwrap(),
"grades of the class"
);
#[cfg(unix)]
{
let linked = dir.join("linked");
let elsewhere = dir.join("elsewhere");
fs::create_dir_all(&linked).unwrap();
fs::create_dir_all(&elsewhere).unwrap();
std::os::unix::fs::symlink(&elsewhere, linked.join("marks")).unwrap();
assert!(marks_dir(&linked).is_err());
assert!(
fs::symlink_metadata(linked.join("marks"))
.unwrap()
.is_symlink()
);
assert_eq!(fs::read_dir(&elsewhere).unwrap().count(), 0);
}
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn concurrent_runs_share_the_cores() {
assert_eq!(test_threads(16, 1), 16);
assert_eq!(test_threads(16, 4), 4);
assert_eq!(test_threads(18, 4), 4);
assert_eq!(test_threads(16, 8), 2);
assert_eq!(test_threads(16, 9), 2);
assert_eq!(test_threads(4, 16), 2);
assert_eq!(test_threads(1, 1), 2);
assert_eq!(test_threads(8, 0), 8);
}
#[test]
fn cargo_is_told_the_same_everywhere() {
assert!(CargoConfig::default().flags().is_empty());
let some = CargoConfig {
features: vec!["a".to_string(), "dep/b".to_string()],
no_default_features: true,
..CargoConfig::default()
};
assert_eq!(
some.flags(),
["--features", "a,dep/b", "--no-default-features"]
);
let all = CargoConfig {
all_features: true,
locked: true,
..CargoConfig::default()
};
assert_eq!(all.flags(), ["--all-features", "--locked"]);
}
#[test]
fn source_mutants_are_described_like_the_others() {
let source = "fn f(a: i32, b: i32, k: Option<i32>) -> bool { \
match k { Some(n) if n > 1 => !(a < b) || a + b == 0, _ => -a * b > 1 } }";
let found = instrument::discover(source, 0).unwrap().sites;
let described: Vec<String> = found
.iter()
.flat_map(|site| {
instrument::source_mutants(site)
.into_iter()
.map(|mutant| report::describe(site, mutation_of(site, &mutant)))
})
.collect();
assert_eq!(
described,
[
"the body of `f` replaced by `true`",
"the body of `f` replaced by `false`",
"remove the arm `Some(n) if n > 1 => ..`",
"the guard `n > 1` replaced by `true`",
"`n == 1`",
"`n < 1`",
"`n >= 1`",
"`!(a < b) && a + b == 0`",
"`(a < b)`",
"`a == b`",
"`a > b`",
"`a <= b`",
"`a + b != 0`",
"`a - b`",
"`a * b`",
"`-a * b == 1`",
"`-a * b < 1`",
"`-a * b >= 1`",
"`-a / b`",
"`-a + b`",
"`a`",
]
);
let source = "fn f(k: K) -> u8 { match k { K::A(n) if n > 1 => 1, K::A(_) => 2 } }";
let found = instrument::discover(source, 0).unwrap().sites;
let guard = found
.iter()
.find(|s| matches!(s.kind, SiteKind::Guard { .. }))
.unwrap();
let described: Vec<String> = instrument::source_mutants(guard)
.iter()
.map(|mutant| report::describe(guard, mutation_of(guard, mutant)))
.collect();
assert_eq!(
described,
[
"the guard `n > 1` replaced by `true`",
"the guard `n > 1` replaced by `false`"
]
);
}
}