beads/cmd/bd/where_embedded_test.go
Jim Wordelman 77a9abb983
fix: cmd/bd no-workspace tests depend on temp-dir ancestry and a stale git cache (#5798)
* fix: green — cmd/bd no-workspace tests depend on temp-dir ancestry and a stale git cache (refs be-vnkv)

TestWhereNoWorkspace and TestBootstrapNoWorkspace now git-init their temp
dir so the no-workspace ancestor walk has an explicit boundary and cannot
escape to a real ancestor .beads/ (e.g. $HOME/.beads) when GOTMPDIR/TMPDIR
resolve under the caller's home directory.

TestResolveWhereBeadsDir_ReturnsEmptyWithoutWorkspace gets the same
git-init boundary, and all three TestResolveWhereBeadsDir_* tests that
os.Chdir now call git.ResetCaches() after chdiring and again in cleanup
after chdiring back, since internal/git memoizes git-root lookups once
per process and otherwise leaks a stale cwd's cached result across
same-package tests that run in the same test binary.

* fix(test): move initGitRepoAt to the pure-Go helper file (refs be-87jk)

initGitRepoAt was defined in cmd/bd/init_embedded_test.go, which carries
//go:build cgo. Every other caller is cgo-tagged too, but cmd/bd/where_test.go
has no build tag, so it compiles under CGO_ENABLED=0 -- where the helper does
not exist:

    cmd/bd/where_test.go:85:2: undefined: initGitRepoAt

That broke two required lanes on PR #5798: "Check pure-Go and js/wasm
boundaries (CGO_ENABLED=0)" and "Worktree remove boundary (Windows)"
(-tags gms_pure_go, CGO_ENABLED=0).

The helper is stdlib-only (os/exec + testing), so it belongs in
test_helpers_pure_test.go, whose header already states the rule: helpers there
must stay stdlib-only so pure-Go tests in this package compile under
CGO_ENABLED=0. Moved verbatim -- no behavior change -- with a comment recording
why it must stay there.

Local verification (both configurations):
  CGO_ENABLED=0 go test -tags gms_pure_go -c ./cmd/bd   -> ok (was: build failed)
  CGO_ENABLED=1 go test -tags gms_pure_go -c ./cmd/bd   -> ok
  CGO_ENABLED=0 go test -tags gms_pure_go -run '^TestWorktreeRemove' ./cmd/bd -> ok
  CGO_ENABLED=0 go test -tags gms_pure_go -run '^TestResolveWhereBeadsDir' ./cmd/bd -> 3/3 PASS
  go vet ./cmd/bd/... under CGO_ENABLED=0 and =1 -> clean

* ci: retrigger — unrelated Ryuk reaper flake in storage/uow/tracker job

The "Test (storage domain + uow)" job failed on an infrastructure flake
unrelated to this PR's diff, taking the CI Gate / Required rollup with it.
That job runs three package trees in one go test invocation
(.github/workflows/pr.yml:676), so Go runs their test binaries in parallel
and each starts its own Dolt testcontainer. The binaries share a single
testcontainers Ryuk reaper; in this run the internal/tracker binary reused
a sibling's reaper and its handshake failed:

  18:26:20 Reaper obtained from Docker for this test session 72a9750d
  18:26:20 Reaper handshake failed: read ack: EOF

With no live connection holding the session open, Ryuk reaped the session's
containers. The tracker package's Dolt container (f2b3addaf5ea) started
healthy at 18:26:21 and served tests for 26 seconds, then went down at
18:26:47 — every subsequent store-backed test failed instantly on
127.0.0.1:32772 with "invalid connection" and then "connection refused".
All 50 failures in that job are that one dead container: 34 connection
refused, 16 invalid connection, 1 write commit result indeterminate. No
assertion failed. domain, domain/db, domain/fs, domain/git and uow all
passed in the same job.

This is be-2on, root-caused on a different PR (#5339) with the identical
signature. The durable fix is PR #5770 (disable Ryuk on the Dolt
testcontainer steps), which is open and awaiting upstream merge.

This PR touches only cmd/bd/*_test.go files in package main, which nothing
can import, and internal/tracker contains no reference to cmd/bd. Empty
commit to re-trigger CI.
2026-08-19 20:41:21 -07:00

196 lines
5.4 KiB
Go

//go:build cgo
package main
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"strings"
"sync"
"testing"
)
// bdWhere runs "bd where" with the given args and returns stdout.
func bdWhere(t *testing.T, bd, dir string, args ...string) string {
t.Helper()
fullArgs := append([]string{"where"}, args...)
cmd := exec.Command(bd, fullArgs...)
cmd.Dir = dir
cmd.Env = bdEnv(dir)
stdout, stderr, err := runCommandBuffers(t, cmd)
if err != nil {
t.Fatalf("bd where %s failed: %v\nstdout:\n%s\nstderr:\n%s", strings.Join(args, " "), err, stdout.String(), stderr.String())
}
return stdout.String()
}
func bdWhereAllowError(t *testing.T, bd, dir string, args ...string) (string, error) {
t.Helper()
fullArgs := append([]string{"where"}, args...)
cmd := exec.Command(bd, fullArgs...)
cmd.Dir = dir
cmd.Env = bdEnv(dir)
out, err := cmd.CombinedOutput()
return string(out), err
}
func TestWhereNoWorkspace(t *testing.T) {
t.Parallel()
bd := buildEmbeddedBD(t)
dir := t.TempDir()
initGitRepoAt(t, dir)
t.Run("default_output", func(t *testing.T) {
out, err := bdWhereAllowError(t, bd, dir)
if err == nil {
t.Fatal("expected bd where to exit non-zero without a workspace")
}
if !strings.Contains(out, activeWorkspaceNotFoundMessage()) {
t.Fatalf("expected no-workspace message, got: %s", out)
}
if strings.Contains(out, "no beads database found") {
t.Fatalf("where should report workspace resolution failure, not database init failure: %s", out)
}
})
t.Run("json_output", func(t *testing.T) {
out, err := bdWhereAllowError(t, bd, dir, "--json")
if err == nil {
t.Fatal("expected bd where --json to exit non-zero without a workspace")
}
s := strings.TrimSpace(out)
start := strings.Index(s, "{")
if start < 0 {
t.Fatalf("expected JSON object in output, got: %s", out)
}
var payload map[string]interface{}
if err := json.Unmarshal([]byte(s[start:]), &payload); err != nil {
t.Fatalf("parse where JSON: %v\n%s", err, s)
}
if errField, _ := payload["error"].(string); errField != "no_beads_directory" {
t.Fatalf("error = %q, want %q", errField, "no_beads_directory")
}
if message, _ := payload["message"].(string); message != activeWorkspaceNotFoundMessage() {
t.Fatalf("message = %q, want %q", message, activeWorkspaceNotFoundMessage())
}
hint, _ := payload["hint"].(string)
if !strings.Contains(hint, "BEADS_DIR/worktree setup") {
t.Fatalf("hint should mention workspace diagnostics, got: %q", hint)
}
if !strings.Contains(hint, "bd init") {
t.Fatalf("hint should mention bd init, got: %q", hint)
}
})
}
func TestEmbeddedWhere(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir, beadsDir, _ := bdInit(t, bd, "--prefix", "tw")
// ===== Default Output =====
t.Run("where_default", func(t *testing.T) {
out := bdWhere(t, bd, dir)
if !strings.Contains(out, ".beads") {
t.Errorf("expected .beads in where output: %s", out)
}
// Should contain the actual beads directory path
if !strings.Contains(out, beadsDir) {
t.Errorf("expected beads dir %q in where output: %s", beadsDir, out)
}
})
// ===== JSON Output =====
t.Run("where_json", func(t *testing.T) {
out := bdWhere(t, bd, dir, "--json")
s := strings.TrimSpace(out)
start := strings.Index(s, "{")
if start < 0 {
// --json may be affected by same flag shadowing as info;
// just verify no crash and output contains path
if !strings.Contains(out, ".beads") {
t.Errorf("expected .beads in where --json output: %s", out)
}
return
}
var m map[string]interface{}
if err := json.Unmarshal([]byte(s[start:]), &m); err != nil {
t.Fatalf("parse where JSON: %v\n%s", err, s)
}
// Verify path is present in JSON (WhereResult uses "path" key)
if path, ok := m["path"]; ok {
if p, ok := path.(string); ok && !strings.Contains(p, ".beads") {
t.Errorf("expected .beads in path: %v", path)
}
}
if prefix, ok := m["prefix"]; !ok {
t.Fatalf("expected prefix in where --json output: %s", out)
} else if p, ok := prefix.(string); !ok || p != "tw" {
t.Fatalf("expected prefix %q in where --json output, got %#v", "tw", prefix)
}
})
}
// TestEmbeddedWhereConcurrent exercises where operations concurrently.
func TestEmbeddedWhereConcurrent(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir, _, _ := bdInit(t, bd, "--prefix", "wx")
const numWorkers = 8
type workerResult struct {
worker int
err error
}
results := make([]workerResult, numWorkers)
var wg sync.WaitGroup
wg.Add(numWorkers)
for w := 0; w < numWorkers; w++ {
go func(worker int) {
defer wg.Done()
r := workerResult{worker: worker}
cmd := exec.Command(bd, "where")
cmd.Dir = dir
cmd.Env = bdEnv(dir)
out, err := cmd.CombinedOutput()
if err != nil {
r.err = fmt.Errorf("where (worker %d): %v\n%s", worker, err, out)
results[worker] = r
return
}
if !strings.Contains(string(out), ".beads") {
r.err = fmt.Errorf("where (worker %d): expected .beads in output: %s", worker, out)
results[worker] = r
return
}
results[worker] = r
}(w)
}
wg.Wait()
for _, r := range results {
if r.err != nil && !strings.Contains(r.err.Error(), "one writer at a time") {
t.Errorf("worker %d failed: %v", r.worker, r.err)
}
}
}