diff --git a/cmd/testwrapper/multipkg_test.go b/cmd/testwrapper/multipkg_test.go new file mode 100644 index 000000000..defe6e65b --- /dev/null +++ b/cmd/testwrapper/multipkg_test.go @@ -0,0 +1,209 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +package main_test + +import ( + "bytes" + "os" + "path/filepath" + "strings" + "testing" +) + +// multiPkgDir creates a temporary directory for test packages under +// testdata, so the packages are inside this module but ignored by +// "./..." patterns if a test ever leaks them. +func multiPkgDir(t *testing.T) string { + t.Helper() + dir, err := os.MkdirTemp("testdata", "multipkg-") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(dir) }) + return dir +} + +// writePkg writes a test-only package named name under dir with the +// given test source and returns its relative package pattern. +func writePkg(t *testing.T, dir, name, src string) string { + t.Helper() + pkgDir := filepath.Join(dir, name) + if err := os.MkdirAll(pkgDir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(pkgDir, name+"_test.go"), []byte(src), 0o644); err != nil { + t.Fatal(err) + } + return "./" + filepath.ToSlash(pkgDir) +} + +// importPath returns the import path of a package written by writePkg. +func importPath(pattern string) string { + return "tailscale.com/cmd/testwrapper/" + strings.TrimPrefix(pattern, "./") +} + +// firstPassRuns returns the debug "running ..." lines for first-pass +// go test invocations, which unlike retries have no --run flag. +func firstPassRuns(out []byte) []string { + var runs []string + for _, line := range strings.Split(string(out), "\n") { + if strings.HasPrefix(line, "running test") && !strings.Contains(line, "--run") { + runs = append(runs, line) + } + } + return runs +} + +const passSrc = `package pass_test + +import "testing" + +func TestPass(t *testing.T) {} +` + +const flakySrc = `package flaky_test + +import ( + "os" + "testing" +) + +func TestFlaky(t *testing.T) { + if os.Getenv("TS_TESTWRAPPER_ATTEMPT") == "1" { + t.Fatal("failing on the first attempt so the wrapper retries") + } +} +` + +const failSrc = `package fail_test + +import "testing" + +func TestAlwaysFails(t *testing.T) { t.Fatal("nope") } +` + +// TestMultiPackage covers several package patterns on one command line: +// the first pass must be a single go test invocation naming all of +// them, and results, flake retries, and permanent failures must still be +// attributed to the right package. +func TestMultiPackage(t *testing.T) { + t.Parallel() + + dir := multiPkgDir(t) + passPkg := writePkg(t, dir, "pass", passSrc) + flakyPkg := writePkg(t, dir, "flaky", flakySrc) + failPkg := writePkg(t, dir, "fail", failSrc) + + cmd := cmdTestwrapper(t, passPkg, flakyPkg, failPkg) + cmd.Env = append(cmd.Env, "TS_TESTWRAPPER_DEBUG=1") + out, err := cmd.CombinedOutput() + if code, ok := errExitCode(err); !ok || code != 1 { + t.Fatalf("got exit code %d, want 1 (err: %v) with output:\n%s", code, err, out) + } + + runs := firstPassRuns(out) + if len(runs) != 1 { + t.Errorf("got %d first-pass go test invocations, want 1:\n%s\noutput:\n%s", len(runs), strings.Join(runs, "\n"), out) + } else { + for _, p := range []string{passPkg, flakyPkg, failPkg} { + if !strings.Contains(runs[0], " "+p+" ") { + t.Errorf("first-pass invocation %q lacks package %q", runs[0], p) + } + } + } + + for _, want := range []string{ + "ok\t" + importPath(passPkg), + "FAIL\t" + importPath(flakyPkg), // first pass fails; the retry is per test + "FAIL\t" + importPath(failPkg), + "flakytest failures JSON:", + "permanent test failures JSON:", + } { + if !bytes.Contains(out, []byte(want)) { + t.Errorf("output lacks %q:\n%s", want, out) + } + } + flakyLine, permLine := jsonLines(out) + if !strings.Contains(flakyLine, importPath(flakyPkg)) || !strings.Contains(flakyLine, "TestFlaky") { + t.Errorf("flaky failures JSON %q should name %s TestFlaky", flakyLine, importPath(flakyPkg)) + } + if !strings.Contains(permLine, importPath(failPkg)) || !strings.Contains(permLine, "TestAlwaysFails") { + t.Errorf("permanent failures JSON %q should name %s TestAlwaysFails", permLine, importPath(failPkg)) + } + if strings.Contains(permLine, "TestFlaky") || strings.Contains(flakyLine, "TestAlwaysFails") { + t.Errorf("failures attributed to the wrong list:\nflaky: %s\npermanent: %s", flakyLine, permLine) + } +} + +// jsonLines returns the flakytest and permanent failures JSON lines +// from testwrapper output, or "" for each that is absent. +func jsonLines(out []byte) (flaky, permanent string) { + for _, line := range strings.Split(string(out), "\n") { + if strings.HasPrefix(line, "flakytest failures JSON:") { + flaky = line + } + if strings.HasPrefix(line, "permanent test failures JSON:") { + permanent = line + } + } + return flaky, permanent +} + +// TestMultiPackageBuildError covers a build error in one package of a +// batch: the other packages still run and report, and the wrapper +// exits with go test's exit code. +func TestMultiPackageBuildError(t *testing.T) { + t.Parallel() + + dir := multiPkgDir(t) + passPkg := writePkg(t, dir, "pass", passSrc) + brokenPkg := writePkg(t, dir, "broken", "package broken_test\n\nderp\n") + + out, err := cmdTestwrapper(t, passPkg, brokenPkg).CombinedOutput() + if code, ok := errExitCode(err); !ok || code != 1 { + t.Fatalf("got exit code %d, want 1 (err: %v) with output:\n%s", code, err, out) + } + for _, want := range []string{ + "ok\t" + importPath(passPkg), + "expected declaration, found derp", + } { + if !bytes.Contains(out, []byte(want)) { + t.Errorf("output lacks %q:\n%s", want, out) + } + } +} + +// TestMultiFile covers several .go file arguments: each is its own +// "command-line-arguments" package, so each gets its own first-pass +// invocation and retries target the right file. +func TestMultiFile(t *testing.T) { + t.Parallel() + + dir := t.TempDir() + fileA := filepath.Join(dir, "a_test.go") + fileB := filepath.Join(dir, "b_test.go") + if err := os.WriteFile(fileA, []byte(passSrc), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(fileB, []byte(flakySrc), 0o644); err != nil { + t.Fatal(err) + } + + cmd := cmdTestwrapper(t, fileA, fileB) + cmd.Env = append(cmd.Env, "TS_TESTWRAPPER_DEBUG=1") + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("testwrapper: %v with output:\n%s", err, out) + } + if runs := firstPassRuns(out); len(runs) != 2 { + t.Errorf("got %d first-pass go test invocations, want 2 (one per file):\n%s\noutput:\n%s", len(runs), strings.Join(runs, "\n"), out) + } + wantRetry := fileB + " --run ^(TestFlaky)$" + if !bytes.Contains(out, []byte(wantRetry)) { + t.Errorf("output lacks retry of %q:\n%s", wantRetry, out) + } + if bytes.Contains(out, []byte("permanent test failures JSON:")) { + t.Errorf("unexpected permanent failures:\n%s", out) + } +} diff --git a/cmd/testwrapper/testwrapper.go b/cmd/testwrapper/testwrapper.go index 4bcbca760..57e699665 100644 --- a/cmd/testwrapper/testwrapper.go +++ b/cmd/testwrapper/testwrapper.go @@ -263,28 +263,29 @@ func testFuncNames(path string) ([]string, error) { return names, sc.Err() } -// runTests runs the tests in pt and sends the results on ch. It sends a -// testAttempt for each test and a final testAttempt per pkg with pkgFinished -// set to true. Package build errors will not emit a testAttempt (as no valid -// JSON is produced) but the [os/exec.ExitError] will be returned. +// runTests runs the tests in the packages matching patterns in a single +// "go test" invocation and sends the results on ch. It sends a testAttempt +// for each test and a final testAttempt per pkg with pkgFinished set to +// true. Package build errors will not emit a testAttempt (as no valid JSON +// is produced) but the [os/exec.ExitError] will be returned. // It calls close(ch) when it's done. -func runTests(ctx context.Context, attempt int, pt *packageTests, goTestArgs, testArgs []string, ch chan<- *testAttempt) error { +func runTests(ctx context.Context, attempt int, patterns []string, goTestArgs, testArgs []string, ch chan<- *testAttempt) error { defer close(ch) args := []string{"test"} args = append(args, goTestArgs...) - args = append(args, pt.Pattern) - if len(pt.Tests) > 0 { - // Specific tests requested (e.g. flaky test retry). - runArg := strings.Join(pt.Tests, "|") - args = append(args, "--run", runArg) - } else if shardSpec := os.Getenv("TS_TEST_SHARD"); shardSpec != "" { + args = append(args, patterns...) + if shardSpec := os.Getenv("TS_TEST_SHARD"); shardSpec != "" { // Automatic test-name sharding: list tests and filter by hash. - shardTests, err := testsForShard(ctx, pt.Pattern, shardSpec) + if len(patterns) != 1 { + return fmt.Errorf("TS_TEST_SHARD requires a single package pattern per go test invocation; got %q", patterns) + } + pattern := patterns[0] + shardTests, err := testsForShard(ctx, pattern, shardSpec) if err != nil { return err } if len(shardTests) == 0 { - ch <- &testAttempt{pkg: pt.Pattern, outcome: outcomeSkip, pkgFinished: true} + ch <- &testAttempt{pkg: pattern, outcome: outcomeSkip, pkgFinished: true} return nil } quoted := make([]string, len(shardTests)) @@ -811,6 +812,12 @@ func buildPackageTests(fts []*failedTest, fakeRepo string) []packageTests { return out } +// isGoFile reports whether arg names a Go source file rather than a +// package pattern. +func isGoFile(arg string) bool { + return strings.HasSuffix(arg, ".go") +} + func main() { goTestArgs, packages, testArgs, err := splitArgs(os.Args[1:]) if err != nil { @@ -860,21 +867,34 @@ func main() { } // First pass: run every package once, collect failed tests for retry. + // + // All package patterns go to one "go test" invocation so the go + // command can build, link, and run them in parallel, exactly as it + // does for a single "./..." pattern. Test-name sharding lists tests + // per package, and .go file arguments each form their own + // "command-line-arguments" package, so those keep one invocation + // per argument. + batches := [][]string{packages} + if os.Getenv("TS_TEST_SHARD") != "" || slices.ContainsFunc(packages, isGoFile) { + batches = nil + for _, p := range packages { + batches = append(batches, []string{p}) + } + } var failed []*failedTest var pkgFatal bool // a package produced a non-test fatal (build error, etc.) resultsSummary := os.Getenv("TS_TESTWRAPPER_RESULTS_SUMMARY") != "" allResults := map[string]testOutcome{} - for _, pkgPattern := range packages { - pt := &packageTests{Pattern: pkgPattern} + for _, patterns := range batches { ch := make(chan *testAttempt) runErrCh := make(chan error, 1) go func() { defer close(runErrCh) - runErrCh <- runTests(ctx, 1, pt, goTestArgs, testArgs, ch) + runErrCh <- runTests(ctx, 1, patterns, goTestArgs, testArgs, ch) }() - // Collect failed tests in this package on the side; we use the count + // Collect failed tests in this batch on the side; we use the count // when a package reports a fail to decide if the failure is explained // by retryable test failures or is a separate package-level fatal. var pkgFailedTests []*failedTest @@ -882,9 +902,11 @@ func main() { // Go assigns the package name "command-line-arguments" when you // `go test FILE` rather than `go test PKG`. It's more // convenient for us to specify files in tests, so fix tr.pkg - // so that subsequent testwrapper attempts run correctly. + // so that subsequent testwrapper attempts run correctly. File + // arguments always run one per batch, so the batch's only + // pattern is the file. if tr.pkg == "command-line-arguments" { - tr.pkg = packages[0] + tr.pkg = patterns[0] } if tr.pkgFinished { if tr.raceDetected {