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 <bcmills@google.com>
Run-TryBot: Bryan Mills <bcmills@google.com>
gopls-CI: kokoro <noreply+kokoro@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Roland Shoemaker <roland@golang.org>
This commit is contained in:
Bryan C. Mills 2022-03-04 11:59:03 -05:00 committed by Bryan Mills
parent 19fe2d77ce
commit 0eabed704f
1 changed files with 19 additions and 45 deletions

View File

@ -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)
}