#![allow(
dead_code,
reason = "each test binary uses a different subset of the helpers"
)]
use fallow_mutation::{Instrumented, Mutant, MutationOptions, Operator, SourceKind, instrument};
use oxc_allocator::Allocator;
use oxc_parser::{ParseOptions, Parser};
use oxc_semantic::SemanticBuilder;
pub fn assert_valid(code: &str, kind: SourceKind) {
let allocator = Allocator::default();
let options = ParseOptions {
parse_regular_expression: true,
..ParseOptions::default()
};
let parsed = Parser::new(&allocator, code, kind.source_type())
.with_options(options)
.parse();
assert!(
!parsed.fatal_error && !parsed.diagnostics.has_errors(),
"code does not parse: {:?}\n---\n{code}",
parsed.diagnostics,
);
let semantic = SemanticBuilder::new()
.with_check_syntax_error(true)
.build(&parsed.program);
assert!(
!semantic.diagnostics.has_errors(),
"code has syntax errors: {:?}\n---\n{code}",
semantic.diagnostics,
);
}
pub fn apply(source: &str, mutant: &Mutant) -> String {
let (start, end) = (mutant.span.0 as usize, mutant.span.1 as usize);
format!(
"{}{}{}",
&source[..start],
mutant.replacement,
&source[end..]
)
}
pub fn run_with(source: &str, kind: SourceKind, options: &MutationOptions) -> Instrumented {
let result = match instrument(source, "src/fixture.ts", kind, options) {
Ok(result) => result,
Err(error) => panic!("instrument failed: {error}"),
};
assert_valid(&result.code, kind);
for mutant in &result.mutants {
assert_eq!(
&source[mutant.span.0 as usize..mutant.span.1 as usize],
mutant.original
);
assert_valid(&apply(source, mutant), kind);
}
result
}
pub fn run(source: &str, kind: SourceKind) -> Instrumented {
run_with(source, kind, &MutationOptions::default())
}
pub fn pairs(result: &Instrumented, operator: Operator) -> Vec<(String, String)> {
let mut pairs: Vec<(String, String)> = result
.mutants
.iter()
.filter(|mutant| mutant.operator == operator)
.map(|mutant| (mutant.original.clone(), mutant.replacement.clone()))
.collect();
pairs.sort();
pairs
}
pub fn expected(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
let mut owned: Vec<(String, String)> = pairs
.iter()
.map(|(a, b)| ((*a).to_owned(), (*b).to_owned()))
.collect();
owned.sort();
owned
}
pub fn assert_only_in_control(source: &str, kind: SourceKind, control: &str) {
let start = match source.find(control) {
Some(start) => start as u32,
None => panic!("control {control:?} is not in the source"),
};
let end = start + control.len() as u32;
let result = run(source, kind);
assert!(
!result.mutants.is_empty(),
"the control {control:?} gave no mutant"
);
for mutant in &result.mutants {
assert!(
mutant.span.0 >= start && mutant.span.1 <= end,
"mutant outside the control: {} {:?} -> {:?}",
mutant.operator,
mutant.original,
mutant.replacement,
);
}
}
const NODE_SETUP: &str = r#"const active = process.env.FALLOW_TEST_ACTIVE;
if (active) {
globalThis.__fallowMutation = { a: (id) => id === active, c: () => {} };
}
const normalize = (message) => String(message)
.replace(/^.+? (is not (?:a function|a constructor|iterable|async iterable|an object|a function or its return value is not (?:async )?iterable))/, "<expr> $1")
.replace(/ of '.*' as it is/, " of <expr> as it is");
const report = (error) => {
const name = error && error.name;
const message = normalize(error && error.message);
process.stdout.write(`uncaught ${name}: ${message}\n`);
process.exit(1);
};
process.on("uncaughtException", report);
process.on("unhandledRejection", report);
"#;
fn node_setup() -> Option<&'static std::path::Path> {
static SETUP: std::sync::OnceLock<Option<std::path::PathBuf>> = std::sync::OnceLock::new();
SETUP
.get_or_init(|| {
let path = std::env::temp_dir().join(format!(
"fallow-mutation-node-setup-{}.cjs",
std::process::id()
));
std::fs::write(&path, NODE_SETUP).ok()?;
Some(path)
})
.as_deref()
}
fn run_node_with(code: &str, active: Option<&str>) -> Option<(String, Option<i32>)> {
use std::io::Write;
use std::process::{Command, Stdio};
let mut command = Command::new("node");
command
.arg("--require")
.arg(node_setup()?)
.args(["--input-type=commonjs", "-"])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null());
match active {
Some(id) => command.env("FALLOW_TEST_ACTIVE", id),
None => command.env_remove("FALLOW_TEST_ACTIVE"),
};
let mut child = command.spawn().ok()?;
child.stdin.take()?.write_all(code.as_bytes()).ok()?;
let output = child.wait_with_output().ok()?;
Some((
String::from_utf8_lossy(&output.stdout).into_owned(),
output.status.code(),
))
}
pub fn run_node(code: &str) -> Option<(String, Option<i32>)> {
run_node_with(code, None)
}
pub fn run_node_active(code: &str, id: &str) -> Option<(String, Option<i32>)> {
run_node_with(code, Some(id))
}
pub fn assert_runs_like_each_mutant(source: &str, options: &MutationOptions) -> usize {
let Some(original) = run_node(source) else {
return 0;
};
assert_eq!(original.1, Some(0), "the fixture fails: {original:?}");
let result = run_with(source, SourceKind::Js, options);
assert_eq!(
run_node(&result.code),
Some(original),
"the inactive instrumented code differs\n---\n{}",
result.code
);
for mutant in &result.mutants {
let mutated = run_node(&apply(source, mutant));
let switched = run_node_active(&result.code, mutant.id.as_str());
assert_eq!(
switched, mutated,
"{} {:?} -> {:?}",
mutant.operator, mutant.original, mutant.replacement
);
}
result.mutants.len()
}