// Copyright (c) Tailscale Inc & contributors // SPDX-License-Identifier: BSD-3-Clause package tailscaleroot import ( "cmp" "maps" "os" "os/exec" "slices" "strings" "testing" ) // maxTestVariants is the most packages that any one test binary may // recompile as test variants. The largest in the tree was 4 when this // limit was set. const maxTestVariants = 5 // TestTestVariantAmplification checks that no package's test binary // recompiles many other packages as test variants. // // When package P has in-package _test.go files, "go test P" compiles a // modified copy of P, and every package in the test binary that depends // on P (directly or not) is recompiled against that copy. These show up // in "go list -test -deps" as "Q [P.test]". They share no build cache // entries with normal compiles, so a test that imports something large // that depends on P (such as feature/condregister from package feature) // can add minutes of compile CPU. The fix is usually to move that test // into an external test package of a package nothing else imports, or // into a test-only leaf package. func TestTestVariantAmplification(t *testing.T) { for _, goos := range []string{"linux", "darwin", "windows"} { t.Run(goos, func(t *testing.T) { t.Parallel() cmd := exec.Command("go", "list", "-e", "-test", "-deps", "-f", "{{.ImportPath}}", "./...") cmd.Env = append(os.Environ(), "GOOS="+goos) cmd.Stderr = os.Stderr out, err := cmd.Output() if err != nil { t.Fatalf("go list: %v", err) } variants := map[string][]string{} // test package => recompiled deps for line := range strings.Lines(string(out)) { pkg, testPkg, ok := strings.Cut(strings.TrimSpace(line), " [") if !ok { continue } testPkg, ok = strings.CutSuffix(testPkg, ".test]") if !ok || pkg == testPkg || pkg == testPkg+"_test" { continue } variants[testPkg] = append(variants[testPkg], pkg) } for _, testPkg := range slices.SortedFunc(maps.Keys(variants), func(a, b string) int { return cmp.Or(cmp.Compare(len(variants[b]), len(variants[a])), cmp.Compare(a, b)) }) { deps := variants[testPkg] if len(deps) <= maxTestVariants { break } t.Errorf("%s test binary recompiles %d packages as [%s.test] variants (max %d), including %s", testPkg, len(deps), testPkg, maxTestVariants, strings.Join(deps[:5], ", ")) } }) } }