|
| 1 | +package spannertest |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os" |
| 6 | + "os/exec" |
| 7 | + "path/filepath" |
| 8 | + "runtime" |
| 9 | + "sync" |
| 10 | + "testing" |
| 11 | +) |
| 12 | + |
| 13 | +var harness struct { |
| 14 | + once sync.Once |
| 15 | + dir string // temp dir holding the binary; "" until built |
| 16 | + bin string |
| 17 | + missing string // harness project path when it is absent (skip) |
| 18 | + err error |
| 19 | +} |
| 20 | + |
| 21 | +// HarnessBinary returns the path of a harness/googlesql-spanner CLI built once |
| 22 | +// per test binary into a private temp dir, so parallel `go test -p=N` packages |
| 23 | +// never write (or exec) the same file — building into the module dir raced and |
| 24 | +// surfaced as "fork/exec ...: text file busy". The dir lives until |
| 25 | +// RemoveHarness, which the owning package's TestMain calls. Skips when the |
| 26 | +// harness project is not checked out. |
| 27 | +func HarnessBinary(t testing.TB) string { |
| 28 | + t.Helper() |
| 29 | + harness.once.Do(func() { |
| 30 | + _, thisFile, _, _ := runtime.Caller(0) |
| 31 | + // googlesql/internal/spannertest/harness.go → repo root is ../../.. |
| 32 | + repoRoot := filepath.Clean(filepath.Join(filepath.Dir(thisFile), "..", "..", "..")) |
| 33 | + projDir := filepath.Join(repoRoot, "harness", "googlesql-spanner") |
| 34 | + if _, err := os.Stat(projDir); err != nil { |
| 35 | + harness.missing = projDir |
| 36 | + return |
| 37 | + } |
| 38 | + dir, err := os.MkdirTemp("", "googlesql-spanner-harness-") |
| 39 | + if err != nil { |
| 40 | + harness.err = fmt.Errorf("temp dir for harness: %w", err) |
| 41 | + return |
| 42 | + } |
| 43 | + harness.dir = dir |
| 44 | + bin := filepath.Join(dir, "googlesql-spanner") |
| 45 | + build := exec.Command("go", "build", "-o", bin, ".") |
| 46 | + build.Dir = projDir |
| 47 | + if out, err := build.CombinedOutput(); err != nil { |
| 48 | + harness.err = fmt.Errorf("building harness: %w\n%s", err, out) |
| 49 | + return |
| 50 | + } |
| 51 | + harness.bin = bin |
| 52 | + }) |
| 53 | + if harness.missing != "" { |
| 54 | + t.Skipf("harness project not found at %s", harness.missing) |
| 55 | + } |
| 56 | + if harness.err != nil { |
| 57 | + t.Fatal(harness.err) |
| 58 | + } |
| 59 | + return harness.bin |
| 60 | +} |
| 61 | + |
| 62 | +// RemoveHarness deletes the temp dir HarnessBinary built into. Call it from |
| 63 | +// TestMain after m.Run(); it is a no-op when nothing was built. |
| 64 | +func RemoveHarness() { |
| 65 | + if harness.dir != "" { |
| 66 | + _ = os.RemoveAll(harness.dir) |
| 67 | + } |
| 68 | +} |
0 commit comments