use super::*;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedTarget {
pub target: String,
pub test_ids: Vec<String>,
pub unmatched: Option<Unmatched>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Unmatched {
NotATestFile,
NoPlannedCode,
NoTest,
}
impl Unmatched {
pub const fn reason(self) -> Option<&'static str> {
match self {
Self::NotATestFile => Some("not-a-test-file"),
Self::NoPlannedCode => Some("no-planned-code"),
Self::NoTest => None,
}
}
const fn describe(self) -> &'static str {
match self {
Self::NotATestFile => "the runner does not list the file as a test file",
Self::NoPlannedCode => {
"the file reaches no planned code, so the dry run does not run it"
}
Self::NoTest => "no test of the dry run has this id",
}
}
}
#[derive(Clone, Copy)]
pub(super) struct TargetFiles<'a> {
runner: &'a [String],
dry: &'a [String],
}
impl<'a> TargetFiles<'a> {
pub(super) const fn new(runner: &'a [String], dry: &'a [String]) -> Self {
Self { runner, dry }
}
fn unmatched(self, target: &str) -> Option<Unmatched> {
let names = |files: &[String]| files.iter().any(|file| names_file(target, file));
if names(self.dry) {
None
} else if names(self.runner) {
Some(Unmatched::NoPlannedCode)
} else {
Some(Unmatched::NotATestFile)
}
}
}
fn names_file(target: &str, file: &str) -> bool {
target
.strip_prefix(file)
.is_some_and(|rest| rest.is_empty() || rest.starts_with("::"))
}
pub(super) fn check_targets(
config: &ScheduleConfig,
caps: Capabilities,
files: TargetFiles<'_>,
) -> Result<(), ScheduleError> {
if config.targets.is_empty() {
return Ok(());
}
if !caps.test_filter {
return Err(ScheduleError::TargetsNeedTestFilter);
}
let unmatched: Option<Vec<ResolvedTarget>> = config
.targets
.iter()
.map(|target| {
files.unmatched(target).map(|reason| ResolvedTarget {
target: target.clone(),
test_ids: Vec::new(),
unmatched: Some(reason),
})
})
.collect();
match unmatched {
Some(unmatched) => Err(ScheduleError::UnmatchedTargets(unmatched)),
None => Ok(()),
}
}
pub(super) fn unmatched_message(targets: &[ResolvedTarget]) -> String {
let named: Vec<String> = targets
.iter()
.map(|target| {
let reason = target.unmatched.unwrap_or(Unmatched::NoTest).describe();
format!("{} ({reason})", target.target)
})
.collect();
format!(
"no --kill-matrix-for target selects a test of the dry run: {}; the dry run runs the test files that reach the planned code",
named.join(", ")
)
}
impl Worker<'_> {
pub(super) fn attempt_targets(
&mut self,
job: &Job,
caps: Capabilities,
) -> Result<Attempt, ScheduleError> {
let targets = Job {
tests: job.targets.clone(),
..job.clone()
};
let first = self.attempt_tests(&targets, caps, false)?;
if first.status == MutantStatus::Survived && !self.config.target_full {
return Ok(Attempt {
status: MutantStatus::NotKilledByTarget,
..first
});
}
let terminal = match first.status {
MutantStatus::Killed => first.kill_matrix_complete,
MutantStatus::Survived => true,
_ => false,
};
let others: Vec<String> = job
.tests
.iter()
.filter(|test| !job.targets.contains(test))
.cloned()
.collect();
if !terminal || others.is_empty() {
return Ok(first);
}
let others = Job {
tests: others,
..job.clone()
};
let second = self.attempt_tests(&others, caps, true)?;
let target_kill = first.status == MutantStatus::Killed;
let mut merged = merge_target_phases(first, second);
let other_killer = merged
.killing_tests
.iter()
.any(|test| !job.targets.contains(test));
if target_kill && merged.kill_matrix_complete {
merged.kill_matrix_complete = self.passes_without_mutant(&targets, caps)?
&& (!other_killer || self.passes_without_mutant(&others, caps)?);
}
Ok(merged)
}
fn passes_without_mutant(
&mut self,
job: &Job,
caps: Capabilities,
) -> Result<bool, ScheduleError> {
let tests: Vec<String> = job
.tests
.iter()
.filter(|test| !self.memo.is_failed(test))
.cloned()
.collect();
if tests.len() != job.tests.len() {
return Ok(false);
}
Ok(matches!(
self.check_control(&tests, job, caps)?,
ControlCheck::Passed
))
}
}
fn merge_target_phases(targets: Attempt, others: Attempt) -> Attempt {
let duration_ms = match (targets.duration_ms, others.duration_ms) {
(Some(first), Some(second)) => Some(first.saturating_add(second)),
(first, second) => first.or(second),
};
let mut dropped_tests = targets.dropped_tests;
dropped_tests.extend(others.dropped_tests.iter().cloned());
dropped_tests.sort();
dropped_tests.dedup();
let other_killer = (others.status == MutantStatus::Killed)
.then(|| others.killed_by.clone())
.flatten();
if others.status == MutantStatus::NoCoverage {
return Attempt {
kill_matrix_complete: targets.kill_matrix_complete && dropped_tests.is_empty(),
dropped_tests,
..targets
};
}
if targets.status != MutantStatus::Killed {
return Attempt {
killing_tests: other_killer.into_iter().collect(),
kill_matrix_complete: targets.kill_matrix_complete && dropped_tests.is_empty(),
duration_ms,
dropped_tests,
..others
};
}
let others_terminal = match others.status {
MutantStatus::Killed => other_killer.is_some(),
MutantStatus::Survived => true,
_ => false,
};
let mut killing_tests = targets.killing_tests;
killing_tests.extend(other_killer);
killing_tests.sort();
killing_tests.dedup();
Attempt {
killing_tests,
kill_matrix_complete: targets.kill_matrix_complete
&& others_terminal
&& dropped_tests.is_empty(),
duration_ms,
dropped_tests,
issue: targets.issue.or(others.issue),
..targets
}
}
pub(super) fn retries_unique_kill(config: &ScheduleConfig, job: &Job, attempt: &Attempt) -> bool {
!config.target_full
&& attempt.status == MutantStatus::Killed
&& attempt.kill_matrix_complete
&& matches!(attempt.killing_tests.as_slice(), [test] if job.targets.contains(test))
}
pub(super) fn job_targets(context: &JobContext<'_>, tests: &[String]) -> Vec<String> {
context.targets.map_or_else(Vec::new, |targets| {
tests
.iter()
.filter(|test| targets.contains(*test))
.cloned()
.collect()
})
}
pub(super) fn config_targets(
config: &ScheduleConfig,
dry: &DryRunResult,
caps: Capabilities,
files: TargetFiles<'_>,
outcome: &mut ScheduleOutcome,
) -> Result<Option<FxHashSet<String>>, ScheduleError> {
if config.targets.is_empty() {
return Ok(None);
}
let (targets, _) = resolve_targets(&config.targets, &dry.tests, caps)?;
let (mut targets, ids) = without_duplicate_ids(targets, &reported_duplicates(dry))?;
for target in targets
.iter_mut()
.filter(|target| target.test_ids.is_empty())
{
target.unmatched = Some(files.unmatched(&target.target).unwrap_or(Unmatched::NoTest));
}
if ids.is_empty() {
return Err(ScheduleError::UnmatchedTargets(targets));
}
outcome.targets = targets;
Ok(Some(ids))
}
pub(super) fn duplicate_message(ids: &[String]) -> String {
format!(
"these --kill-matrix-for targets name a duplicate test id: {}; the runner numbers tests that share a title in report order, so the kill evidence of these tests is not reliable; give each test a unique title",
ids.join(", ")
)
}
fn without_duplicate_ids(
targets: Vec<ResolvedTarget>,
duplicate_ids: &[String],
) -> Result<(Vec<ResolvedTarget>, FxHashSet<String>), ScheduleError> {
let duplicates: FxHashSet<&String> = duplicate_ids.iter().collect();
let named: Vec<String> = targets
.iter()
.filter(|target| duplicates.contains(&target.target))
.map(|target| target.target.clone())
.collect();
if !named.is_empty() {
return Err(ScheduleError::DuplicateTargetTestIds(named));
}
let mut ids = FxHashSet::default();
let mut kept = Vec::with_capacity(targets.len());
for mut target in targets {
target.test_ids.retain(|id| !duplicates.contains(id));
ids.extend(target.test_ids.iter().cloned());
kept.push(target);
}
Ok((kept, ids))
}
pub(super) fn resolve_targets(
targets: &[String],
tests: &[DryTest],
caps: Capabilities,
) -> Result<(Vec<ResolvedTarget>, FxHashSet<String>), ScheduleError> {
if !caps.test_filter {
return Err(ScheduleError::TargetsNeedTestFilter);
}
let mut resolved = Vec::with_capacity(targets.len());
let mut ids = FxHashSet::default();
for target in targets {
let mut test_ids: Vec<String> = tests
.iter()
.filter(|test| test.test_id == *target || test.file == *target)
.map(|test| test.test_id.clone())
.collect();
test_ids.sort();
test_ids.dedup();
ids.extend(test_ids.iter().cloned());
resolved.push(ResolvedTarget {
target: target.clone(),
test_ids,
unmatched: None,
});
}
Ok((resolved, ids))
}
pub(super) fn confirmed_kill(
first: &MutantOutcome,
status: MutantStatus,
retry: Attempt,
) -> (MutantStatus, Attempt) {
let killers = |tests: &[String]| -> BTreeSet<String> { tests.iter().cloned().collect() };
let same_killers = killers(&first.killing_tests) == killers(&retry.killing_tests);
if status != MutantStatus::Killed || !same_killers {
let status = if status == MutantStatus::Killed {
MutantStatus::Flaky
} else {
status
};
return (
status,
Attempt {
kill_matrix_complete: false,
..retry
},
);
}
(
status,
Attempt {
kill_matrix_complete: first.kill_matrix_complete && retry.kill_matrix_complete,
..retry
},
)
}