beads/cmd/bd/init_cancel_e2e_test.go
Bee 3571331b50
test: fixtures commit with maintenance.auto=false before every git worktree add (wy-7ocweu) (#7358)
Fixes #7349. The same race #7314 closed in internal/beads and
internal/config, in the fixtures it did not cover: a fixture's plain
`git commit` spawns the detached `git maintenance run --auto` child, whose
worktree-prune races the fixture's next `git worktree add` and deletes
.git/worktrees/<name>/locked under it (seen on PR #7312 run 37585997441,
cmd/bd Dolt-server tier shard 4/16, TestBootstrap_WorktreeFallbackDir).

One noAutoMaintenance + gitCommand(args...) helper per test package, each
in an existing untagged shared test file (cmd/bd/helpers_test.go,
doctor/git_test_helpers_test.go, doctor/fix/common_test.go,
formula/parser_test.go, git/gitdir_test.go, storage/domain/git/git_test.go;
cmd/bd/test_helpers_test.go is //go:build cgo so unusable for the pure
lane), and every inline exec.Command("git", ...) in those six packages
swapped for it. The flags ride the command line, never env config: the
routing-key scrub drops env config. No new files, so no BUILD.bazel rows.

Proof: GIT_TRACE on `go test ./cmd/bd -run TestBootstrap_WorktreeFallbackDir`
counts 3 `maintenance run --auto` spawns at d8d8bf587b and 0 with this
change.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-08 08:01:46 +00:00

174 lines
4 KiB
Go

//go:build cgo && integration
package main
import (
"bytes"
"errors"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"testing"
"time"
)
func TestInitCancel_E2E(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("skipping SIGINT E2E test on Windows")
}
tmpDir := createTempDirWithCleanup(t)
runGitCmd(t, tmpDir, "init", "-b", "main")
stdinR, stdinW, err := os.Pipe()
if err != nil {
t.Fatalf("failed to create stdin pipe: %v", err)
}
defer func() { _ = stdinW.Close() }()
stdoutR, stdoutW, err := os.Pipe()
if err != nil {
t.Fatalf("failed to create stdout pipe: %v", err)
}
defer func() { _ = stdoutR.Close() }()
cmd := exec.Command(testBD, "init", "--prefix", "test", "--contributor")
cmd.Dir = tmpDir
cmd.Stdin = stdinR
cmd.Stdout = stdoutW
cmd.Stderr = stdoutW
cmd.Env = append(filteredEnv("BEADS_DB", "BEADS_DIR", "HOME", "XDG_CONFIG_HOME", "BD_NON_INTERACTIVE", "CI"),
"BEADS_DB=",
"HOME="+tmpDir,
"XDG_CONFIG_HOME="+filepath.Join(tmpDir, "xdg-config"),
"BD_NON_INTERACTIVE=0",
"CI=",
)
if err := cmd.Start(); err != nil {
t.Fatalf("failed to start bd init: %v", err)
}
_ = stdinR.Close()
_ = stdoutW.Close()
prompts := [][]byte{
[]byte("Continue with contributor setup? [y/N]: "),
[]byte("Continue anyway? [y/N]: "),
}
promptSeen := make(chan struct{})
readerDone := make(chan struct{})
var output bytes.Buffer
var outputMu sync.Mutex
var promptOnce sync.Once
go func() {
defer close(readerDone)
buf := make([]byte, 1024)
for {
n, err := stdoutR.Read(buf)
if n > 0 {
outputMu.Lock()
output.Write(buf[:n])
for _, prompt := range prompts {
if bytes.Contains(output.Bytes(), prompt) {
promptOnce.Do(func() { close(promptSeen) })
break
}
}
outputMu.Unlock()
}
if err != nil {
return
}
}
}()
waitCh := make(chan error, 1)
go func() {
waitCh <- cmd.Wait()
}()
getOutput := func() string {
outputMu.Lock()
defer outputMu.Unlock()
return output.String()
}
select {
case <-promptSeen:
if err := cmd.Process.Signal(os.Interrupt); err != nil {
t.Fatalf("failed to send SIGINT: %v", err)
}
case err := <-waitCh:
t.Fatalf("bd init exited before prompt: %v\nOutput: %s", err, getOutput())
// This deadline guards against a hung init, not startup speed: before the
// wizard prints anything, bd init creates the embedded dolt store, which
// under the nightly full-suite -race load takes ~5s on CI runners and grew
// past the old 5s limit (4.71s -> 4.92s -> 5.02s across 2026-07-23..25).
case <-time.After(60 * time.Second):
_ = cmd.Process.Kill()
err := <-waitCh
t.Fatalf("timeout waiting for prompt (exit=%v)\nOutput: %s", err, getOutput())
}
err = <-waitCh
select {
case <-readerDone:
case <-time.After(2 * time.Second):
t.Log("timeout waiting for output drain")
}
if err == nil {
t.Fatalf("expected non-zero exit, got success\nOutput: %s", getOutput())
}
var exitErr *exec.ExitError
if !errors.As(err, &exitErr) {
t.Fatalf("unexpected error type: %v\nOutput: %s", err, getOutput())
}
if exitErr.ExitCode() != exitCodeCanceled {
t.Fatalf("expected exit code %d, got %d\nOutput: %s", exitCodeCanceled, exitErr.ExitCode(), getOutput())
}
if !strings.Contains(getOutput(), "Setup canceled.") {
t.Fatalf("expected cancel message, got:\n%s", getOutput())
}
}
func runGitCmd(t *testing.T, dir string, args ...string) {
t.Helper()
cmd := gitCommand(args...)
cmd.Dir = dir
output, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("git %v failed in %s: %v\n%s", args, dir, err, output)
}
}
func filteredEnv(keys ...string) []string {
strip := make(map[string]struct{}, len(keys))
for _, key := range keys {
strip[key+"="] = struct{}{}
}
env := os.Environ()
filtered := make([]string, 0, len(env))
for _, entry := range env {
trim := false
for prefix := range strip {
if strings.HasPrefix(entry, prefix) {
trim = true
break
}
}
if !trim {
filtered = append(filtered, entry)
}
}
return filtered
}