e2e/bin_test.go

e6cd75b5f28bacf51620bb531320c30fd4e66bfd
gitbay/e2e/bin_test.go history · blame · raw

67 lines · 2040 bytes

10 symbols in this file
 1package e2e
 2
 3import (
 4	"os"
 5	"os/exec"
 6	"path/filepath"
 7	"sync"
 8	"testing"
 9)
10
11// The suite starts an instance per test, and each one needs gitbayd. Built
12// per test, that is 200-odd links of a byte-identical 35MB binary: go's
13// build cache covers the compile but not the final link, so it cost about
14// 0.8s every time, a quarter of the whole run.
15//
16// Built once per process instead, under a directory TestMain owns. The
17// binaries outlive any single test, so t.TempDir is the wrong home for
18// them — it is removed when the test that asked for it ends.
19var (
20	gitbaydBin = &builtBin{name: "gitbayd", pkg: "gitbay.org/gitbay/cmd/gitbayd"}
21	gitbayBin  = &builtBin{name: "gitbay", pkg: "gitbay.org/gitbay/cmd/gitbay"}
22	runnerBin  = &builtBin{name: "gitbay-runner", pkg: "gitbay.org/gitbay/cmd/gitbay-runner"}
23)
24
25// binDir is where the built binaries live, set by TestMain.
26var binDir string
27
28type builtBin struct {
29	name string
30	pkg  string
31
32	once sync.Once
33	path string
34	out  []byte
35	err  error
36}
37
38// get builds the binary on first use and returns the same path thereafter.
39// Lazily, so `-run TestOneThing` does not link the two binaries it has no
40// use for.
41func (b *builtBin) get(t *testing.T) string {
42	t.Helper()
43	b.once.Do(func() {
44		b.path = filepath.Join(binDir, b.name)
45		cmd := exec.Command("go", "build", "-o", b.path, b.pkg)
46		cmd.Dir = ".."
47		b.out, b.err = cmd.CombinedOutput()
48	})
49	if b.err != nil {
50		t.Fatalf("build %s: %v\n%s", b.name, b.err, b.out)
51	}
52	return b.path
53}
54
55func buildGitbayd(t *testing.T) string   { return gitbaydBin.get(t) }
56func buildGitbayCLI(t *testing.T) string { return gitbayBin.get(t) }
57func buildRunner(t *testing.T) string    { return runnerBin.get(t) }
58
59// makeBinDir is called by TestMain. Returned rather than deferred because
60// TestMain ends in os.Exit, which runs no deferred functions.
61func makeBinDir() (dir string, cleanup func(), err error) {
62	dir, err = os.MkdirTemp("", "e2e-bin")
63	if err != nil {
64		return "", func() {}, err
65	}
66	return dir, func() { os.RemoveAll(dir) }, nil
67}