Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
52 changes: 44 additions & 8 deletions internal/lang/goanalyzer/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"os"
"path/filepath"
"regexp"
"slices"
"strconv"
"strings"
"sync"
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -124,27 +131,34 @@ 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 {
return res
}
}
}
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}
Comment thread
kamuikatsurgi marked this conversation as resolved.
Resolved
}
cfg := p.session.cfg
site := p.session.sites[idx]
Expand All @@ -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)
Comment thread
kamuikatsurgi marked this conversation as resolved.
Resolved
}

// 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)
}
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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, "|") + ")$"
}
106 changes: 70 additions & 36 deletions internal/lang/goanalyzer/session_prepare.go
Original file line number Diff line number Diff line change
Expand Up @@ -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...)
Comment thread
kamuikatsurgi marked this conversation as resolved.
Resolved
}
}

func (p *mutantPackage) fallback(ctx context.Context, why string) {
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand All @@ -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
Expand Down
Loading
Loading