1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
use schemars::JsonSchema;
use serde::{Deserialize, Deserializer, Serialize};
/// The test runner of `fallow mutation`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum MutationRunner {
/// Detect the runner from the project: the `vitest` dependency, the
/// test module that the test files import, a Bun file at the root, or a
/// `node --test` script.
#[default]
Auto,
/// Vitest 4.1 to 5 from the project `node_modules`.
Vitest,
/// `node:test` of Node.js 22.18 or later. Each test file runs in its own
/// Node process.
NodeTest,
/// `bun test` of Bun 1.4 or later. Each test file runs in its own Bun
/// process.
BunTest,
}
/// A mutation operator name, kebab-case.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum MutationOperatorName {
/// `a + b` to `a - b`, and the other arithmetic pairs.
ArithmeticOperator,
/// `a < b` to `a <= b`, and the other relational pairs.
RelationalOperator,
/// `a && b` to `a || b`, and the reverse.
LogicalOperator,
/// A condition to its negation.
NegateCondition,
/// A unary operator removed or changed.
UnaryOperator,
/// `i++` to `i--`, and the reverse.
UpdateOperator,
/// A call statement removed.
RemovedCall,
/// A return value changed.
ReturnValue,
/// `true` to `false`, and the reverse.
BooleanLiteral,
/// A string or template literal emptied or filled.
StringLiteral,
/// `a?.b` to `a.b`.
OptionalChaining,
/// One token of a regular expression literal changed: an anchor or a
/// quantifier removed, a `{n,m}` range shortened to `{n}`, a character
/// class negated, or a class escape with the opposite case.
RegexLiteral,
/// `z.number().int()` to `z.number()` in a module-level `const`
/// initializer: one call link of a fluent chain removed.
RemovedChainLink,
/// Opt-in. The statements of a block or function body removed.
BlockStatement,
/// Opt-in. `[x]` to `[]`, and `[]` to `["fallow"]`.
ArrayLiteral,
/// Opt-in. A non-empty object literal to `{}`.
ObjectLiteral,
/// Opt-in. `startsWith` to `endsWith` and the other method pairs, or
/// `s.trim()` to `s`.
MethodExpression,
/// Opt-in. The statements of a `case` clause removed.
SwitchCase,
/// Opt-in. A call in an expression position to `void 0`.
CallExpression,
/// Opt-in. A `throw new X(...)` statement removed.
ThrowStatement,
/// Opt-in. The regex changes applied to a `new RegExp("...")` pattern.
RegexConstructor,
/// Opt-in. A lookaround negated, or `\b` and `\B` swapped.
RegexAssertion,
/// Opt-in. `a ?? b` to `a`.
NullishFallback,
}
impl MutationOperatorName {
/// The kebab-case name.
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::ArithmeticOperator => "arithmetic-operator",
Self::RelationalOperator => "relational-operator",
Self::LogicalOperator => "logical-operator",
Self::NegateCondition => "negate-condition",
Self::UnaryOperator => "unary-operator",
Self::UpdateOperator => "update-operator",
Self::RemovedCall => "removed-call",
Self::ReturnValue => "return-value",
Self::BooleanLiteral => "boolean-literal",
Self::StringLiteral => "string-literal",
Self::OptionalChaining => "optional-chaining",
Self::RegexLiteral => "regex-literal",
Self::RemovedChainLink => "removed-chain-link",
Self::BlockStatement => "block-statement",
Self::ArrayLiteral => "array-literal",
Self::ObjectLiteral => "object-literal",
Self::MethodExpression => "method-expression",
Self::SwitchCase => "switch-case",
Self::CallExpression => "call-expression",
Self::ThrowStatement => "throw-statement",
Self::RegexConstructor => "regex-constructor",
Self::RegexAssertion => "regex-assertion",
Self::NullishFallback => "nullish-fallback",
}
}
}
fn deserialize_min_score<'de, D>(deserializer: D) -> Result<Option<f64>, D::Error>
where
D: Deserializer<'de>,
{
let value = Option::<f64>::deserialize(deserializer)?;
if let Some(score) = value
&& (!score.is_finite() || !(0.0..=100.0).contains(&score))
{
return Err(serde::de::Error::custom(format!(
"mutation.minScore must be between 0 and 100 (got {score})"
)));
}
Ok(value)
}
fn deserialize_concurrency<'de, D>(deserializer: D) -> Result<Option<usize>, D::Error>
where
D: Deserializer<'de>,
{
let value = Option::<usize>::deserialize(deserializer)?;
if value == Some(0) {
return Err(serde::de::Error::custom(
"mutation.concurrency must be at least 1",
));
}
Ok(value)
}
fn deserialize_mutants_per_line<'de, D>(deserializer: D) -> Result<Option<usize>, D::Error>
where
D: Deserializer<'de>,
{
let value = Option::<usize>::deserialize(deserializer)?;
if value == Some(0) {
return Err(serde::de::Error::custom(
"mutation.mutantsPerLine must be at least 1",
));
}
Ok(value)
}
/// Project settings for `fallow mutation`.
///
/// Project config cannot widen what a run executes: the override that keeps
/// mutants near file system, process, network or database sinks is a CLI
/// flag only (`--allow-side-effects`), and no key starts a run.
#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct MutationConfig {
/// The test runner: `auto`, `vitest`, `node-test` or `bun-test`. `auto`
/// detects it from the project.
#[serde(default)]
pub runner: MutationRunner,
/// The operators to use. Unset uses the default set. An opt-in operator
/// runs only when this list or `--operators` names it. `--operators`
/// wins.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operators: Option<Vec<MutationOperatorName>>,
/// The minimum mutation score, from 0 to 100. When the score of a run is
/// lower, `fallow mutation` exits with code 1. Unset never fails a run.
/// `--min-score` wins.
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "deserialize_min_score"
)]
#[schemars(range(min = 0.0, max = 100.0))]
pub min_score: Option<f64>,
/// The number of mutation runner processes. Unset uses half the logical cores.
/// `--concurrency` wins.
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "deserialize_concurrency"
)]
#[schemars(range(min = 1))]
pub concurrency: Option<usize>,
/// The maximum number of mutants on one source line. The plan keeps the
/// most productive mutants of the line (relational, condition,
/// arithmetic and logical operators first). The others are `pending`
/// with the reason `sampled-out`. Unset keeps each mutant.
/// `--mutants-per-line` wins.
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "deserialize_mutants_per_line"
)]
#[schemars(range(min = 1))]
pub mutants_per_line: Option<usize>,
/// Widen each changed line to the whole function that holds it, so that a
/// change to a parameter or a signature selects the mutants of the
/// function. Only the changed-code scope uses it. Unset or `false` mutates
/// the changed lines only. `--function-scope` turns it on.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub function_scope: Option<bool>,
/// Type-check each survived mutant through the type-aware companion
/// of `--type-aware`. A survivor that does not type-check becomes
/// `compile_error` and does not count in the score. A survivor that
/// removes an optional-chaining link or a nullish fallback from a
/// receiver whose type excludes `null` and `undefined` gets an advisory
/// `equivalence_hint`. Its status
/// and the score do not change. Unset or `false` checks no survivor.
/// `--typecheck` turns the check on.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub typecheck: Option<bool>,
/// The config file of the test runner, relative to the project root, for
/// example `vitest.integration.config.mjs`. The file must exist inside
/// the project root. Only the Vitest runner reads it. Unset uses the
/// default config discovery of the runner. `--runner-config` wins.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub runner_config: Option<String>,
/// The names of the Vitest projects that the run uses, as the Vitest
/// `--project` flag selects them, for example `["unit"]`. A name can
/// hold a `*` wildcard. The run then ignores each other project of the
/// config, also a project from a separate config file. Only the Vitest
/// runner reads it. Unset uses each project. `--runner-project` wins.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub runner_projects: Option<Vec<String>>,
}
impl MutationConfig {
/// True when no key is set.
#[must_use]
pub fn is_default(&self) -> bool {
*self == Self::default()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn parse(json: &str) -> Result<MutationConfig, String> {
serde_json::from_str::<MutationConfig>(json).map_err(|error| error.to_string())
}
#[test]
fn every_key_parses_in_camel_case() {
let config = parse(
r#"{"runner":"vitest","operators":["arithmetic-operator","removed-call"],
"minScore":80,"concurrency":4,"mutantsPerLine":2,"functionScope":true,"typecheck":true,
"runnerConfig":"vitest.integration.config.mjs","runnerProjects":["unit"]}"#,
)
.expect("valid config");
assert_eq!(config.runner, MutationRunner::Vitest);
assert_eq!(
config.operators,
Some(vec![
MutationOperatorName::ArithmeticOperator,
MutationOperatorName::RemovedCall
])
);
assert_eq!(config.min_score, Some(80.0));
assert_eq!(config.concurrency, Some(4));
assert_eq!(config.mutants_per_line, Some(2));
assert_eq!(config.function_scope, Some(true));
assert_eq!(config.typecheck, Some(true));
assert_eq!(
config.runner_config.as_deref(),
Some("vitest.integration.config.mjs")
);
assert_eq!(config.runner_projects, Some(vec!["unit".to_owned()]));
}
#[test]
fn the_runner_names_node_test_and_bun_test() {
let node = parse(r#"{"runner":"node-test"}"#).expect("node-test");
assert_eq!(node.runner, MutationRunner::NodeTest);
let bun = parse(r#"{"runner":"bun-test"}"#).expect("bun-test");
assert_eq!(bun.runner, MutationRunner::BunTest);
assert!(parse(r#"{"runner":"jest"}"#).is_err());
}
#[test]
fn an_empty_section_is_the_default() {
let config = parse("{}").expect("empty section");
assert!(config.is_default());
assert_eq!(config.runner, MutationRunner::Auto);
assert!(!parse(r#"{"minScore":10}"#).expect("set").is_default());
}
#[test]
fn side_effect_override_is_not_a_config_key() {
let error = parse(r#"{"allowSideEffects":true}"#).expect_err("flag only");
assert!(error.contains("allowSideEffects"), "{error}");
}
#[test]
fn keys_that_the_run_does_not_apply_are_rejected() {
for key in ["include", "exclude", "timeoutFactor", "timeoutMs"] {
let json = if key.starts_with("timeout") {
format!(r#"{{"{key}":2}}"#)
} else {
format!(r#"{{"{key}":["src/**"]}}"#)
};
let error = parse(&json).expect_err(&json);
assert!(error.contains("unknown field"), "{json}: {error}");
}
}
#[test]
fn out_of_range_values_fail_loud() {
for (json, needle) in [
(r#"{"minScore":101}"#, "between 0 and 100"),
(r#"{"minScore":-1}"#, "between 0 and 100"),
(r#"{"concurrency":0}"#, "concurrency must be at least 1"),
(
r#"{"mutantsPerLine":0}"#,
"mutantsPerLine must be at least 1",
),
(r#"{"runner":"jest"}"#, "unknown variant"),
(r#"{"operators":["bogus"]}"#, "unknown variant"),
] {
let error = parse(json).expect_err(json);
assert!(error.contains(needle), "{json}: {error}");
}
assert_eq!(
parse(r#"{"minScore":0}"#).expect("zero").min_score,
Some(0.0)
);
assert_eq!(
parse(r#"{"minScore":100}"#).expect("max").min_score,
Some(100.0)
);
}
#[test]
fn operator_names_round_trip_through_serde() {
for name in [
MutationOperatorName::ArithmeticOperator,
MutationOperatorName::RelationalOperator,
MutationOperatorName::LogicalOperator,
MutationOperatorName::NegateCondition,
MutationOperatorName::UnaryOperator,
MutationOperatorName::UpdateOperator,
MutationOperatorName::RemovedCall,
MutationOperatorName::ReturnValue,
MutationOperatorName::BooleanLiteral,
MutationOperatorName::StringLiteral,
MutationOperatorName::OptionalChaining,
MutationOperatorName::NullishFallback,
] {
let json = serde_json::to_value(name).expect("serializes");
assert_eq!(json, serde_json::Value::String(name.as_str().to_owned()));
}
}
}