testing_conventions/lib.rs
1pub mod agents;
2pub mod co_change;
3pub mod colocated_test;
4pub mod config;
5pub mod coverage;
6pub mod e2e;
7pub mod isolation;
8pub mod lint;
9pub mod mutation;
10pub mod packaging;
11pub mod patch_coverage;
12pub mod ts;
13pub mod violation;
14pub mod workflow;
15
16use std::path::{Path, PathBuf};
17
18use clap::{CommandFactory, Parser, Subcommand};
19
20#[derive(Parser, Debug)]
21#[command(
22 name = "testing-conventions",
23 version,
24 about = "Enforce testing conventions in libraries (Python, TypeScript, and Rust).",
25 long_about = None,
26)]
27pub struct Cli {
28 #[command(subcommand)]
29 command: Option<Command>,
30}
31
32#[derive(Subcommand, Debug)]
33enum Command {
34 /// Check the repository against its testing-conventions config.
35 Check,
36 /// Write the testing contract into the repository's agent context file
37 /// (#232): a marker-delimited, hash-versioned block in `AGENTS.md` that a
38 /// coding agent reads before writing code. Idempotent — re-running
39 /// refreshes the owned region and touches nothing outside it.
40 Install {
41 /// The agent context file to manage.
42 #[arg(default_value = "AGENTS.md")]
43 path: PathBuf,
44 },
45 /// Unit-test conventions.
46 Unit {
47 #[command(subcommand)]
48 rule: UnitRule,
49 },
50 /// Integration-test conventions.
51 Integration {
52 #[command(subcommand)]
53 rule: IntegrationRule,
54 },
55 /// Packaging conventions: test files must not ship in the built artifact.
56 Packaging {
57 /// Root of the built artifact to inspect (e.g. an unpacked wheel or `dist/`).
58 path: PathBuf,
59 /// Language convention to enforce (required).
60 #[arg(long, value_enum)]
61 language: colocated_test::Language,
62 },
63 /// Workflow guard (private — hidden from `--help`, #191): every `testing-conventions`
64 /// invocation in a CI workflow must name a subcommand this binary still exposes
65 /// (guards the `@v0` path, #92). Run from our own CI, not a documented consumer command;
66 /// it stays in the binary because the guard needs the in-process command tree.
67 #[command(hide = true)]
68 Workflow {
69 /// Workflow file (or a directory of them) to scan.
70 path: PathBuf,
71 },
72 /// End-to-end-test conventions.
73 E2e {
74 #[command(subcommand)]
75 command: E2eCommand,
76 },
77}
78
79/// Rules enforced on the unit-test suite (the README's "Unit" taxonomy).
80#[derive(Subcommand, Debug)]
81enum UnitRule {
82 /// Check that every source file has a colocated, matching-named unit test
83 /// (tree-wide presence). With `--base`, additionally run the commit-scoped
84 /// `co-change` check over `<base>...HEAD` (#33): a modified or deleted source
85 /// whose colocated test is not in the diff fails. Presence always runs;
86 /// `--base` *adds* the diff-scoped check.
87 ColocatedTest {
88 /// Directory to scan recursively.
89 path: PathBuf,
90 /// Language convention to enforce (required).
91 #[arg(long, value_enum)]
92 language: colocated_test::Language,
93 /// Opt-in commit-scoped co-change check (#33): diff `<base>...HEAD` and
94 /// also flag a modified or deleted source whose colocated test didn't
95 /// co-change. Absent means presence-only — there is no default. Python /
96 /// TypeScript only: `--base --language rust` is rejected (inline
97 /// `#[cfg(test)]` units have no sibling test to go stale).
98 #[arg(long)]
99 base: Option<String>,
100 /// testing-conventions config file providing the `exempt` list. Optional:
101 /// if the file is absent, no files are exempt.
102 #[arg(long, default_value = "testing-conventions.toml")]
103 config: PathBuf,
104 },
105 /// Check that the unit suite meets the configured coverage floor. With
106 /// `--base`, the same configured floor is measured over the `<base>...HEAD`
107 /// diff (the changed lines) instead of the whole tree (#162) — a changed line
108 /// below the floor fails, no matter how small the diff.
109 Coverage {
110 /// Directory whose unit suite is run and measured.
111 path: PathBuf,
112 /// Language convention to enforce (required).
113 #[arg(long, value_enum)]
114 language: colocated_test::Language,
115 /// Opt-in diff-scoped coverage (#162): diff `<base>...HEAD` and measure the
116 /// configured floor over only the changed lines, instead of the whole tree.
117 /// Absent means whole-tree — there is no default. This is the patch-scoped
118 /// check the old `unit patch-coverage` command did, re-homed onto the floor
119 /// it shares.
120 #[arg(long)]
121 base: Option<String>,
122 /// testing-conventions config file with the coverage thresholds and
123 /// `exempt` list. Optional: if the file — or its `[<language>].coverage`
124 /// table — is absent, the language's sane default floor is used and
125 /// nothing is exempt.
126 #[arg(long, default_value = "testing-conventions.toml")]
127 config: PathBuf,
128 },
129 /// Lint unit test files for isolation: mock every collaborator (Python, TypeScript, Rust).
130 Lint {
131 /// Crate root / source dir to scan recursively.
132 path: PathBuf,
133 /// Language convention to enforce (required).
134 #[arg(long, value_enum)]
135 language: isolation::Language,
136 /// testing-conventions config file providing the `exempt` list (waivers).
137 /// Optional: if the file is absent, nothing is waived.
138 #[arg(long, default_value = "testing-conventions.toml")]
139 config: PathBuf,
140 },
141 /// Run mutation testing over the unit suite and fail on any surviving mutant not
142 /// lifted by a `mutation` exemption — the rung above coverage (#201). The gate is
143 /// on by default (no report-only mode). All three languages (Python, TypeScript,
144 /// Rust) are at parity and wired into the reusable workflow as a diff-scoped,
145 /// PR-only job (#204).
146 Mutation {
147 /// Crate whose unit suite is mutated.
148 path: PathBuf,
149 /// Language convention to enforce (required): `python`, `typescript`, or `rust`.
150 #[arg(long, value_enum)]
151 language: colocated_test::Language,
152 /// Opt-in diff-scoping (#201): restrict to mutants on lines a `<base>...HEAD`
153 /// diff added or modified, via cargo-mutants' `--in-diff`. Absent means the
154 /// whole crate (slower).
155 #[arg(long)]
156 base: Option<String>,
157 /// testing-conventions config file providing the `exempt` list. Optional:
158 /// absent means nothing is exempt (every survivor must be killed).
159 #[arg(long, default_value = "testing-conventions.toml")]
160 config: PathBuf,
161 /// Path to the bundled TypeScript mutation adapter (`dist/mutation/main.js`), used
162 /// only by `--language typescript`. The npm launcher appends it; hidden because a
163 /// consumer never sets it by hand.
164 #[arg(long = "ts-mutation-adapter", hide = true)]
165 ts_adapter: Option<PathBuf>,
166 },
167}
168
169/// Languages the integration-test lints support — its own set (Python,
170/// TypeScript, Rust), distinct from the file-pairing `colocated_test::Language`,
171/// so adding Rust here doesn't touch the colocated-test/coverage rules.
172#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
173pub enum IntegrationLintLanguage {
174 /// Python test files (`*_test.py`, `test_*.py`, `conftest.py`).
175 #[value(name = "python")]
176 Python,
177 /// TypeScript test files (`*.test.{ts,tsx,mts,cts}`).
178 #[value(name = "typescript")]
179 TypeScript,
180 /// Rust integration crates under `tests/`.
181 #[value(name = "rust")]
182 Rust,
183}
184
185/// Lints enforced on integration tests (mocking mechanism & style, and more to
186/// come). The README's "Integration" taxonomy.
187#[derive(Subcommand, Debug)]
188enum IntegrationRule {
189 /// Lint integration test files for mocking mechanism & style (Python, TypeScript, Rust).
190 Lint {
191 /// Directory to scan recursively for test files.
192 path: PathBuf,
193 /// Language convention to enforce (required).
194 #[arg(long, value_enum)]
195 language: IntegrationLintLanguage,
196 /// testing-conventions config file providing the `exempt` list (waivers).
197 /// Optional: if the file is absent, nothing is waived.
198 #[arg(long, default_value = "testing-conventions.toml")]
199 config: PathBuf,
200 },
201}
202
203/// E2E attestation commands (#17): record a local e2e run and (later, #68)
204/// verify in CI that the latest code commit is attested.
205#[derive(Subcommand, Debug)]
206enum E2eCommand {
207 /// Run the e2e suite and write a committed attestation naming the current commit.
208 Attest {
209 /// The e2e command to run (e.g. `pnpm run e2e`), executed via the shell.
210 command: String,
211 },
212 /// Verify the committed attestation names the latest code commit (the CI gate).
213 Verify {
214 /// Directory whose committed e2e-attestation.json is verified (default: current directory).
215 #[arg(default_value = ".")]
216 path: PathBuf,
217 /// Directory the "latest code commit" freshness walk is scoped to, if
218 /// narrower than `path` (default: `path` itself, byte-identical to before
219 /// this flag existed). Must be `path` or a descendant of it.
220 #[arg(long)]
221 scope: Option<PathBuf>,
222 /// Opt-in diff-scoping (#319): restrict freshness to the commits this
223 /// branch introduced (`<base>..HEAD`) rather than all reachable history.
224 /// A branch that didn't touch the scoped source passes with nothing to
225 /// re-attest — the way the changed-line coverage/mutation gates pass on an
226 /// empty diff, and what makes the gate safe for a squash-merging repo.
227 /// Absent means the whole history (byte-identical to before this flag).
228 #[arg(long)]
229 base: Option<String>,
230 },
231}
232
233pub fn run<I, T>(args: I) -> anyhow::Result<i32>
234where
235 I: IntoIterator<Item = T>,
236 T: Into<std::ffi::OsString> + Clone,
237{
238 let cli = Cli::try_parse_from(args)?;
239 match cli.command {
240 // The config-driven `check` umbrella isn't wired yet; the scaffold
241 // proves the wiring while individual rules land under their test-kind
242 // group (e.g. `unit colocated-test`).
243 Some(Command::Check) | None => Ok(0),
244 Some(Command::Unit { rule }) => match rule {
245 UnitRule::ColocatedTest {
246 path,
247 language,
248 base,
249 config,
250 } => run_unit_colocated_test(&path, language, base.as_deref(), &config),
251 UnitRule::Coverage {
252 path,
253 language,
254 base,
255 config,
256 } => run_unit_coverage(&path, language, base.as_deref(), &config),
257 UnitRule::Lint {
258 path,
259 language,
260 config,
261 } => run_unit_lint(&path, language, &config),
262 UnitRule::Mutation {
263 path,
264 language,
265 base,
266 config,
267 ts_adapter,
268 } => run_unit_mutation(
269 &path,
270 language,
271 base.as_deref(),
272 &config,
273 ts_adapter.as_deref(),
274 ),
275 },
276 Some(Command::Integration { rule }) => match rule {
277 IntegrationRule::Lint {
278 path,
279 language,
280 config,
281 } => run_integration_lint(&path, language, &config),
282 },
283 Some(Command::Packaging { path, language }) => run_packaging(&path, language),
284 Some(Command::Workflow { path }) => run_workflow(&path),
285 Some(Command::E2e { command }) => match command {
286 E2eCommand::Attest { command } => run_e2e_attest(&command),
287 E2eCommand::Verify { path, scope, base } => {
288 run_e2e_verify(&path, scope.as_deref(), base.as_deref())
289 }
290 },
291 Some(Command::Install { path }) => {
292 agents::install(&path)?;
293 Ok(0)
294 }
295 }
296}
297
298/// The binary's own clap command tree — the source of truth for which subcommands
299/// it exposes. The `workflow` guard (#92) checks a workflow's invocations against
300/// it, so a renamed or removed subcommand is caught the moment they diverge.
301pub fn command() -> clap::Command {
302 Cli::command()
303}
304
305/// Run the unit colocated-test check over `root` for `language`. Always runs the
306/// tree-wide **presence** check (every source file has its colocated test; Rust:
307/// an inline `#[cfg(test)]` module). When `base` is `Some`, *additionally* runs the
308/// commit-scoped **co-change** check (#33) over `<base>...HEAD` — a modified or
309/// deleted source whose colocated test didn't co-change — and the run fails if
310/// either check does. Returns `0` only when both pass.
311///
312/// Presence loads the `colocated-test`-rule exemptions and co-change the
313/// `co-change`-rule exemptions from the config at `config_path` (no config file →
314/// no exemptions). `--base` rejects `--language rust`: Rust units are inline
315/// `#[cfg(test)]` in the same file, so a sibling test can't go stale (presence,
316/// without `--base`, still supports Rust).
317fn run_unit_colocated_test(
318 root: &Path,
319 language: colocated_test::Language,
320 base: Option<&str>,
321 config_path: &Path,
322) -> anyhow::Result<i32> {
323 // `--base` carries the co-change check, which rejects Rust the same way the
324 // standalone `unit co-change` did — before any work, so the message matches.
325 if base.is_some() && language == colocated_test::Language::Rust {
326 anyhow::bail!(
327 "`unit colocated-test --base` supports `--language python` / `typescript`; Rust \
328 units are inline `#[cfg(test)]` in the same file, so a sibling test can't go stale"
329 );
330 }
331 let presence_clean = report_colocated_presence(root, language, config_path)?;
332 let co_change_clean = match base {
333 Some(base) => report_co_change(root, base, language, config_path)?,
334 None => true,
335 };
336 Ok(if presence_clean && co_change_clean {
337 0
338 } else {
339 1
340 })
341}
342
343/// The tree-wide colocated-test **presence** check: every source file under `root`
344/// has its colocated unit test (Rust: an inline `#[cfg(test)]` module). Prints each
345/// orphan to stderr and returns `Ok(false)` when any are found, `Ok(true)` when the
346/// tree is clean. The `colocated-test`-rule exemptions from the config at
347/// `config_path` lift a file (no config file → nothing exempt).
348fn report_colocated_presence(
349 root: &Path,
350 language: colocated_test::Language,
351 config_path: &Path,
352) -> anyhow::Result<bool> {
353 let exempt = colocated_test_exemptions(root, language, config_path)?;
354 let orphans = match language {
355 // Rust units are inline `#[cfg(test)]` modules, so "colocated" means a test
356 // module in the same file, not a sibling file (#40).
357 colocated_test::Language::Rust => colocated_test::missing_inline_tests(root, &exempt)?,
358 _ => colocated_test::missing_unit_tests(root, language, &exempt)?,
359 };
360 if orphans.is_empty() {
361 return Ok(true);
362 }
363 let (label, summary) = match language {
364 colocated_test::Language::Rust => (
365 "missing inline `#[cfg(test)]` tests",
366 "source file(s) with testable code but no inline `#[cfg(test)]` module \
367 (add an inline test module, or an `exempt` entry with a reason)",
368 ),
369 _ => (
370 "missing colocated unit test",
371 "source file(s) missing a colocated unit test \
372 (add a colocated test, or an `exempt` entry with a reason)",
373 ),
374 };
375 for orphan in &orphans {
376 eprintln!("{label}: {}", orphan.display());
377 }
378 eprintln!("error: {} {summary}", orphans.len());
379 Ok(false)
380}
381
382/// The `colocated-test`-rule exempt paths for `language`, resolved (and validated)
383/// from the config at `config_path`. A missing config file means no exemptions —
384/// the check still runs, just with nothing exempted.
385fn colocated_test_exemptions(
386 root: &Path,
387 language: colocated_test::Language,
388 config_path: &Path,
389) -> anyhow::Result<std::collections::BTreeSet<String>> {
390 if !config_path.exists() {
391 return Ok(std::collections::BTreeSet::new());
392 }
393 let config = config::load_config(config_path)?;
394 config::resolve_exempt(
395 root,
396 config.exemptions(language),
397 config::Rule::ColocatedTest,
398 )
399}
400
401/// The commit-scoped **co-change** check (#33) over `root`, diffing `<base>...HEAD`:
402/// every modified or deleted source whose colocated test didn't co-change. Prints
403/// each stale source to stderr and returns `Ok(false)` when any are found,
404/// `Ok(true)` when clean.
405///
406/// Loads the `co-change`-rule exemptions from the config at `config_path` (no
407/// config file → no exemptions); an exempt source needn't co-change. The caller
408/// rejects `--language rust` before this runs: Rust units are inline `#[cfg(test)]`
409/// in the same file, so a sibling test can't go stale.
410fn report_co_change(
411 root: &Path,
412 base: &str,
413 language: colocated_test::Language,
414 config_path: &Path,
415) -> anyhow::Result<bool> {
416 let exempt = co_change_exemptions(root, language, config_path)?;
417 let stale = co_change::stale_sources(root, base, language, &exempt)?;
418 if stale.is_empty() {
419 return Ok(true);
420 }
421 for source in &stale {
422 eprintln!(
423 "source changed without its colocated test: {}",
424 source.display()
425 );
426 }
427 eprintln!(
428 "error: {} source file(s) changed without their colocated test co-changing \
429 (update the test, or add an `exempt` entry with a reason)",
430 stale.len()
431 );
432 Ok(false)
433}
434
435/// The `co-change`-rule exempt paths for `language`, resolved (and validated)
436/// from the config at `config_path`. A missing config file means no exemptions —
437/// every changed source must co-change its test.
438fn co_change_exemptions(
439 root: &Path,
440 language: colocated_test::Language,
441 config_path: &Path,
442) -> anyhow::Result<std::collections::BTreeSet<String>> {
443 if !config_path.exists() {
444 return Ok(std::collections::BTreeSet::new());
445 }
446 let config = config::load_config(config_path)?;
447 config::resolve_exempt(root, config.exemptions(language), config::Rule::CoChange)
448}
449
450/// Split a resolved exempt-scope map (#226) into the whole-file paths and the
451/// line-scoped sets — the two shapes the `coverage` / `mutation` measure functions
452/// take. A [`config::LineScope::WholeFile`] becomes a path in the first vec; a
453/// [`config::LineScope::Lines`] a `path → lines` entry in the second map.
454fn split_scopes(
455 scopes: std::collections::BTreeMap<String, config::LineScope>,
456) -> (
457 Vec<String>,
458 std::collections::BTreeMap<String, std::collections::BTreeSet<u32>>,
459) {
460 let mut whole_file = Vec::new();
461 let mut line_scoped = std::collections::BTreeMap::new();
462 for (path, scope) in scopes {
463 match scope {
464 config::LineScope::WholeFile => whole_file.push(path),
465 config::LineScope::Lines(lines) => {
466 line_scoped.insert(path, lines);
467 }
468 }
469 }
470 (whole_file, line_scoped)
471}
472
473/// Run the unit-test coverage check over `root` for `language`, enforcing the
474/// floor from the config at `config_path`. Returns `0` when the floor is met,
475/// `1` otherwise.
476///
477/// With `base` set, the same configured floor is measured over the
478/// `<base>...HEAD` diff (the changed lines) rather than the whole tree (#162),
479/// via the diff-scoped [`patch_coverage::measure`] / `measure_typescript` /
480/// `measure_rust`; without it, the whole-tree [`coverage::measure`] family runs.
481///
482/// Coverage is zero-config by default for Python and TypeScript (#80): a missing
483/// config file — or a config with no `[<language>].coverage` table — falls back to
484/// the language's sane default floor ([`config::PythonCoverage::default`] /
485/// [`config::TypeScriptCoverage::default`]), the same way `unit colocated-test` and
486/// `integration lint` treat an absent config as "nothing exempt". A present
487/// `coverage` table overrides the default; `coverage`-rule exemptions still apply.
488/// Rust (#206) is zero-config too: a missing `[rust].coverage` table falls back to
489/// [`config::RustCoverage::default`] (`lines = 100`, `regions` opt-in, no branch).
490fn run_unit_coverage(
491 root: &Path,
492 language: colocated_test::Language,
493 base: Option<&str>,
494 config_path: &Path,
495) -> anyhow::Result<i32> {
496 let config = if config_path.exists() {
497 config::load_config(config_path)?
498 } else {
499 config::Config::default()
500 };
501 let outcome = match language {
502 colocated_test::Language::Python => {
503 let python = config.python.unwrap_or_default();
504 let coverage = python.coverage.unwrap_or_default();
505 let thresholds = coverage::Thresholds {
506 fail_under: coverage.fail_under,
507 branch: coverage.branch,
508 };
509 let (omit, exempt_lines) = split_scopes(config::resolve_exempt_scoped(
510 root,
511 &python.exempt,
512 config::Rule::Coverage,
513 )?);
514 match base {
515 Some(base) => {
516 patch_coverage::measure(root, base, thresholds, &omit, &exempt_lines)?
517 }
518 None if exempt_lines.is_empty() => coverage::measure(root, thresholds, &omit)?,
519 None => {
520 patch_coverage::measure_line_exempt(root, thresholds, &omit, &exempt_lines)?
521 }
522 }
523 }
524 colocated_test::Language::TypeScript => {
525 let typescript = config.typescript.unwrap_or_default();
526 let coverage = typescript.coverage.unwrap_or_default();
527 let thresholds = coverage::TypeScriptThresholds {
528 lines: coverage.lines,
529 branches: coverage.branches,
530 functions: coverage.functions,
531 statements: coverage.statements,
532 };
533 let (exclude, exempt_lines) = split_scopes(config::resolve_exempt_scoped(
534 root,
535 &typescript.exempt,
536 config::Rule::Coverage,
537 )?);
538 match base {
539 Some(base) => patch_coverage::measure_typescript(
540 root,
541 base,
542 thresholds,
543 &exclude,
544 &exempt_lines,
545 )?,
546 None if exempt_lines.is_empty() => {
547 coverage::measure_typescript(root, thresholds, &exclude)?
548 }
549 None => patch_coverage::measure_line_exempt_typescript(
550 root,
551 thresholds,
552 &exclude,
553 &exempt_lines,
554 )?,
555 }
556 }
557 colocated_test::Language::Rust => {
558 let rust = config.rust.unwrap_or_default();
559 // Zero-config (#206): a missing `[rust].coverage` table falls back to the
560 // default Rust floor (`lines = 100`, with `regions` opt-in and no branch
561 // component) — matching Python/TypeScript — rather than erroring for a
562 // required table. A present table overrides it.
563 let coverage = rust.coverage.unwrap_or_default();
564 let thresholds = coverage::RustThresholds {
565 regions: coverage.regions,
566 lines: coverage.lines,
567 functions: coverage.functions,
568 branch: coverage.branch,
569 };
570 let (ignore, exempt_lines) = split_scopes(config::resolve_exempt_scoped(
571 root,
572 &rust.exempt,
573 config::Rule::Coverage,
574 )?);
575 match base {
576 Some(base) => patch_coverage::measure_rust(
577 root,
578 base,
579 thresholds,
580 &ignore,
581 &exempt_lines,
582 &rust.features,
583 )?,
584 None if exempt_lines.is_empty() => {
585 coverage::measure_rust(root, thresholds, &ignore, &rust.features)?
586 }
587 None => patch_coverage::measure_line_exempt_rust(
588 root,
589 thresholds,
590 &ignore,
591 &exempt_lines,
592 &rust.features,
593 )?,
594 }
595 }
596 };
597 match outcome {
598 coverage::Outcome::Pass => Ok(0),
599 coverage::Outcome::Fail(reason) => {
600 eprintln!("error: coverage check failed — {reason}");
601 Ok(1)
602 }
603 }
604}
605
606/// Run `unit mutation` over `root` (#201, #202): run the per-language engine and fail
607/// on any surviving mutant not lifted by a `mutation` exemption.
608///
609/// The gate is **on by default and binary** — "no *unexplained* surviving mutant":
610/// every survivor must be killed with an assertion, or lifted by a reason-required
611/// `[[<language>.exempt]] rules = ["mutation"]` for an equivalent / deliberately-defensive
612/// mutation. There is no percentage floor (equivalent mutants make one unreachable)
613/// and no report-only mode — the only loosening is a reasoned, per-file exemption.
614/// All three languages are wired: Rust (cargo-mutants), TypeScript (Stryker), and
615/// Python (cosmic-ray). `--base` scopes the run to the diff.
616fn run_unit_mutation(
617 root: &Path,
618 language: colocated_test::Language,
619 base: Option<&str>,
620 config_path: &Path,
621 ts_adapter: Option<&Path>,
622) -> anyhow::Result<i32> {
623 let config = if config_path.exists() {
624 config::load_config(config_path)?
625 } else {
626 config::Config::default()
627 };
628 let survivors = match language {
629 colocated_test::Language::Rust => {
630 let rust = config.rust.unwrap_or_default();
631 let (exempt, exempt_lines) = split_scopes(config::resolve_exempt_scoped(
632 root,
633 &rust.exempt,
634 config::Rule::Mutation,
635 )?);
636 mutation::measure_rust(root, &exempt, &exempt_lines, base, &rust.features)?
637 }
638 colocated_test::Language::TypeScript => {
639 let typescript = config.typescript.unwrap_or_default();
640 let (exempt, exempt_lines) = split_scopes(config::resolve_exempt_scoped(
641 root,
642 &typescript.exempt,
643 config::Rule::Mutation,
644 )?);
645 // The npm launcher appends `--ts-mutation-adapter`; its absence means the binary
646 // was run directly, not through the published CLI.
647 let adapter = ts_adapter.ok_or_else(|| {
648 anyhow::anyhow!(
649 "the TypeScript mutation adapter path is required: pass \
650 `--ts-mutation-adapter <path>`. The npm `testing-conventions` CLI appends it \
651 automatically — run the rule through that CLI, not the raw binary."
652 )
653 })?;
654 mutation::measure_typescript(root, &exempt, &exempt_lines, base, adapter)?
655 }
656 colocated_test::Language::Python => {
657 let python = config.python.unwrap_or_default();
658 let (exempt, exempt_lines) = split_scopes(config::resolve_exempt_scoped(
659 root,
660 &python.exempt,
661 config::Rule::Mutation,
662 )?);
663 mutation::measure_python(root, &exempt, &exempt_lines, base)?
664 }
665 };
666 if survivors.is_empty() {
667 println!("unit mutation: no surviving mutants — every mutation was caught");
668 return Ok(0);
669 }
670
671 eprintln!(
672 "error: {} unexplained surviving mutant(s) — kill each with an assertion, or lift an \
673 equivalent/defensive one with a reason-required `[[<language>.exempt]] rules = [\"mutation\"]`:",
674 survivors.len()
675 );
676 for survivor in &survivors {
677 eprintln!(
678 " {}:{}: {}",
679 survivor.file, survivor.line, survivor.description
680 );
681 }
682 Ok(1)
683}
684
685/// Run the `unit lint` check over `root` for `language` — the unit-suite
686/// isolation lints (`unmocked-collaborator`, `untyped-mock`, `no-out-of-module-call`,
687/// `no-out-of-module-import`) — printing each violation to stderr as
688/// `path:line: rule — message` and returning `1` when any are found, `0` otherwise.
689fn run_unit_lint(
690 root: &Path,
691 language: isolation::Language,
692 config_path: &Path,
693) -> anyhow::Result<i32> {
694 let (raw, select): (Vec<lint::Violation>, ExemptSelect) = match language {
695 isolation::Language::Rust => (isolation::find_violations(root)?, |c| c.rust_exemptions()),
696 isolation::Language::TypeScript => (ts::find_unit_violations(root)?, |c| {
697 c.exemptions(colocated_test::Language::TypeScript)
698 }),
699 isolation::Language::Python => (lint::find_unit_isolation_violations(root)?, |c| {
700 c.exemptions(colocated_test::Language::Python)
701 }),
702 };
703 let violations = apply_waivers(raw, root, config_path, select)?;
704 if violations.is_empty() {
705 return Ok(0);
706 }
707 for v in &violations {
708 eprintln!(
709 "{}:{}: {} — {}",
710 v.file.display(),
711 v.line,
712 v.rule,
713 v.message
714 );
715 }
716 eprintln!("error: {} isolation violation(s)", violations.len());
717 Ok(1)
718}
719
720/// Run the integration-test lints over `root` for `language`, printing each
721/// violation to stderr as `path:line: rule — message` and returning `1` when any
722/// are found, `0` otherwise.
723fn run_integration_lint(
724 root: &Path,
725 language: IntegrationLintLanguage,
726 config_path: &Path,
727) -> anyhow::Result<i32> {
728 let (raw, select): (Vec<lint::Violation>, ExemptSelect) = match language {
729 IntegrationLintLanguage::Python => (lint::find_violations(root)?, |c| {
730 c.exemptions(colocated_test::Language::Python)
731 }),
732 IntegrationLintLanguage::TypeScript => (ts::find_integration_violations(root)?, |c| {
733 c.exemptions(colocated_test::Language::TypeScript)
734 }),
735 IntegrationLintLanguage::Rust => (isolation::find_integration_violations(root)?, |c| {
736 c.rust_exemptions()
737 }),
738 };
739 let violations = apply_waivers(raw, root, config_path, select)?;
740 if violations.is_empty() {
741 return Ok(0);
742 }
743 for v in &violations {
744 eprintln!(
745 "{}:{}: {} — {}",
746 v.file.display(),
747 v.line,
748 v.rule,
749 v.message
750 );
751 }
752 eprintln!("error: {} lint violation(s)", violations.len());
753 Ok(1)
754}
755
756/// Selects a language's `[[<lang>.exempt]]` table from a loaded config — the one
757/// varying piece between the `unit lint` and `integration lint` waiver paths.
758type ExemptSelect = fn(&config::Config) -> &[config::Exemption];
759
760/// Drop the violations waived by the config's `exempt` list (#32/#102). A
761/// violation is waived when its `rule` is a known [`config::Rule`] and its
762/// `root`-relative path is exempt for that rule. `exemptions` selects the
763/// language's `[[<lang>.exempt]]` table from the loaded config. A missing config
764/// file waives nothing; a reason-less or stale entry errors (via `load_config` /
765/// `resolve_exempt`), so the escape hatch can't silently rot.
766fn apply_waivers(
767 violations: Vec<lint::Violation>,
768 root: &Path,
769 config_path: &Path,
770 exemptions: ExemptSelect,
771) -> anyhow::Result<Vec<lint::Violation>> {
772 use std::collections::hash_map::Entry;
773
774 if !config_path.exists() {
775 return Ok(violations);
776 }
777 let config = config::load_config(config_path)?;
778 let exempt = exemptions(&config);
779 // Resolve each rule's exempt set once (and surface a stale entry as an error).
780 let mut resolved: std::collections::HashMap<config::Rule, std::collections::BTreeSet<String>> =
781 std::collections::HashMap::new();
782 let mut kept = Vec::new();
783 for violation in violations {
784 let waived = match config::Rule::from_id(violation.rule) {
785 Some(rule) => {
786 let exempt_paths = match resolved.entry(rule) {
787 Entry::Occupied(entry) => entry.into_mut(),
788 Entry::Vacant(entry) => {
789 entry.insert(config::resolve_exempt(root, exempt, rule)?)
790 }
791 };
792 violation
793 .file
794 .strip_prefix(root)
795 .ok()
796 .map(|rel| rel.to_string_lossy().replace('\\', "/"))
797 .is_some_and(|rel| exempt_paths.contains(&rel))
798 }
799 None => false,
800 };
801 if !waived {
802 kept.push(violation);
803 }
804 }
805 Ok(kept)
806}
807
808/// Run the packaging check: inspect the built artifact at `artifact` for test
809/// files that must not ship (README "Packaging"), per `language`'s test-file
810/// globs.
811///
812/// `artifact` is either an already-unpacked directory or a packed artifact the
813/// rule unpacks itself — a Python wheel (`.whl`) today; the TypeScript (#73) and
814/// Rust (#74) archives follow. Returns `0` when no test file is present, `1`
815/// otherwise (after printing each offending path, relative to the artifact root).
816fn run_packaging(artifact: &Path, language: colocated_test::Language) -> anyhow::Result<i32> {
817 let globs = match language {
818 colocated_test::Language::Python => vec!["*_test.py".to_string()],
819 colocated_test::Language::TypeScript => vec!["*.test.*".to_string()],
820 // `#[cfg(test)]` units compile out for free; the only thing to keep out of
821 // the `.crate` source tarball is the crate-root integration `tests/` dir.
822 colocated_test::Language::Rust => vec!["tests/".to_string()],
823 };
824 let offenders = packaging::inspect(artifact, &globs)?;
825 if offenders.is_empty() {
826 return Ok(0);
827 }
828 for offender in &offenders {
829 eprintln!("test file in built artifact: {}", offender.display());
830 }
831 eprintln!(
832 "error: {} test file(s) present in the built artifact \
833 (they must be excluded from packaging)",
834 offenders.len()
835 );
836 Ok(1)
837}
838
839/// Run the workflow guard over `path` (a workflow file or directory): flag every
840/// `testing-conventions` invocation that names a subcommand this binary no longer
841/// exposes, printing each as `path:line: rule — message` and returning `1` when any
842/// are found, `0` otherwise.
843fn run_workflow(path: &Path) -> anyhow::Result<i32> {
844 let violations = workflow::check(path, &command())?;
845 if violations.is_empty() {
846 return Ok(0);
847 }
848 for v in &violations {
849 eprintln!(
850 "{}:{}: {} — {}",
851 v.file.display(),
852 v.line,
853 v.rule,
854 v.message
855 );
856 }
857 eprintln!(
858 "error: {} workflow invocation(s) name a subcommand this binary no longer exposes",
859 violations.len()
860 );
861 Ok(1)
862}
863
864/// Run `command` as an e2e suite and write a committed attestation naming the
865/// current commit (#67). Force-runs: the attestation is written regardless of
866/// the command's exit code, so this exits `0` once the attestation is recorded.
867fn run_e2e_attest(command: &str) -> anyhow::Result<i32> {
868 let repo = std::env::current_dir()?;
869 let attestation = e2e::attest(&repo, command)?;
870 println!(
871 "e2e attestation recorded for commit {} (command exited {})",
872 attestation.commit, attestation.exit_code
873 );
874 Ok(0)
875}
876
877/// Verify the committed e2e attestation names the latest code commit (#68) — the
878/// CI side of the nudge. Exits `0` when fresh; otherwise prints the actionable
879/// hint and exits `1`. Never runs e2e, never judges the recorded run.
880///
881/// `path` is the directory whose committed `e2e-attestation.json` is checked
882/// (#281) — the default `.` resolves against the current directory, so a
883/// no-argument call behaves exactly like the pre-#281 `current_dir()` read.
884/// Passing a package subdirectory scopes discovery to it, matching a call made
885/// with that directory as cwd. `scope`, when set, narrows the "latest code
886/// commit" freshness walk to a directory under `path` instead of all of it
887/// (#294) — `None` behaves exactly like passing `path` itself. `base`, when set,
888/// restricts the walk to the commits this branch introduced (`<base>..HEAD`)
889/// instead of all history (#319) — `None` behaves exactly like before the flag.
890fn run_e2e_verify(path: &Path, scope: Option<&Path>, base: Option<&str>) -> anyhow::Result<i32> {
891 match e2e::verify_since(path, scope.unwrap_or(path), base)? {
892 e2e::Verification::Fresh => Ok(0),
893 e2e::Verification::Missing => {
894 eprintln!(
895 "e2e attestation missing — run `testing-conventions e2e attest '<your e2e command>'`"
896 );
897 Ok(1)
898 }
899 e2e::Verification::Stale { attested, latest } => {
900 eprintln!(
901 "e2e attestation out of date: attested {}, latest code commit {} — \
902 run `testing-conventions e2e attest '<your e2e command>'`",
903 &attested[..attested.len().min(7)],
904 &latest[..latest.len().min(7)]
905 );
906 Ok(1)
907 }
908 }
909}
910
911#[cfg(test)]
912mod tests {
913 use super::*;
914
915 #[test]
916 fn no_args_returns_ok_zero() {
917 assert_eq!(run(["testing-conventions"]).unwrap(), 0);
918 }
919
920 #[test]
921 fn check_returns_ok_zero() {
922 assert_eq!(run(["testing-conventions", "check"]).unwrap(), 0);
923 }
924
925 #[test]
926 fn unknown_flag_errors() {
927 assert!(run(["testing-conventions", "--bogus"]).is_err());
928 }
929
930 #[test]
931 fn help_flag_returns_clap_display_help() {
932 let err = run(["testing-conventions", "--help"]).expect_err("--help should bubble");
933 let clap_err = err
934 .downcast_ref::<clap::Error>()
935 .expect("error should be a clap::Error");
936 assert_eq!(clap_err.kind(), clap::error::ErrorKind::DisplayHelp);
937 }
938
939 #[test]
940 fn version_flag_returns_clap_display_version() {
941 let err = run(["testing-conventions", "--version"]).expect_err("--version should bubble");
942 let clap_err = err
943 .downcast_ref::<clap::Error>()
944 .expect("error should be a clap::Error");
945 assert_eq!(clap_err.kind(), clap::error::ErrorKind::DisplayVersion);
946 }
947}