beads/cmd/bd/prompt_test.go
Jim Wordelman 571ab8afe6
fix(cmd/bd): restore os.Stdout via deferred idempotent restore so capture helpers survive t.Fatal (#5803)
* test(feat): red — cmd/bd capture helpers leak os.Stdout on t.Fatal (refs be-leuf)

Add TestCaptureCycleStdoutRestoresOnFatal (dep_cycles_test.go) and the
package-wide TestZZStdioNotLeaked guard (zz_stdio_leak_guard_test.go).
Both express the be-gh02 acceptance criteria before any fix: a capture
helper that restores os.Stdout/os.Stderr on the happy path only leaks
the global when its callback exits via runtime.Goexit (t.Fatal/panic).

RED confirmed: TestCaptureCycleStdoutRestoresOnFatal fails with
"captureCycleStdout leaked os.Stdout after a Goexit"; go vet clean;
0 broken-pipe collateral (the new test restores os.Stdout itself
before failing, so it doesn't poison later tests).

* fix(feat): green — cmd/bd capture helpers leak os.Stdout on t.Fatal (refs be-leuf)

Move every bare stdio-restore in cmd/bd's capture helpers into a defer
registered immediately after assignment, so a callback that exits via
runtime.Goexit (t.Fatal) or panic can no longer leave os.Stdout/os.Stderr
pointed at an orphaned pipe.

- captureCycleStdout (dep_cycles_test.go): restore moved into a defer,
  drain moved to a goroutine so a >64KiB write can't deadlock.
- Both inline os.Stderr captures in dep_cycles_test.go: deferred.
- captureStdout/captureStderr (test_helpers_pure_test.go): deferred,
  stdioMutex discipline unchanged.
- TestCaptureCycleStdoutRestoresOnFatal: drives the leaking callback via
  a goroutine + runtime.Goexit so the suite stays fully green (the fix
  spec's stated alternative to the failing-subtest shape).
- 19-site mechanical sweep across 11 more files: same bare-restore ->
  defer transform, no other restructuring, per spec item 6.

GREEN confirmed: go vet ./cmd/bd/... clean. go test -v -count=1
./cmd/bd/... via scripts/test.sh (beads_test_env_enter,
BEADS_TEST_SKIP=dolt) — EXIT_CODE=0, 0 'broken pipe' occurrences (was
3), 0 FAIL lines, all packages ok. TestRunSyncCommandExitCodeMapping
passes (all 3 subtests), TestZZStdioNotLeaked passes,
TestCaptureCycleStdoutRestoresOnFatal passes. The two dep-cycles tests
(TestDepCyclesNamesTheMembersItCannotDescribe,
TestDepCyclesSaysNothingIsWrongForACleanWorkspace) also pass in this
run — their arming precondition is order/environment-dependent per the
fix spec, so this is not required and does not indicate the fix works
only by coincidentally fixing them; the decoupling is structural.

* docs(release-gates): add be-sr7a gate record — PASS

Review be-1kxq passed; independently re-verified diff-owned tests
(TestCaptureCycleStdoutRestoresOnFatal, TestZZStdioNotLeaked,
TestRunSyncCommandExitCodeMapping) and full ./cmd/bd/... suite
(2389 PASS, 0 FAIL, 0 broken pipe/EPIPE occurrences), plus the
ci-pr-policy lane. .githooks/commit-msg false-failure root-caused
as a local gc-rig worktree shim (same finding as be-3b4e) and
remediated reversibly rather than waived.
2026-08-19 21:01:06 -07:00

173 lines
4.1 KiB
Go

package main
import (
"bufio"
"context"
"errors"
"io"
"os"
"strings"
"syscall"
"testing"
"time"
)
type notifyStub struct {
ready chan struct{}
cancel context.CancelFunc
signals []os.Signal
}
func installNotifyStub(t *testing.T) *notifyStub {
t.Helper()
stub := &notifyStub{ready: make(chan struct{}, 1)}
original := notifyContext
notifyContext = func(parent context.Context, signals ...os.Signal) (context.Context, context.CancelFunc) {
stub.signals = append([]os.Signal(nil), signals...)
ctx, cancel := context.WithCancel(parent)
stub.cancel = cancel
select {
case stub.ready <- struct{}{}:
default:
}
return ctx, cancel
}
t.Cleanup(func() { notifyContext = original })
return stub
}
func TestReadLineWithContextReadsLine(t *testing.T) {
stub := installNotifyStub(t)
reader := bufio.NewReader(strings.NewReader("yes\n"))
line, err := readLineWithContext(context.Background(), reader, nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if line != "yes\n" {
t.Fatalf("unexpected line: %q", line)
}
if len(stub.signals) != 2 || stub.signals[0] != os.Interrupt || stub.signals[1] != syscall.SIGTERM {
t.Fatalf("unexpected signals: %v", stub.signals)
}
}
func TestReadLineWithContextCanceled(t *testing.T) {
stub := installNotifyStub(t)
pr, pw := io.Pipe()
t.Cleanup(func() {
_ = pr.Close()
_ = pw.Close()
})
reader := bufio.NewReader(pr)
done := make(chan error, 1)
go func() {
_, err := readLineWithContext(context.Background(), reader, pr)
done <- err
}()
select {
case <-stub.ready:
case <-time.After(2 * time.Second):
t.Fatal("timeout waiting for notifyContext")
}
if stub.cancel == nil {
t.Fatal("expected cancel function")
}
stub.cancel()
_ = pw.Close()
select {
case err := <-done:
if !errors.Is(err, context.Canceled) {
t.Fatalf("expected context.Canceled, got %v", err)
}
case <-time.After(2 * time.Second):
t.Fatal("timeout waiting for readLineWithContext")
}
}
func TestPromptAutoExportDefaultsOff(t *testing.T) {
got, output, err := runPromptAutoExport(t, "\n")
if err != nil {
t.Fatalf("promptAutoExport returned error: %v", err)
}
if got {
t.Fatal("empty response should leave auto-export disabled")
}
if !strings.Contains(output, "Enable auto-export? [y/N]:") {
t.Fatalf("prompt did not show opt-in default:\n%s", output)
}
if !strings.Contains(output, "optional JSONL export") {
t.Fatalf("prompt should describe JSONL as optional export:\n%s", output)
}
if !strings.Contains(output, "Dolt remotes/backups handle cross-machine sync and backup") {
t.Fatalf("prompt should direct sync to Dolt remotes:\n%s", output)
}
}
func TestPromptAutoExportAcceptsYes(t *testing.T) {
got, _, err := runPromptAutoExport(t, "yes\n")
if err != nil {
t.Fatalf("promptAutoExport returned error: %v", err)
}
if !got {
t.Fatal("yes response should enable auto-export")
}
}
func runPromptAutoExport(t *testing.T, input string) (bool, string, error) {
t.Helper()
stdinFile, err := os.CreateTemp(t.TempDir(), "stdin-*")
if err != nil {
t.Fatalf("create temp stdin: %v", err)
}
if _, err := stdinFile.WriteString(input); err != nil {
t.Fatalf("write temp stdin: %v", err)
}
if _, err := stdinFile.Seek(0, 0); err != nil {
t.Fatalf("rewind temp stdin: %v", err)
}
oldStdin := os.Stdin
oldStdout := os.Stdout
oldRootCtx := rootCtx
oldRootCancel := rootCancel
var oldCmdRootCtx context.Context
var oldCmdRootCancel context.CancelFunc
if cmdCtx != nil {
oldCmdRootCtx = cmdCtx.RootCtx
oldCmdRootCancel = cmdCtx.RootCancel
}
r, w, err := os.Pipe()
if err != nil {
t.Fatalf("create stdout pipe: %v", err)
}
ctx, cancel := context.WithCancel(context.Background())
setRootContext(ctx, cancel)
os.Stdin = stdinFile
os.Stdout = w
defer func() { os.Stdout = oldStdout }()
got, promptErr := promptAutoExport()
_ = w.Close()
var b strings.Builder
_, _ = io.Copy(&b, r)
_ = r.Close()
os.Stdin = oldStdin
cancel()
rootCtx = oldRootCtx
rootCancel = oldRootCancel
if cmdCtx != nil {
cmdCtx.RootCtx = oldCmdRootCtx
cmdCtx.RootCancel = oldCmdRootCancel
}
_ = stdinFile.Close()
return got, b.String(), promptErr
}