From 0eabed704f2d723cd00636d70e3a8eb57134fbfa Mon Sep 17 00:00:00 2001 From: "Bryan C. Mills" Date: Fri, 4 Mar 2022 11:59:03 -0500 Subject: [PATCH] cmd/file2fuzz: exec main from TestMain instead of running 'go build' in tests This may address a test hang observed in https://build.golang.org/log/da703ece9e1626eaeabf485e1a3a8180a6bde512. At the very least, it should make the test much more efficient. Change-Id: I6a41f9704c8a95276c904f0aee57c4521d642ea7 Reviewed-on: https://go-review.googlesource.com/c/tools/+/390074 Trust: Bryan Mills Run-TryBot: Bryan Mills gopls-CI: kokoro TryBot-Result: Gopher Robot Reviewed-by: Roland Shoemaker --- cmd/file2fuzz/main_test.go | 64 +++++++++++--------------------------- 1 file changed, 19 insertions(+), 45 deletions(-) diff --git a/cmd/file2fuzz/main_test.go b/cmd/file2fuzz/main_test.go index 55d824cf9e..fe2c103c28 100644 --- a/cmd/file2fuzz/main_test.go +++ b/cmd/file2fuzz/main_test.go @@ -5,67 +5,41 @@ package main import ( - "fmt" "io/ioutil" "os" "os/exec" "path/filepath" - "runtime" "strings" "sync" "testing" ) -// The setup for this test is mostly cribbed from x/exp/txtar. +func TestMain(m *testing.M) { + if os.Getenv("GO_FILE2FUZZ_TEST_IS_FILE2FUZZ") != "" { + main() + os.Exit(0) + } -var buildBin struct { + os.Exit(m.Run()) +} + +var f2f struct { once sync.Once - name string + path string err error } -func binPath(t *testing.T) string { - t.Helper() - if _, err := exec.LookPath("go"); err != nil { - t.Skipf("cannot build file2fuzz binary: %v", err) - } - - buildBin.once.Do(func() { - exe, err := ioutil.TempFile("", "file2fuzz-*.exe") - if err != nil { - buildBin.err = err - return - } - exe.Close() - buildBin.name = exe.Name() - - cmd := exec.Command("go", "build", "-o", buildBin.name, ".") - out, err := cmd.CombinedOutput() - if err != nil { - buildBin.err = fmt.Errorf("%s: %v\n%s", strings.Join(cmd.Args, " "), err, out) - } - }) - - if buildBin.err != nil { - if runtime.GOOS == "android" { - t.Skipf("skipping test after failing to build file2fuzz binary: go_android_exec may have failed to copy needed dependencies (see https://golang.org/issue/37088)") - } - t.Fatal(buildBin.err) - } - return buildBin.name -} - -func TestMain(m *testing.M) { - os.Exit(m.Run()) - if buildBin.name != "" { - os.Remove(buildBin.name) - } -} - func file2fuzz(t *testing.T, dir string, args []string, stdin string) (string, bool) { - t.Helper() - cmd := exec.Command(binPath(t), args...) + f2f.once.Do(func() { + f2f.path, f2f.err = os.Executable() + }) + if f2f.err != nil { + t.Fatal(f2f.err) + } + + cmd := exec.Command(f2f.path, args...) cmd.Dir = dir + cmd.Env = append(os.Environ(), "PWD="+dir, "GO_FILE2FUZZ_TEST_IS_FILE2FUZZ=1") if stdin != "" { cmd.Stdin = strings.NewReader(stdin) }