diff --git a/cmd/bd/cli_fast_test.go b/cmd/bd/cli_fast_test.go index 6ecabd91c..31e3576b1 100644 --- a/cmd/bd/cli_fast_test.go +++ b/cmd/bd/cli_fast_test.go @@ -144,6 +144,38 @@ func createTempDirWithCleanup(t *testing.T) string { return tmpDir } +// restoreEnvSnapshot puts the process environment back to before, a prior +// os.Environ(), touching only the keys that differ. An in-process +// rootCmd.Execute mutates the environment with raw os.Setenv and restores +// nothing (PersistentPreRun exports the selected workspace as BEADS_DIR, +// loads the workspace's .beads/.env, ...); left in place, the BEADS_DIR of a +// since-deleted fixture makes every later test's workspace discovery report +// "no active beads workspace found" (e.g. TestResolvedConfigRepoRoot). +func restoreEnvSnapshot(before []string) { + want := make(map[string]string, len(before)) + for _, kv := range before { + if k, v, ok := strings.Cut(kv, "="); ok && k != "" { + want[k] = v + } + } + for _, kv := range os.Environ() { + k, v, ok := strings.Cut(kv, "=") + if !ok || k == "" { + continue + } + if old, had := want[k]; !had { + _ = os.Unsetenv(k) + } else if old != v { + _ = os.Setenv(k, old) + } + } + for k, v := range want { + if _, ok := os.LookupEnv(k); !ok { + _ = os.Setenv(k, v) + } + } +} + // runBDInProcess runs bd commands in-process by calling rootCmd.Execute // This is ~10-20x faster than exec.Command because it avoids process spawn overhead func runBDInProcess(t *testing.T, dir string, args ...string) string { @@ -180,7 +212,9 @@ func runBDInProcess(t *testing.T, dir string, args ...string) string { os.Args = append([]string{"bd"}, args...) // Execute command + envBefore := os.Environ() err := rootCmd.Execute() + restoreEnvSnapshot(envBefore) // Close and clean up all global state to prevent contamination between tests if store != nil { @@ -1042,7 +1076,7 @@ func init() { panic(err) } testBD = filepath.Join(tmpDir, bdBinary) - cmd := exec.Command("go", "build", "-tags", "gms_pure_go", "-o", testBD, ".") + cmd := goBuildBDCommand(testBD) if out, err := cmd.CombinedOutput(); err != nil { panic(string(out)) } @@ -1234,7 +1268,9 @@ func runBDInProcessAllowError(t *testing.T, dir string, args ...string) (string, rootCmd.SetArgs(args) os.Args = append([]string{"bd"}, args...) + envBefore := os.Environ() cmdErr := rootCmd.Execute() + restoreEnvSnapshot(envBefore) if store != nil { store.Close() diff --git a/cmd/bd/config_test.go b/cmd/bd/config_test.go index 3b8ad0ad5..2713083a7 100644 --- a/cmd/bd/config_test.go +++ b/cmd/bd/config_test.go @@ -758,6 +758,10 @@ func TestResolvedConfigRepoRoot(t *testing.T) { t.Fatalf("Failed to create sub dir: %v", err) } + // CWD discovery is what is under test: an inherited BEADS_DIR + // (a developer's shell, or one an earlier in-process command + // exported) would take precedence and fail the lookup. + t.Setenv("BEADS_DIR", "") t.Chdir(subDir) resetResolutionCaches(t) @@ -802,6 +806,7 @@ func TestResolvedConfigRepoRoot(t *testing.T) { t.Fatalf("Failed to create bare metadata.json: %v", err) } + t.Setenv("BEADS_DIR", "") // as above: discovery, not BEADS_DIR, is under test t.Chdir(worktreeDir) resetResolutionCaches(t) diff --git a/cmd/bd/delete_test.go b/cmd/bd/delete_test.go index c29f8672e..d4358116a 100644 --- a/cmd/bd/delete_test.go +++ b/cmd/bd/delete_test.go @@ -5,11 +5,13 @@ package main import ( "context" + "errors" "os/exec" "path/filepath" "strings" "testing" + "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/issueops" ) @@ -211,13 +213,11 @@ func TestDeleteIssueWrapper(t *testing.T) { t.Fatalf("deleteIssue failed: %v", err) } - // Verify issue is gone + // Verify issue is gone: GetIssue reports a missing issue as + // storage.ErrNotFound. deleted, err := s.GetIssue(ctx, issue.ID) - if err != nil { - t.Fatalf("GetIssue failed: %v", err) - } - if deleted != nil { - t.Error("Issue should be completely deleted") + if !errors.Is(err, storage.ErrNotFound) { + t.Fatalf("GetIssue after delete: got (%v, %v), want storage.ErrNotFound", deleted, err) } }) @@ -309,25 +309,3 @@ func TestDeleteIssueWrapper(t *testing.T) { } }) } - -func TestDeleteIssueUnsupportedStorage(t *testing.T) { - if testDoltServerPort == 0 { - t.Skip("skipping: Dolt test container not available") - } - - oldStore := store - defer func() { store = oldStore }() - - // Set store to nil - the type assertion will fail - store = nil - - ctx := context.Background() - err := deleteIssue(ctx, "any-id") - if err == nil { - t.Error("Expected error when storage is nil") - } - expectedMsg := "delete operation not supported by this storage backend" - if err.Error() != expectedMsg { - t.Errorf("Expected error %q, got %q", expectedMsg, err.Error()) - } -} diff --git a/cmd/bd/doctor_repair_test.go b/cmd/bd/doctor_repair_test.go index 7ee8e10d6..81180f88a 100644 --- a/cmd/bd/doctor_repair_test.go +++ b/cmd/bd/doctor_repair_test.go @@ -22,7 +22,7 @@ func buildBDForTest(t *testing.T) string { binDir := t.TempDir() exe := filepath.Join(binDir, exeName) - cmd := exec.Command("go", "build", "-tags", "gms_pure_go", "-o", exe, ".") + cmd := goBuildBDCommand(exe) out, err := cmd.CombinedOutput() if err != nil { t.Fatalf("go build failed: %v\n%s", err, string(out)) diff --git a/cmd/bd/explicit_db_nodb_test.go b/cmd/bd/explicit_db_nodb_test.go index 93d721fa5..17c58f017 100644 --- a/cmd/bd/explicit_db_nodb_test.go +++ b/cmd/bd/explicit_db_nodb_test.go @@ -52,7 +52,7 @@ func buildBDUnderTest(t *testing.T) string { binName = "bd.exe" } buildBDPath = filepath.Join(dir, binName) - buildCmd := exec.Command("go", "build", "-tags", "gms_pure_go", "-o", buildBDPath, ".") + buildCmd := goBuildBDCommand(buildBDPath) if out, err := buildCmd.CombinedOutput(); err != nil { buildBDErr = &buildBDError{err: err, output: out} return diff --git a/cmd/bd/init_embedded_test.go b/cmd/bd/init_embedded_test.go index 9f961b835..730d2e6bd 100644 --- a/cmd/bd/init_embedded_test.go +++ b/cmd/bd/init_embedded_test.go @@ -95,7 +95,7 @@ func buildEmbeddedBD(t *testing.T) string { name = "bd.exe" } embeddedBD = filepath.Join(tmpDir, name) - cmd := exec.Command("go", "build", "-tags", "gms_pure_go", "-o", embeddedBD, ".") + cmd := goBuildBDCommand(embeddedBD) if out, err := cmd.CombinedOutput(); err != nil { embeddedBDErr = fmt.Errorf("go build failed: %v\n%s", err, out) } diff --git a/cmd/bd/init_permissions_test.go b/cmd/bd/init_permissions_test.go index abdd711bb..0b27f435a 100644 --- a/cmd/bd/init_permissions_test.go +++ b/cmd/bd/init_permissions_test.go @@ -37,7 +37,7 @@ func buildBDForInitPermissionTests(t *testing.T) string { return } initPermissionTestBD = filepath.Join(tmpDir, "bd") - cmd := exec.Command("go", "build", "-tags", "gms_pure_go", "-o", initPermissionTestBD, ".") + cmd := goBuildBDCommand(initPermissionTestBD) if out, err := cmd.CombinedOutput(); err != nil { initPermissionTestBDErr = fmt.Errorf("go build failed: %v\n%s", err, out) } diff --git a/cmd/bd/migrate_dolt_mode_frontdoor_integration_test.go b/cmd/bd/migrate_dolt_mode_frontdoor_integration_test.go index 51d8f6f51..7b0862527 100644 --- a/cmd/bd/migrate_dolt_mode_frontdoor_integration_test.go +++ b/cmd/bd/migrate_dolt_mode_frontdoor_integration_test.go @@ -75,8 +75,8 @@ func migrationFrontDoorBinary(t *testing.T) string { return p } out := filepath.Join(t.TempDir(), "bd") - cmd := exec.Command("go", "build", "-o", out, ".") - cmd.Dir = "." + cmd := exec.Command("go", "build", "-o", out, bdModulePackage) + cmd.Dir = bdSourceDir if b, err := cmd.CombinedOutput(); err != nil { t.Fatalf("build cgo bd: %v\n%s", err, b) } diff --git a/cmd/bd/scripttest_test.go b/cmd/bd/scripttest_test.go index b02ba9391..76fb57651 100644 --- a/cmd/bd/scripttest_test.go +++ b/cmd/bd/scripttest_test.go @@ -6,7 +6,6 @@ package main import ( "context" "os" - "os/exec" "path/filepath" "runtime" "testing" @@ -32,7 +31,7 @@ func TestScripts(t *testing.T) { if prebuilt, err := findPrebuiltBDBinary(); err == nil && prebuilt != "" && filepath.Base(prebuilt) == exeName { exe = prebuilt binDir = filepath.Dir(prebuilt) - } else if err := exec.Command("go", "build", "-tags", "gms_pure_go", "-o", exe, ".").Run(); err != nil { + } else if err := goBuildBDCommand(exe).Run(); err != nil { t.Fatal(err) } diff --git a/cmd/bd/shared_server_integration_test.go b/cmd/bd/shared_server_integration_test.go index f5d02d392..09a777436 100644 --- a/cmd/bd/shared_server_integration_test.go +++ b/cmd/bd/shared_server_integration_test.go @@ -611,19 +611,13 @@ func buildSharedServerTestBinary(t *testing.T) string { sharedServerBdBinary = prebuilt return } - pkgDir, err := os.Getwd() - if err != nil { - sharedServerBuildErr = fmt.Errorf("getwd: %w", err) - return - } buildDir, err := testTempDir("beads-shared-server-bd-*") if err != nil { sharedServerBuildErr = fmt.Errorf("mkdirtemp: %w", err) return } bdBin := filepath.Join(buildDir, "bd") - cmd := exec.Command("go", "build", "-tags", "gms_pure_go", "-o", bdBin, ".") - cmd.Dir = pkgDir + cmd := goBuildBDCommand(bdBin) cmd.Env = append(os.Environ(), "CGO_ENABLED=1") out, err := cmd.CombinedOutput() if err != nil { diff --git a/cmd/bd/test_helpers_pure_test.go b/cmd/bd/test_helpers_pure_test.go index 49e46fdb2..d6e29eaa2 100644 --- a/cmd/bd/test_helpers_pure_test.go +++ b/cmd/bd/test_helpers_pure_test.go @@ -324,6 +324,73 @@ func findPrebuiltBDBinary() (string, error) { return bazeltest.PrebuiltBD() } +// bdModulePackage is cmd/bd's import path. The in-test fallback build names +// it explicitly instead of "." so it can never build whatever package happens +// to be in the working directory. +const bdModulePackage = "github.com/steveyegge/beads/cmd/bd" + +// bdSourceDir is cmd/bd's source directory, resolved during package +// initialization, before TestMain or any test can chdir: this file's +// compiled-in path when it is absolute (not -trimpath) and next to main.go, +// else the working directory go test starts the binary in (the package +// directory). +var bdSourceDir = resolveBDSourceDir() + +func resolveBDSourceDir() string { + if _, file, _, ok := runtime.Caller(0); ok && filepath.IsAbs(file) { + dir := filepath.Dir(file) + if _, err := os.Stat(filepath.Join(dir, "main.go")); err == nil { + return dir + } + } + wd, _ := os.Getwd() + return wd +} + +// goBuildBDCommand returns the `go build` that subprocess-test helpers fall +// back to when BEADS_TEST_BD_BINARY is unset. It is the build CI prebuilds +// that binary with (main.yml build-artifacts: go build -tags gms_pure_go +// ./cmd/bd; no -race), and it builds cmd/bd whatever the caller's working +// directory is: the package is named by import path and the command runs in +// bdSourceDir, so a helper first reached from a test that chdir'd into a +// fixture (or a precompiled test binary run from elsewhere) still builds bd. +func goBuildBDCommand(out string) *exec.Cmd { + cmd := exec.Command("go", "build", "-tags", "gms_pure_go", "-o", out, bdModulePackage) + cmd.Dir = bdSourceDir + return cmd +} + +// TestGoBuildBDCommandIsCWDIndependent pins that the fallback build resolves +// cmd/bd from any working directory. It resolves the command's package in +// the command's directory with `go list` rather than paying for a full link. +func TestGoBuildBDCommandIsCWDIndependent(t *testing.T) { + if bazeltest.IsBazel() { + t.Skip("Bazel always injects bd through BEADS_TEST_BD_BINARY; the fallback build is unused") + } + if _, err := exec.LookPath("go"); err != nil { + t.Skipf("go toolchain not on PATH: %v", err) + } + t.Chdir(t.TempDir()) + + cmd := goBuildBDCommand(filepath.Join(t.TempDir(), "bd")) + if got := cmd.Args[len(cmd.Args)-1]; got != bdModulePackage { + t.Fatalf("goBuildBDCommand builds %q, want %q", got, bdModulePackage) + } + if !strings.Contains(strings.Join(cmd.Args, " "), "-tags gms_pure_go") { + t.Fatalf("goBuildBDCommand args %q lack CI's -tags gms_pure_go", cmd.Args) + } + + list := exec.Command("go", "list", "-tags", "gms_pure_go", "-f", "{{.Name}} {{.ImportPath}}", bdModulePackage) + list.Dir = cmd.Dir + out, err := list.CombinedOutput() + if err != nil { + t.Fatalf("go list %s in %q: %v\n%s", bdModulePackage, cmd.Dir, err, out) + } + if got, want := strings.TrimSpace(string(out)), "main "+bdModulePackage; got != want { + t.Fatalf("go list in %q = %q, want %q", cmd.Dir, got, want) + } +} + // buildBDForInitTests builds (or locates) a bd binary suitable for subprocess // tests. Uses the gms_pure_go tag so the resulting binary works in either // CGO mode. Lives in the pure-Go helpers file so subprocess-style tests can @@ -360,7 +427,7 @@ func buildBDForInitTests(t *testing.T) string { return } initTestBD = filepath.Join(tmpDir, bdBinary) - cmd := exec.Command("go", "build", "-tags", "gms_pure_go", "-o", initTestBD, ".") + cmd := goBuildBDCommand(initTestBD) if out, err := cmd.CombinedOutput(); err != nil { initTestBDErr = fmt.Errorf("go build failed: %v\n%s", err, out) } diff --git a/tools/bazel/equivalence_allowlist.txt b/tools/bazel/equivalence_allowlist.txt index b2c7e4e70..83e84b128 100644 --- a/tools/bazel/equivalence_allowlist.txt +++ b/tools/bazel/equivalence_allowlist.txt @@ -15,6 +15,8 @@ # The in-test `go build` of bd that this test guards does not happen under # Bazel (bd comes in through BEADS_TEST_BD_BINARY); go test still runs it. cmd/bd TestGOMODCACHENotUnderTestHome skip # no in-test go build under Bazel; guarded by go test +# Same: it checks the fallback `go build` of bd, which Bazel never takes. +cmd/bd TestGoBuildBDCommandIsCWDIndependent skip # no in-test go build under Bazel; guarded by go test # Needs TestAAAStdioBaseline in the same process; sharding splits them. # TestMain's checkStdioAfterRun still checks every shard. cmd/bd TestZZStdioNotLeaked skip # baseline test lands in another shard; checkStdioAfterRun covers each shard