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
103 changes: 95 additions & 8 deletions internal/mutate/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,9 @@ func RunAll(chosen []Mutation, importers map[string][]string, timeout string, jo
// time, beside the test processes.
b := &builds{sem: make(chan struct{}, 1), work: work, bins: map[string]*importerBinary{}}
covers := &coverages{by: map[string]*coverage{}, timeout: timeout, slots: slots}
byDir := map[string][]Mutation{}
var dirs []string
for _, m := range chosen {
dir := filepath.Dir(m.File)
if byDir[dir] == nil {
dirs = append(dirs, dir)
}
byDir[dir] = append(byDir[dir], m)
byDir, dirs := byPackage(chosen)
if broken, err := brokenImporters(dirs, importers, timeout, slots); err != nil {
return Tally{Broken: broken}, err
}
results := make(chan result)
var wg sync.WaitGroup
Expand Down Expand Up @@ -136,6 +131,98 @@ func RunAll(chosen []Mutation, importers map[string][]string, timeout string, jo
return t, firstErr
}

// byPackage is chosen by the directory of its package, and those directories in the order chosen
// first names them.
func byPackage(chosen []Mutation) (map[string][]Mutation, []string) {
byDir := map[string][]Mutation{}
var dirs []string
for _, m := range chosen {
dir := filepath.Dir(m.File)
if byDir[dir] == nil {
dirs = append(dirs, dir)
}
byDir[dir] = append(byDir[dir], m)
}
return byDir, dirs
}

// brokenImporters runs the tests of every importer of dirs once, on the code as it is, each in one
// of slots' trees, and fails naming each test that fails as "<importer>: <test>", sorted. A package's own tests
// are measured that way (Cover), and one that fails is asked about no edit; an importer's are
// asked whole, so one that fails regardless refuses every edit asked of it, and the run reports
// none survived. One that does not build asks nothing either way, and is not named.
func brokenImporters(dirs []string, importers map[string][]string, timeout string, slots chan *Tree) ([]string, error) {
seen := map[string]bool{}
for _, dir := range dirs {
for _, importer := range importers[filepath.ToSlash(dir)] {
seen[importer] = true
}
}
if len(seen) == 0 {
return nil, nil
}
root, err := moduleRoot(".")
if err != nil {
return nil, err
}
var (
mu sync.Mutex
broken []string
firstErr error
wg sync.WaitGroup
)
for importer := range seen {
wg.Go(func() {
tree := <-slots
defer func() { slots <- tree }()
var said strings.Builder
outcome, err := runPackage(tree, importer, filepath.Join(root, importer), root, "an importer's tests, unbroken",
nil, timeout, "", &said)
mu.Lock()
defer mu.Unlock()
if err != nil {
firstErr = cmp.Or(firstErr, err)
return
}
if outcome != Killed && outcome != Exceeded {
return
}
// mutate-exempt: how much of the failure is shown, not whether it is.
fmt.Fprintf(os.Stderr, " (%s fails with nothing broken:)\n%s\n", importer, tail([]byte(said.String()), 20))
failed := failedTests(said.String())
if len(failed) == 0 {
failed = []string{"its test binary, which named no test"}
}
for _, test := range failed {
broken = append(broken, importer+": "+test)
}
})
}
wg.Wait()
if firstErr != nil {
return nil, firstErr
}
if len(broken) == 0 {
return nil, nil
}
slices.Sort(broken)
return broken, fmt.Errorf("mutate: %d importer test(s) fail with nothing broken, so they would refuse every edit "+
"asked of them: %s. Each failed in this run's copy of the module, as said above: fix it so that it passes there",
len(broken), strings.Join(broken, ", "))
}

// failedTests is the top-level tests a test binary's -test.v output says failed, in order.
func failedTests(out string) []string {
var failed []string
for line := range strings.SplitSeq(out, "\n") {
if rest, ok := strings.CutPrefix(line, "--- FAIL: "); ok {
name, _, _ := strings.Cut(rest, " ")
failed = append(failed, name)
}
}
return failed
}

// pkgRun is one package's mutations put to the tests.
type pkgRun struct {
dir, work, timeout string
Expand Down
33 changes: 33 additions & 0 deletions internal/mutate/runner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,39 @@ func TestATestThatAlwaysFailsRefusesNothing(t *testing.T) {
assert.Len(t, tally.Survived, 2, "every edit is still asked, and said: %s", said.String())
}

// An importer's test that fails with nothing broken would refuse every edit asked of it, and the
// run would report none survived: an always-failing test in spin-stack/machine#418 gave
// "0 survived" on every run, all of them invalid. Each importer's tests are run once on the code
// as it is before any edit, and the run refuses to start, naming the test.
func TestAnImporterTestThatAlwaysFailsStopsTheRunBeforeAnyEdit(t *testing.T) {
dir := t.TempDir()
for name, body := range map[string]string{
"go.mod": "module example.com/importerbroken\n\ngo 1.24\n",
"lib/lib.go": "package lib\n\nfunc Double(n int) int {\n\treturn n + n\n}\n",
"lib/lib_test.go": "package lib\n\nimport \"testing\"\n\nfunc TestRuns(t *testing.T) {\n\t_ = Double(2)\n}\n",
"use/use.go": "package use\n\nimport \"example.com/importerbroken/lib\"\n\nfunc Four() int { return lib.Double(2) }\n",
"use/use_test.go": "package use\n\nimport \"testing\"\n\nfunc TestFour(t *testing.T) {\n\t_ = Four()\n}\n\n" +
"func TestBroken(t *testing.T) {\n\tt.Fatal(\"broken regardless\")\n}\n",
} {
require.NoError(t, os.MkdirAll(filepath.Join(dir, filepath.Dir(name)), 0o700))
require.NoError(t, os.WriteFile(filepath.Join(dir, name), []byte(body), 0o600))
}
t.Chdir(dir)
plan, err := mutate.Plan(filepath.Join("lib", "lib.go"), map[int]bool{4: true})
require.NoError(t, err)
require.NotEmpty(t, plan)
for i := range plan {
plan[i].ID = i + 1
}
var said strings.Builder
tally, err := mutate.RunAll(plan, map[string][]string{"lib": {"./use"}}, "2m", 2, &said)
require.Error(t, err, "a run whose importer has a test that fails with nothing broken started: %s", said.String())
assert.Contains(t, err.Error(), "./use: TestBroken")
assert.Equal(t, []string{"./use: TestBroken"}, tally.Broken)
assert.Zero(t, tally.Killed, "an edit was asked, and refused by a test broken regardless: %s", said.String())
assert.NotContains(t, said.String(), "refused", "an edit was asked before the importers were: %s", said.String())
}

// A package with no tests of its own is asked through the packages that import it, each built
// once: Double's edits are refused by the importer's test and Half's, which it never calls, are not.
func TestAPackageWithNoTestsIsAskedThroughItsImporters(t *testing.T) {
Expand Down
5 changes: 5 additions & 0 deletions site/src/content/docs/mutate.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,11 @@ run still asks every edit and prints the test's output, then exits 2 naming the
test. A pass here would be a green check over a failing test. The fix is the test's: what it reads
that the copy doesn't have, or a path it shares with a test run beside it.

The packages that import the one being broken are checked the same way. Before the first edit,
`mutate` runs each importer's tests once on your code as it is. If one fails, the run stops
there and exits 2, naming the importer and the test. Asked anyway, that test would refuse every
edit put to it, and the run would report `0 survived` over a broken test.

### Tests that need an environment

`mutate` runs your tests as `go test` would, in the environment it was started in. Anything they
Expand Down