diff --git a/README.md b/README.md index f05d8ff..678405f 100644 --- a/README.md +++ b/README.md @@ -265,8 +265,9 @@ Only mutants that compiled and were tested are scored. The summary lists everyth | not covered | survived | no test executes the mutated code (Go) | | does not compile | excluded | the mutation is not a valid program, so it says nothing about the tests | | not run | excluded | the budget ran out or the run was cancelled; a gating tier with any of these is at least WARN | +| not tested | excluded | the tests that reach the mutant fail without any mutation; a gating tier with any of these is FAIL | -If a package's tests fail before any mutation is applied, its mutants are reported as not run instead of all "killed". +A test that fails before any mutation is applied cannot judge a mutant. It is retried once, then left out and named on stderr; the other tests still run. A mutant that only such tests reach is reported as not tested instead of "killed", and the run fails rather than passing over code it could not check. #### Keeping large diffs fast diff --git a/internal/lang/goanalyzer/session.go b/internal/lang/goanalyzer/session.go index 1b79e83..85fec36 100644 --- a/internal/lang/goanalyzer/session.go +++ b/internal/lang/goanalyzer/session.go @@ -6,6 +6,7 @@ import ( "os" "path/filepath" "regexp" + "slices" "strconv" "strings" "sync" @@ -26,6 +27,9 @@ const slowTestThreshold = time.Second // A mutant that cannot be compiled into the shared binary, or a package // whose shared build or baseline fails, is tested the slow way: one // `go test -overlay` per mutant. +// +// Tests that fail without any mutation cannot judge a mutant. They are left +// out, and a mutant only they reach is reported as baseline-failed. type goSession struct { cfg lang.SessionConfig sites []lang.MutantSite @@ -116,6 +120,9 @@ type mutantPackage struct { // build is unavailable, which routes every site to the overlay path. embedded map[int]bool bins []*testBinary + // leftOut names the tests of bins that fail without any mutation. The + // overlay path skips them too. + leftOut []string baselineOnce sync.Once baselineOK bool @@ -124,8 +131,9 @@ type mutantPackage struct { // runSchemata tests mutant id against every test that reaches it. func (p *mutantPackage) runSchemata(ctx context.Context, id int) lang.MutantResult { - covered := false + covered, broken := false, false for _, b := range p.bins { + broken = broken || b.broken[id] for _, g := range b.groupsReaching(id) { covered = true if res := b.runGroup(ctx, g, id, p.session.cfg); res.Outcome != lang.OutcomeSurvived { @@ -133,18 +141,24 @@ func (p *mutantPackage) runSchemata(ctx context.Context, id int) lang.MutantResu } } } - if !covered { - return lang.MutantResult{Outcome: lang.OutcomeNotCovered} + switch { + case covered: + return lang.MutantResult{Outcome: lang.OutcomeSurvived} + case broken: + return lang.MutantResult{Outcome: lang.OutcomeBaselineFailed} } - return lang.MutantResult{Outcome: lang.OutcomeSurvived} + return lang.MutantResult{Outcome: lang.OutcomeNotCovered} } // runOverlay tests one mutant with its own build: the mutated file replaces // the original through a build overlay. func (p *mutantPackage) runOverlay(ctx context.Context, idx int) lang.MutantResult { p.baselineOnce.Do(func() { p.overlayBaseline(ctx) }) - if !p.baselineOK { + switch { + case ctx.Err() != nil: return lang.MutantResult{Outcome: lang.OutcomeNotRun} + case !p.baselineOK: + return lang.MutantResult{Outcome: lang.OutcomeBaselineFailed} } cfg := p.session.cfg site := p.session.sites[idx] @@ -167,24 +181,35 @@ func (p *mutantPackage) runOverlay(ctx context.Context, idx int) lang.MutantResu // so that a hang is reported as a timeout, not as a failing test. timeout := overlayTimeout(p.baselineTook, cfg.Timeout) args := buildTestArgs(lang.TestRunConfig{Timeout: timeout + time.Minute, TestPattern: cfg.TestPattern}, overlay) + args = slices.Insert(args, len(args)-1, p.skipArgs()...) return classify(ctx, p.goCmd(ctx, timeout, args...), lang.OutcomeKilled) } // overlayBaseline runs the package's unmutated tests once. If they fail, -// every result would read as a kill, so the package's mutants are not run. +// every result would read as a kill, so the package's mutants are reported +// as baseline-failed instead of being run. func (p *mutantPackage) overlayBaseline(ctx context.Context) { args := []string{"test", "-count=1"} if pattern := p.session.cfg.TestPattern; pattern != "" { args = append(args, "-run", pattern) } + args = append(args, p.skipArgs()...) res := p.goCmd(ctx, baselineTimeout(p.session.cfg), append(args, "./...")...) p.baselineOK = res.err == nil p.baselineTook = res.duration if !p.baselineOK && ctx.Err() == nil { - p.session.logf("tests fail without any mutation in %s; its mutants were not run\n%s", p.dir, res.output) + p.session.logf("tests fail without any mutation in %s; its mutants cannot be tested\n%s", p.dir, res.output) } } +// skipArgs returns the go test flag that skips the left-out tests. +func (p *mutantPackage) skipArgs() []string { + if p.leftOut == nil { + return nil + } + return []string{"-skip", exactly(p.leftOut)} +} + func (p *mutantPackage) goCmd(ctx context.Context, timeout time.Duration, args ...string) procResult { return proc{dir: p.dir, timeout: timeout, name: "go", args: args, keep: 1 << 20}.run(ctx) } @@ -229,10 +254,16 @@ func mutantTimeout(baseline, ceiling time.Duration) time.Duration { type testBinary struct { path string dir string + own bool // the mutated package's own tests // tests holds one traced run per test when every test passes on its // own; otherwise whole holds a single traced run of the full suite. tests []tracedTest whole *tracedTest + // broken holds the mutants reached by tests that fail without any + // mutation and are therefore left out of tests. + broken map[int]bool + // leftOut names those tests. + leftOut []string } // tracedTest is an unmutated test run and the mutants it reached. @@ -309,9 +340,14 @@ func runFilter(names []string, pattern string) []string { } return []string{"-test.run", pattern} } + return []string{"-test.run", exactly(names)} +} + +// exactly returns the pattern matching the tests called names and no other. +func exactly(names []string) string { quoted := make([]string, len(names)) for i, n := range names { quoted[i] = regexp.QuoteMeta(n) } - return []string{"-test.run", "^(" + strings.Join(quoted, "|") + ")$"} + return "^(" + strings.Join(quoted, "|") + ")$" } diff --git a/internal/lang/goanalyzer/session_prepare.go b/internal/lang/goanalyzer/session_prepare.go index e88ef08..9477022 100644 --- a/internal/lang/goanalyzer/session_prepare.go +++ b/internal/lang/goanalyzer/session_prepare.go @@ -44,6 +44,9 @@ func (p *mutantPackage) prepare(ctx context.Context) { return } p.embedded, p.bins = in.embedded, bins + for _, b := range bins { + p.leftOut = append(p.leftOut, b.leftOut...) + } } func (p *mutantPackage) fallback(ctx context.Context, why string) { @@ -224,7 +227,7 @@ func (p *mutantPackage) buildTestBinary(ctx context.Context, overlay string, tp if _, err := os.Stat(path); err != nil { return nil, false } - return &testBinary{path: path, dir: tp.dir}, false + return &testBinary{path: path, dir: tp.dir, own: tp.own}, false } // testPackage is a package whose tests can observe the mutated package. @@ -282,27 +285,36 @@ func dependsOn(deps, importPath string) bool { // baseline runs the binary's tests unmutated, recording which mutants each // reaches. It prefers one run per test, which lets a mutant be tested by -// only the tests that reach it; if a test fails on its own (tests that -// depend on each other), it falls back to a single run of the whole suite. -// It reports false if the suite does not pass even then. +// only the tests that reach it. If some tests fail on their own, a single +// run of the whole suite is tried (tests that depend on each other); if +// that fails too, the failing tests are left out and the rest are used. +// It reports false if that leaves nothing to go on. func (b *testBinary) baseline(ctx context.Context, s *goSession) bool { - names, ok := b.listTests(ctx, s.cfg) + names, listed := b.listTests(ctx, s.cfg) + passing, failing := b.traceEach(ctx, s, names) + if listed && failing == nil { + b.tests = passing + return true + } + release := s.acquire() + whole, ok := b.trace(ctx, s.cfg, "") + release() if ok { - if tests, ok := b.traceEach(ctx, s, names); ok { - b.tests = tests - return true - } + b.whole = &whole + return true } - for range 2 { - release := s.acquire() - whole, ok := b.trace(ctx, s.cfg, "") - release() - if ok { - b.whole = &whole - return true - } + if ctx.Err() != nil || !b.usable(passing, failing) { + return false } - return false + // The failed suite run counts too: a test that needs another's setup + // reaches code there that it never gets to on its own. + b.tests, b.broken = passing, whole.reach + for _, t := range failing { + b.leftOut = append(b.leftOut, t.name) + maps.Copy(b.broken, t.reach) + } + s.logf("%s: %d test(s) fail without any mutation and were left out: %s", b.dir, len(b.leftOut), strings.Join(b.leftOut, ", ")) + return true } // testName matches the top-level tests a binary lists that -test.run can @@ -327,35 +339,60 @@ func (b *testBinary) listTests(ctx context.Context, cfg lang.SessionConfig) ([]s return names, true } -// traceEach traces every test in its own process. It reports false, and -// stops starting further traces, as soon as one of them fails. -func (b *testBinary) traceEach(ctx context.Context, s *goSession, names []string) ([]tracedTest, bool) { - ctx, cancel := context.WithCancel(ctx) - defer cancel() +// usable reports whether a binary whose suite fails can still be used with +// its failing tests left out. The mutated package's own binary needs a test +// that passes. A dependent package's needs only tests to leave out: with +// none passing it judges nothing, but it must not cost the mutated package +// its own healthy tests. +func (b *testBinary) usable(passing, failing []tracedTest) bool { + if b.own { + return passing != nil + } + return failing != nil +} + +// traceEach traces every test in its own process, a second time if it +// fails, and returns the tests that passed and those that did not. +func (b *testBinary) traceEach(ctx context.Context, s *goSession, names []string) (passing, failing []tracedTest) { tests := make([]tracedTest, len(names)) passed := make([]bool, len(names)) var wg sync.WaitGroup for i, name := range names { release := s.acquire() - if ctx.Err() != nil { - release() - break - } wg.Add(1) go func() { defer wg.Done() defer release() - if tests[i], passed[i] = b.trace(ctx, s.cfg, name); !passed[i] { - cancel() - } + tests[i], passed[i] = b.traceTwice(ctx, s.cfg, name) }() } wg.Wait() - return tests, !slices.Contains(passed, false) + for i, t := range tests { + if passed[i] { + passing = append(passing, t) + } else { + failing = append(failing, t) + } + } + return passing, failing +} + +// traceTwice traces one test, and once more if it fails. A test that fails +// both times keeps what both runs reached. +func (b *testBinary) traceTwice(ctx context.Context, cfg lang.SessionConfig, name string) (tracedTest, bool) { + first, ok := b.trace(ctx, cfg, name) + if ok { + return first, true + } + second, ok := b.trace(ctx, cfg, name) + if !ok { + maps.Copy(second.reach, first.reach) + } + return second, ok } // trace runs one test (or, with an empty name, the whole suite) unmutated -// and returns what it reached. +// and returns what it reached, which is recorded even if the run fails. func (b *testBinary) trace(ctx context.Context, cfg lang.SessionConfig, name string) (tracedTest, bool) { traceFile := b.path + "." + name + ".trace" os.Remove(traceFile) @@ -370,10 +407,7 @@ func (b *testBinary) trace(ctx context.Context, cfg lang.SessionConfig, name str name: b.path, args: append([]string{"-test.count=1"}, runFilter(names, cfg.TestPattern)...), }.run(ctx) - if res.err != nil { - return tracedTest{}, false - } - return tracedTest{name: name, duration: res.duration, reach: readTrace(traceFile)}, true + return tracedTest{name: name, duration: res.duration, reach: readTrace(traceFile)}, res.err == nil } // readTrace returns the mutant ids recorded in a trace file. A missing file diff --git a/internal/lang/goanalyzer/session_test.go b/internal/lang/goanalyzer/session_test.go index ce45424..926b5b8 100644 --- a/internal/lang/goanalyzer/session_test.go +++ b/internal/lang/goanalyzer/session_test.go @@ -9,6 +9,7 @@ import ( "os" "path/filepath" "reflect" + "slices" "strconv" "strings" "testing" @@ -272,15 +273,15 @@ func TestB(t *testing.T) { } // If the tests fail before any mutation, every mutant would look killed. -// They must be reported as not run instead. +// They must be reported as baseline-failed instead. func TestSession_FailingBaselineRunsNothing(t *testing.T) { root := writeModule(t, "package p\n\nfunc Add(a, b int) int { return a + b }\n", "package p\n\nimport \"testing\"\n\nfunc TestRed(t *testing.T) { t.Fatal(Add(1, 1)) }\n") var log bytes.Buffer got, _ := runSession(t, root, lang.SessionConfig{Log: &log}) for k, o := range got { - if o != lang.OutcomeNotRun { - t.Errorf("%s: got %v, want not_run", k, o) + if o != lang.OutcomeBaselineFailed { + t.Errorf("%s: got %v, want baseline_failed", k, o) } } if !strings.Contains(log.String(), "tests fail without any mutation") { @@ -288,6 +289,105 @@ func TestSession_FailingBaselineRunsNothing(t *testing.T) { } } +// One test that fails without any mutation must not cost the package its +// other tests: it is left out and named, and the mutants the passing tests +// reach are tested, including one that needs a build of its own. A mutant +// only failing runs reach is baseline-failed, wherever the evidence is: a +// test's last run (Twice), the whole suite (Setup, reached only after +// another test's setup) or a first attempt the retry did not repeat (Once). +func TestSession_FailingTestIsLeftOut(t *testing.T) { + source := `package p + +func Add(a, b int) int { return a + b } + +func Join(a string) string { return a + "!" } + +func Twice(a int) int { return a * 2 } + +func Setup(a int) int { return a * 3 } + +func Once(a int) int { return a * 4 } + +func Unused(a int) int { return a - 1 } + +func Size() int { + var b [2 + 1]int + return len(b) +} +` + tests := `package p + +import ( + "os" + "testing" +) + +var ready bool + +func TestAdd(t *testing.T) { + ready = true + if Add(2, 3) != 5 || Join("a") != "a!" || Size() != 3 { + t.Fatal("Add") + } +} + +func TestSecondTry(t *testing.T) { + if _, err := os.Stat("tried"); err != nil { + os.WriteFile("tried", nil, 0o644) + t.Fatal("first try") + } +} + +func TestNeedsSetup(t *testing.T) { + if !ready { + t.Fatal("not ready") + } + Setup(1) +} + +func TestFlaky(t *testing.T) { + if _, err := os.Stat("ran"); err != nil { + os.WriteFile("ran", nil, 0o644) + Once(1) + } + t.Fatal("flaky") +} + +func TestRed(t *testing.T) { + Twice(2) + t.Fatal("always red") +} +` + root := writeModule(t, source, tests) + var log bytes.Buffer + got, session := runSession(t, root, lang.SessionConfig{Log: &log}) + want := map[string]lang.MutantOutcome{ + "func Add(a, b int) int { return a + b } | math_operator": lang.OutcomeKilled, + "func Join(a string) string { return a + \"!\" } | math_operator": lang.OutcomeBuildFailed, + "func Twice(a int) int { return a * 2 } | math_operator": lang.OutcomeBaselineFailed, + "func Setup(a int) int { return a * 3 } | math_operator": lang.OutcomeBaselineFailed, + "func Once(a int) int { return a * 4 } | math_operator": lang.OutcomeBaselineFailed, + "func Unused(a int) int { return a - 1 } | math_operator": lang.OutcomeNotCovered, + // An array length cannot be switched at run time: built on its own. + "var b [2 + 1]int | math_operator": lang.OutcomeKilled, + } + for k, o := range want { + if got[k] != o { + t.Errorf("%s: got %v, want %v", k, got[k], o) + } + } + b := session.pkgs[0].bins[0] + if len(b.tests) != 2 || b.tests[0].name != "TestAdd" || b.tests[1].name != "TestSecondTry" || b.whole != nil { + t.Errorf("want TestAdd and TestSecondTry kept, got %+v", b) + } + if session.pkgs[0].embedded[slices.IndexFunc(session.sites, func(s lang.MutantSite) bool { return s.Line == 16 })] { + t.Error("the array-length mutant must take the overlay path") + } + if !strings.Contains(log.String(), "3 test(s) fail without any mutation and were left out: TestNeedsSetup, TestFlaky, TestRed") { + t.Errorf("the left-out tests must be named, log:\n%s", log.String()) + } +} + func TestSession_TestPatternLimitsTheTests(t *testing.T) { root := writeModule(t, sampleSource, sampleTests) got, session := runSession(t, root, lang.SessionConfig{TestPattern: "TestAdd"}) @@ -347,6 +447,52 @@ func TestSession_SubpackageTestsKillMutants(t *testing.T) { } } +// A dependent package whose tests all fail must not cost the mutated package +// its own healthy tests. What only the broken package reaches is +// baseline-failed. +func TestSession_BrokenSubpackageKeepsOwnTests(t *testing.T) { + root := writeModule(t, "package p\n\nfunc Add(a, b int) int { return a + b }\n\nfunc Twice(a int) int { return a * 2 }\n", + "package p\n\nimport \"testing\"\n\nfunc TestAdd(t *testing.T) {\n\tif Add(2, 3) != 5 {\n\t\tt.Fatal()\n\t}\n}\n") + sub := filepath.Join(root, "p/sub") + os.MkdirAll(sub, 0o755) + os.WriteFile(filepath.Join(sub, "sub_test.go"), []byte("package sub\n\nimport (\n\t\"testing\"\n\n\t\"example.com/sample/p\"\n)\n\nfunc TestRed(t *testing.T) {\n\tp.Twice(2)\n\tt.Fatal()\n}\n"), 0o644) + os.WriteFile(filepath.Join(sub, "sub.go"), []byte("package sub\n"), 0o644) + + var log bytes.Buffer + got, session := runSession(t, root, lang.SessionConfig{Log: &log}) + if got["func Add(a, b int) int { return a + b } | math_operator"] != lang.OutcomeKilled { + t.Errorf("Add: %v", got) + } + if got["func Twice(a int) int { return a * 2 } | math_operator"] != lang.OutcomeBaselineFailed { + t.Errorf("Twice: %v", got) + } + if n := len(session.pkgs[0].bins); n != 2 { + t.Errorf("kept %d test binaries, want both", n) + } + if strings.Contains(log.String(), "one build at a time") { + t.Errorf("the shared build must be kept, log:\n%s", log.String()) + } +} + +func TestUsable(t *testing.T) { + some := []tracedTest{{name: "T"}} + cases := []struct { + own bool + passing, failing []tracedTest + want bool + }{ + {true, some, some, true}, + {true, nil, some, false}, + {false, nil, some, true}, + {false, nil, nil, false}, + } + for _, c := range cases { + if got := (&testBinary{own: c.own}).usable(c.passing, c.failing); got != c.want { + t.Errorf("own=%v passing=%d failing=%d: got %v, want %v", c.own, len(c.passing), len(c.failing), got, c.want) + } + } +} + func TestParseTestPackages(t *testing.T) { out := strings.Join([]string{ "example.com/m/p|/src/p|fmt,os", @@ -374,6 +520,16 @@ func TestDependsOn(t *testing.T) { } } +func TestSkipArgs(t *testing.T) { + if got := (&mutantPackage{}).skipArgs(); got != nil { + t.Errorf("nothing left out: got %v, want no flag", got) + } + got := (&mutantPackage{leftOut: []string{"TestA", "TestB/x"}}).skipArgs() + if want := []string{"-skip", "^(TestA|TestB/x)$"}; !reflect.DeepEqual(got, want) { + t.Errorf("got %v, want %v", got, want) + } +} + func TestRunFilter(t *testing.T) { if got := runFilter(nil, ""); got != nil { t.Errorf("whole suite, no pattern: %v", got) @@ -572,8 +728,8 @@ func TestSession_TestsThatDoNotCompileRunNothing(t *testing.T) { var log bytes.Buffer got, _ := runSession(t, root, lang.SessionConfig{Log: &log}) for k, o := range got { - if o != lang.OutcomeNotRun { - t.Errorf("%s: got %v, want not_run", k, o) + if o != lang.OutcomeBaselineFailed { + t.Errorf("%s: got %v, want baseline_failed", k, o) } } if !strings.Contains(log.String(), "its instrumented tests do not build; testing its 2 mutants one build at a time") { diff --git a/internal/lang/lang.go b/internal/lang/lang.go index c77d1fc..9363319 100644 --- a/internal/lang/lang.go +++ b/internal/lang/lang.go @@ -156,17 +156,21 @@ const ( // OutcomeStoppedEarly: skipped because the tier's verdict was already // statistically settled. Excluded. OutcomeStoppedEarly + // OutcomeBaselineFailed: the tests that would judge the mutant fail + // without any mutation, so it could not be tested. Excluded; fails the gate. + OutcomeBaselineFailed ) var outcomeNames = map[MutantOutcome]string{ - OutcomeKilled: "killed", - OutcomeSurvived: "survived", - OutcomeTimedOut: "timed_out", - OutcomeNotCovered: "not_covered", - OutcomeBuildFailed: "build_failed", - OutcomeNotApplied: "not_applied", - OutcomeNotRun: "not_run", - OutcomeStoppedEarly: "stopped_early", + OutcomeKilled: "killed", + OutcomeSurvived: "survived", + OutcomeTimedOut: "timed_out", + OutcomeNotCovered: "not_covered", + OutcomeBuildFailed: "build_failed", + OutcomeNotApplied: "not_applied", + OutcomeNotRun: "not_run", + OutcomeStoppedEarly: "stopped_early", + OutcomeBaselineFailed: "baseline_failed", } // String returns the snake_case name used in reports and the result cache. diff --git a/internal/lang/lang_test.go b/internal/lang/lang_test.go index 2cae978..80c299b 100644 --- a/internal/lang/lang_test.go +++ b/internal/lang/lang_test.go @@ -67,7 +67,7 @@ func TestFileFilter_NilIsTestFile(t *testing.T) { func TestMutantOutcomeNamesRoundTrip(t *testing.T) { all := []MutantOutcome{OutcomeKilled, OutcomeSurvived, OutcomeTimedOut, OutcomeNotCovered, - OutcomeBuildFailed, OutcomeNotApplied, OutcomeNotRun, OutcomeStoppedEarly} + OutcomeBuildFailed, OutcomeNotApplied, OutcomeNotRun, OutcomeStoppedEarly, OutcomeBaselineFailed} seen := map[string]bool{} for _, o := range all { name := o.String() diff --git a/internal/mutation/cache_test.go b/internal/mutation/cache_test.go index 2377890..68be708 100644 --- a/internal/mutation/cache_test.go +++ b/internal/mutation/cache_test.go @@ -131,7 +131,7 @@ func TestCacheable(t *testing.T) { for o, want := range map[lang.MutantOutcome]bool{ lang.OutcomeKilled: true, lang.OutcomeSurvived: true, lang.OutcomeNotCovered: true, lang.OutcomeBuildFailed: true, lang.OutcomeNotApplied: true, - lang.OutcomeTimedOut: false, lang.OutcomeNotRun: false, lang.OutcomeStoppedEarly: false, lang.OutcomeUnset: false, + lang.OutcomeTimedOut: false, lang.OutcomeNotRun: false, lang.OutcomeStoppedEarly: false, lang.OutcomeBaselineFailed: false, lang.OutcomeUnset: false, } { if cacheable(o) != want { t.Errorf("cacheable(%v) = %v, want %v", o, !want, want) diff --git a/internal/mutation/run_test.go b/internal/mutation/run_test.go index e4c2519..26cdb16 100644 --- a/internal/mutation/run_test.go +++ b/internal/mutation/run_test.go @@ -355,6 +355,33 @@ func TestBuildSection_IncompleteGatingTierWarns(t *testing.T) { } } +// Mutants whose tests fail without any mutation were never judged. A gating +// tier holding any of them fails, and says which file they are in. +func TestBuildSection_BaselineFailedFailsTheGate(t *testing.T) { + section := func(operator string) report.Section { + mutants := numbered(3, operator) + mutants[0].setResult(lang.MutantResult{Outcome: lang.OutcomeKilled}) + mutants[1].setResult(lang.MutantResult{Outcome: lang.OutcomeBaselineFailed}) + mutants[2].setResult(lang.MutantResult{Outcome: lang.OutcomeBaselineFailed}) + return buildSection(mutants, Options{}) + } + for _, operator := range []string{"negate_conditional", "boolean_substitution"} { + s := section(operator) + if s.Severity != report.SeverityFail || !strings.Contains(s.Summary, "2 NOT TESTED") { + t.Errorf("%s: %v %q", operator, s.Severity, s.Summary) + } + if len(s.Findings) != 1 || !strings.Contains(s.Findings[0].Message, "NOT TESTED: 2 mutant(s)") || s.Findings[0].File != "a.go" { + t.Errorf("%s: findings = %+v", operator, s.Findings) + } + if total := s.Stats.(map[string]any)["total"]; total != 1 { + t.Errorf("%s: untested mutants must stay out of the score, total = %v", operator, total) + } + } + if s := section("statement_deletion"); s.Severity != report.SeverityPass { + t.Errorf("tier 3 is report-only: severity = %v, want PASS", s.Severity) + } +} + func TestTierSeverity_FailBeatsIncomplete(t *testing.T) { ts := TierStats{Tier: TierLogic, Total: 10, Killed: 1, Score: 10, NotRun: 5} if got := tierSeverity(ts, Options{}); got != report.SeverityFail { diff --git a/internal/mutation/section.go b/internal/mutation/section.go index 3c7b496..605da1d 100644 --- a/internal/mutation/section.go +++ b/internal/mutation/section.go @@ -86,6 +86,7 @@ func outcomeNotes(counts map[lang.MutantOutcome]int, cached int) string { {counts[lang.OutcomeBuildFailed], "do not compile (excluded)"}, {counts[lang.OutcomeNotApplied], "not applied (excluded)"}, {counts[lang.OutcomeNotRun], "NOT RUN (budget or cancelled)"}, + {counts[lang.OutcomeBaselineFailed], "NOT TESTED (their tests fail without any mutation)"}, {counts[lang.OutcomeStoppedEarly], "skipped (verdict settled early)"}, {cached, "from cache"}, } @@ -105,6 +106,8 @@ func outcomeNotes(counts map[lang.MutantOutcome]int, cached int) string { // - Tier 3 is informational only — its score is reported but does not // contribute to severity, because log/metric mutations are untestable // by design in most Go code. +// - A gating tier with mutants whose tests fail without any mutation → +// FAIL: the gate cannot vouch for code it could not test. // - A gating tier with mutants that never ran → at least WARN: the gate // did not see everything it was asked to judge. // @@ -123,7 +126,7 @@ func tieredSeverity(tiers []TierStats, opts Options) report.Severity { } // tierSeverity returns the severity contribution of a single tier: FAIL for -// Tier 1 below its threshold, WARN for Tier 2 below its threshold or for an +// Tier 1 below its threshold or for mutants whose tests fail unmutated, WARN for Tier 2 below its threshold or for an // incomplete gating tier, PASS otherwise (including Tier 3, which is // report-only). func tierSeverity(ts TierStats, opts Options) report.Severity { @@ -131,6 +134,9 @@ func tierSeverity(ts TierStats, opts Options) report.Severity { if !gated { return report.SeverityPass } + if ts.BaselineFailed > 0 { + return report.SeverityFail + } if ts.Total > 0 && ts.Score < threshold { if ts.Tier == TierLogic { return report.SeverityFail @@ -180,8 +186,29 @@ func survivedFindings(mutants []Mutant) []report.Finding { Severity: report.SeverityFail, }) } + findings = append(findings, baselineFindings(mutants)...) slices.SortStableFunc(findings, func(a, b report.Finding) int { return cmp.Or(strings.Compare(a.File, b.File), cmp.Compare(a.Line, b.Line)) }) return findings } + +// baselineFindings reports, once per file, the mutants that could not be +// tested because their tests fail without any mutation. +func baselineFindings(mutants []Mutant) []report.Finding { + perFile := map[string]int{} + for _, m := range mutants { + if m.outcome() == lang.OutcomeBaselineFailed { + perFile[m.File]++ + } + } + var findings []report.Finding + for file, n := range perFile { + findings = append(findings, report.Finding{ + File: file, + Message: fmt.Sprintf("NOT TESTED: %d mutant(s); the tests that reach them fail without any mutation", n), + Severity: report.SeverityFail, + }) + } + return findings +} diff --git a/internal/mutation/tiers.go b/internal/mutation/tiers.go index 7e38809..c96c200 100644 --- a/internal/mutation/tiers.go +++ b/internal/mutation/tiers.go @@ -91,6 +91,8 @@ type TierStats struct { Survived int `json:"survived"` // NotRun counts mutants the budget or a cancellation never reached. NotRun int `json:"not_run,omitempty"` + // BaselineFailed counts mutants whose tests fail without any mutation. + BaselineFailed int `json:"baseline_failed,omitempty"` // Score is killed / total * 100; 0 when total == 0. Score float64 `json:"score"` } @@ -117,6 +119,8 @@ func computeTierStats(mutants []Mutant) []TierStats { s.Survived++ case o == lang.OutcomeNotRun: s.NotRun++ + case o == lang.OutcomeBaselineFailed: + s.BaselineFailed++ } }