test: replace manual os.Chdir with t.Chdir in tests (#457)

Replaces manual working directory save/restore patterns
with Go's built-in `t.Chdir()` helper across 23 test files.

The manual pattern involved calling `os.Getwd()` to save
the original directory, using `defer os.Chdir(origWd)` for
restoration, and manually handling errors during directory
changes. This boilerplate has been replaced with single
`t.Chdir(path)` calls that handle cleanup automatically.

The `t.Chdir()` method automatically restores the working
directory when the test completes, eliminating the need for
manual defer statements and error handling.

Total:
~75 instances replaced (assuming Claude's math is right)

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
Abhinav Gupta
2025-12-04 11:21:43 -08:00
committed by GitHub
parent f4b8a7ad4f
commit ac8ef9b9e3
23 changed files with 113 additions and 612 deletions
+6 -18
View File
@@ -172,9 +172,7 @@ func TestCheckAndAutoImport_EmptyDatabaseNoGit(t *testing.T) {
}() }()
// Change to temp dir (no git repo) // Change to temp dir (no git repo)
oldWd, _ := os.Getwd() t.Chdir(tmpDir)
defer os.Chdir(oldWd)
os.Chdir(tmpDir)
result := checkAndAutoImport(ctx, store) result := checkAndAutoImport(ctx, store)
if result { if result {
@@ -191,9 +189,7 @@ func TestFindBeadsDir(t *testing.T) {
} }
// Change to tmpDir // Change to tmpDir
oldWd, _ := os.Getwd() t.Chdir(tmpDir)
defer os.Chdir(oldWd)
os.Chdir(tmpDir)
found := findBeadsDir() found := findBeadsDir()
if found == "" { if found == "" {
@@ -211,9 +207,7 @@ func TestFindBeadsDir_NotFound(t *testing.T) {
// Create temp directory without .beads // Create temp directory without .beads
tmpDir := t.TempDir() tmpDir := t.TempDir()
oldWd, _ := os.Getwd() t.Chdir(tmpDir)
defer os.Chdir(oldWd)
os.Chdir(tmpDir)
found := findBeadsDir() found := findBeadsDir()
// findBeadsDir walks up to root, so it might find .beads in parent dirs // findBeadsDir walks up to root, so it might find .beads in parent dirs
@@ -237,9 +231,7 @@ func TestFindBeadsDir_ParentDirectory(t *testing.T) {
} }
// Change to subdir // Change to subdir
oldWd, _ := os.Getwd() t.Chdir(subDir)
defer os.Chdir(oldWd)
os.Chdir(subDir)
found := findBeadsDir() found := findBeadsDir()
if found == "" { if found == "" {
@@ -256,9 +248,7 @@ func TestFindBeadsDir_ParentDirectory(t *testing.T) {
func TestCheckGitForIssues_NoGitRepo(t *testing.T) { func TestCheckGitForIssues_NoGitRepo(t *testing.T) {
// Change to temp dir (not a git repo) // Change to temp dir (not a git repo)
tmpDir := t.TempDir() tmpDir := t.TempDir()
oldWd, _ := os.Getwd() t.Chdir(tmpDir)
defer os.Chdir(oldWd)
os.Chdir(tmpDir)
count, path := checkGitForIssues() count, path := checkGitForIssues()
if count != 0 { if count != 0 {
@@ -272,9 +262,7 @@ func TestCheckGitForIssues_NoGitRepo(t *testing.T) {
func TestCheckGitForIssues_NoBeadsDir(t *testing.T) { func TestCheckGitForIssues_NoBeadsDir(t *testing.T) {
// Use current directory which has git but change to somewhere without .beads // Use current directory which has git but change to somewhere without .beads
tmpDir := t.TempDir() tmpDir := t.TempDir()
oldWd, _ := os.Getwd() t.Chdir(tmpDir)
defer os.Chdir(oldWd)
os.Chdir(tmpDir)
count, path := checkGitForIssues() count, path := checkGitForIssues()
if count != 0 || path != "" { if count != 0 || path != "" {
+19 -94
View File
@@ -66,15 +66,7 @@ func TestSyncBranchCommitAndPush_NotConfigured(t *testing.T) {
} }
// Change to temp directory for git operations // Change to temp directory for git operations
oldWd, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
defer os.Chdir(oldWd)
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change directory: %v", err)
}
// Test with no sync.branch configured // Test with no sync.branch configured
log, logMsgs := newTestSyncBranchLogger() log, logMsgs := newTestSyncBranchLogger()
@@ -124,15 +116,7 @@ func TestSyncBranchCommitAndPush_Success(t *testing.T) {
} }
// Initial commit on main branch (before creating JSONL) // Initial commit on main branch (before creating JSONL)
oldWd, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
defer os.Chdir(oldWd)
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change directory: %v", err)
}
initMainBranch(t, tmpDir) initMainBranch(t, tmpDir)
@@ -238,15 +222,7 @@ func TestSyncBranchCommitAndPush_EnvOverridesDB(t *testing.T) {
t.Setenv(syncbranch.EnvVar, "env-branch") t.Setenv(syncbranch.EnvVar, "env-branch")
// Initial commit on main branch // Initial commit on main branch
oldWd, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
defer os.Chdir(oldWd)
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change directory: %v", err)
}
initMainBranch(t, tmpDir) initMainBranch(t, tmpDir)
@@ -343,15 +319,7 @@ func TestSyncBranchCommitAndPush_NoChanges(t *testing.T) {
t.Fatalf("Failed to export: %v", err) t.Fatalf("Failed to export: %v", err)
} }
oldWd, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
defer os.Chdir(oldWd)
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change directory: %v", err)
}
log, logMsgs := newTestSyncBranchLogger() log, logMsgs := newTestSyncBranchLogger()
@@ -428,15 +396,7 @@ func TestSyncBranchCommitAndPush_WorktreeHealthCheck(t *testing.T) {
t.Fatalf("Failed to export: %v", err) t.Fatalf("Failed to export: %v", err)
} }
oldWd, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
defer os.Chdir(oldWd)
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change directory: %v", err)
}
log, logMsgs := newTestSyncBranchLogger() log, logMsgs := newTestSyncBranchLogger()
@@ -510,15 +470,7 @@ func TestSyncBranchPull_NotConfigured(t *testing.T) {
t.Fatalf("Failed to set prefix: %v", err) t.Fatalf("Failed to set prefix: %v", err)
} }
oldWd, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
defer os.Chdir(oldWd)
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change directory: %v", err)
}
log, logMsgs := newTestSyncBranchLogger() log, logMsgs := newTestSyncBranchLogger()
_ = logMsgs // unused in this test _ = logMsgs // unused in this test
@@ -597,15 +549,7 @@ func TestSyncBranchPull_Success(t *testing.T) {
runGitCmd(t, clone1Dir, "push", "origin", "master") runGitCmd(t, clone1Dir, "push", "origin", "master")
// Change to clone1 directory for sync branch operations // Change to clone1 directory for sync branch operations
oldWd, err := os.Getwd() t.Chdir(clone1Dir)
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
defer os.Chdir(oldWd)
if err := os.Chdir(clone1Dir); err != nil {
t.Fatalf("Failed to change directory: %v", err)
}
// Push to sync branch using syncBranchCommitAndPush // Push to sync branch using syncBranchCommitAndPush
log, logMsgs := newTestSyncBranchLogger() log, logMsgs := newTestSyncBranchLogger()
@@ -640,9 +584,7 @@ func TestSyncBranchPull_Success(t *testing.T) {
} }
// Change to clone2 directory // Change to clone2 directory
if err := os.Chdir(clone2Dir); err != nil { t.Chdir(clone2Dir)
t.Fatalf("Failed to change directory: %v", err)
}
// Pull from sync branch // Pull from sync branch
log2, logMsgs2 := newTestSyncBranchLogger() log2, logMsgs2 := newTestSyncBranchLogger()
@@ -736,9 +678,7 @@ func TestSyncBranchIntegration_EndToEnd(t *testing.T) {
runGitCmd(t, clone1Dir, "push", "origin", "master") runGitCmd(t, clone1Dir, "push", "origin", "master")
// Change to clone1 directory // Change to clone1 directory
oldWd, _ := os.Getwd() t.Chdir(clone1Dir)
defer os.Chdir(oldWd)
os.Chdir(clone1Dir)
// Agent A commits to sync branch // Agent A commits to sync branch
log, logMsgs := newTestSyncBranchLogger() log, logMsgs := newTestSyncBranchLogger()
@@ -765,7 +705,7 @@ func TestSyncBranchIntegration_EndToEnd(t *testing.T) {
store2.SetConfig(ctx, "sync.branch", syncBranch) store2.SetConfig(ctx, "sync.branch", syncBranch)
// Change to clone2 directory // Change to clone2 directory
os.Chdir(clone2Dir) t.Chdir(clone2Dir)
// Agent B pulls from sync branch // Agent B pulls from sync branch
log2, logMsgs2 := newTestSyncBranchLogger() log2, logMsgs2 := newTestSyncBranchLogger()
@@ -807,7 +747,7 @@ func TestSyncBranchIntegration_EndToEnd(t *testing.T) {
} }
// Agent A pulls the update // Agent A pulls the update
os.Chdir(clone1Dir) t.Chdir(clone1Dir)
pulled, err = syncBranchPull(ctx, store1, log) pulled, err = syncBranchPull(ctx, store1, log)
if err != nil { if err != nil {
t.Fatalf("syncBranchPull failed for clone1: %v", err) t.Fatalf("syncBranchPull failed for clone1: %v", err)
@@ -891,15 +831,7 @@ func TestSyncBranchConfigChange(t *testing.T) {
t.Fatalf("Failed to export: %v", err) t.Fatalf("Failed to export: %v", err)
} }
oldWd, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
defer os.Chdir(oldWd)
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change directory: %v", err)
}
log, _ := newTestSyncBranchLogger() log, _ := newTestSyncBranchLogger()
@@ -1020,11 +952,8 @@ func TestSyncBranchMultipleConcurrentClones(t *testing.T) {
initMainBranch(t, clone1Dir) initMainBranch(t, clone1Dir)
runGitCmd(t, clone1Dir, "push", "origin", "master") runGitCmd(t, clone1Dir, "push", "origin", "master")
oldWd, _ := os.Getwd()
defer os.Chdir(oldWd)
// Clone1: Create and push issue A // Clone1: Create and push issue A
os.Chdir(clone1Dir) t.Chdir(clone1Dir)
issueA := &types.Issue{ issueA := &types.Issue{
Title: "Issue A from clone1", Title: "Issue A from clone1",
Status: types.StatusOpen, Status: types.StatusOpen,
@@ -1044,7 +973,7 @@ func TestSyncBranchMultipleConcurrentClones(t *testing.T) {
} }
// Clone2: Fetch, pull, create issue B, push // Clone2: Fetch, pull, create issue B, push
os.Chdir(clone2Dir) t.Chdir(clone2Dir)
runGitCmd(t, clone2Dir, "fetch", "origin") runGitCmd(t, clone2Dir, "fetch", "origin")
log2, _ := newTestSyncBranchLogger() log2, _ := newTestSyncBranchLogger()
syncBranchPull(ctx, store2, log2) syncBranchPull(ctx, store2, log2)
@@ -1067,7 +996,7 @@ func TestSyncBranchMultipleConcurrentClones(t *testing.T) {
} }
// Clone3: Fetch, pull, create issue C, push // Clone3: Fetch, pull, create issue C, push
os.Chdir(clone3Dir) t.Chdir(clone3Dir)
runGitCmd(t, clone3Dir, "fetch", "origin") runGitCmd(t, clone3Dir, "fetch", "origin")
log3, _ := newTestSyncBranchLogger() log3, _ := newTestSyncBranchLogger()
syncBranchPull(ctx, store3, log3) syncBranchPull(ctx, store3, log3)
@@ -1090,11 +1019,11 @@ func TestSyncBranchMultipleConcurrentClones(t *testing.T) {
} }
// All clones pull final state // All clones pull final state
os.Chdir(clone1Dir) t.Chdir(clone1Dir)
syncBranchPull(ctx, store1, log1) syncBranchPull(ctx, store1, log1)
importToJSONLWithStore(ctx, store1, jsonlPath1) importToJSONLWithStore(ctx, store1, jsonlPath1)
os.Chdir(clone2Dir) t.Chdir(clone2Dir)
syncBranchPull(ctx, store2, log2) syncBranchPull(ctx, store2, log2)
importToJSONLWithStore(ctx, store2, jsonlPath2) importToJSONLWithStore(ctx, store2, jsonlPath2)
@@ -1164,9 +1093,7 @@ func TestSyncBranchPerformance(t *testing.T) {
jsonlPath := filepath.Join(beadsDir, "issues.jsonl") jsonlPath := filepath.Join(beadsDir, "issues.jsonl")
exportToJSONLWithStore(ctx, store, jsonlPath) exportToJSONLWithStore(ctx, store, jsonlPath)
oldWd, _ := os.Getwd() t.Chdir(tmpDir)
defer os.Chdir(oldWd)
os.Chdir(tmpDir)
log, _ := newTestSyncBranchLogger() log, _ := newTestSyncBranchLogger()
@@ -1255,9 +1182,7 @@ func TestSyncBranchNetworkFailure(t *testing.T) {
jsonlPath := filepath.Join(beadsDir, "issues.jsonl") jsonlPath := filepath.Join(beadsDir, "issues.jsonl")
exportToJSONLWithStore(ctx, store, jsonlPath) exportToJSONLWithStore(ctx, store, jsonlPath)
oldWd, _ := os.Getwd() t.Chdir(tmpDir)
defer os.Chdir(oldWd)
os.Chdir(tmpDir)
log, logMsgs := newTestSyncBranchLogger() log, logMsgs := newTestSyncBranchLogger()
+6 -18
View File
@@ -36,9 +36,7 @@ func TestInstallHooks(t *testing.T) {
tmpDir := t.TempDir() tmpDir := t.TempDir()
// Change to temp directory // Change to temp directory
oldWd, _ := os.Getwd() t.Chdir(tmpDir)
defer os.Chdir(oldWd)
os.Chdir(tmpDir)
// Initialize a real git repo (required for git rev-parse) // Initialize a real git repo (required for git rev-parse)
if err := exec.Command("git", "init").Run(); err != nil { if err := exec.Command("git", "init").Run(); err != nil {
@@ -85,9 +83,7 @@ func TestInstallHooksBackup(t *testing.T) {
tmpDir := t.TempDir() tmpDir := t.TempDir()
// Change to temp directory // Change to temp directory
oldWd, _ := os.Getwd() t.Chdir(tmpDir)
defer os.Chdir(oldWd)
os.Chdir(tmpDir)
// Initialize a real git repo (required for git rev-parse) // Initialize a real git repo (required for git rev-parse)
if err := exec.Command("git", "init").Run(); err != nil { if err := exec.Command("git", "init").Run(); err != nil {
@@ -135,9 +131,7 @@ func TestInstallHooksForce(t *testing.T) {
tmpDir := t.TempDir() tmpDir := t.TempDir()
// Change to temp directory first, then init // Change to temp directory first, then init
oldWd, _ := os.Getwd() t.Chdir(tmpDir)
defer os.Chdir(oldWd)
os.Chdir(tmpDir)
// Initialize a real git repo (required for git rev-parse) // Initialize a real git repo (required for git rev-parse)
if err := exec.Command("git", "init").Run(); err != nil { if err := exec.Command("git", "init").Run(); err != nil {
@@ -175,9 +169,7 @@ func TestUninstallHooks(t *testing.T) {
tmpDir := t.TempDir() tmpDir := t.TempDir()
// Change to temp directory first, then init // Change to temp directory first, then init
oldWd, _ := os.Getwd() t.Chdir(tmpDir)
defer os.Chdir(oldWd)
os.Chdir(tmpDir)
// Initialize a real git repo (required for git rev-parse) // Initialize a real git repo (required for git rev-parse)
if err := exec.Command("git", "init").Run(); err != nil { if err := exec.Command("git", "init").Run(); err != nil {
@@ -215,9 +207,7 @@ func TestHooksCheckGitHooks(t *testing.T) {
tmpDir := t.TempDir() tmpDir := t.TempDir()
// Change to temp directory first, then init // Change to temp directory first, then init
oldWd, _ := os.Getwd() t.Chdir(tmpDir)
defer os.Chdir(oldWd)
os.Chdir(tmpDir)
// Initialize a real git repo (required for git rev-parse) // Initialize a real git repo (required for git rev-parse)
if err := exec.Command("git", "init").Run(); err != nil { if err := exec.Command("git", "init").Run(); err != nil {
@@ -263,9 +253,7 @@ func TestInstallHooksShared(t *testing.T) {
tmpDir := t.TempDir() tmpDir := t.TempDir()
// Change to temp directory // Change to temp directory
oldWd, _ := os.Getwd() t.Chdir(tmpDir)
defer os.Chdir(oldWd)
os.Chdir(tmpDir)
// Initialize a real git repo (needed for git config command) // Initialize a real git repo (needed for git config command)
if err := exec.Command("git", "init").Run(); err != nil { if err := exec.Command("git", "init").Run(); err != nil {
+3 -27
View File
@@ -11,15 +11,7 @@ import (
func TestDetectExistingHooks(t *testing.T) { func TestDetectExistingHooks(t *testing.T) {
// Create a temporary directory // Create a temporary directory
tmpDir := t.TempDir() tmpDir := t.TempDir()
oldDir, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
t.Fatal(err)
}
defer os.Chdir(oldDir)
if err := os.Chdir(tmpDir); err != nil {
t.Fatal(err)
}
// Initialize a real git repo (required for git rev-parse) // Initialize a real git repo (required for git rev-parse)
if err := exec.Command("git", "init").Run(); err != nil { if err := exec.Command("git", "init").Run(); err != nil {
@@ -110,15 +102,7 @@ func TestDetectExistingHooks(t *testing.T) {
func TestInstallGitHooks_NoExistingHooks(t *testing.T) { func TestInstallGitHooks_NoExistingHooks(t *testing.T) {
// Create a temporary directory // Create a temporary directory
tmpDir := t.TempDir() tmpDir := t.TempDir()
oldDir, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
t.Fatal(err)
}
defer os.Chdir(oldDir)
if err := os.Chdir(tmpDir); err != nil {
t.Fatal(err)
}
// Initialize a real git repo (required for git rev-parse) // Initialize a real git repo (required for git rev-parse)
if err := exec.Command("git", "init").Run(); err != nil { if err := exec.Command("git", "init").Run(); err != nil {
@@ -157,15 +141,7 @@ func TestInstallGitHooks_NoExistingHooks(t *testing.T) {
func TestInstallGitHooks_ExistingHookBackup(t *testing.T) { func TestInstallGitHooks_ExistingHookBackup(t *testing.T) {
// Create a temporary directory // Create a temporary directory
tmpDir := t.TempDir() tmpDir := t.TempDir()
oldDir, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
t.Fatal(err)
}
defer os.Chdir(oldDir)
if err := os.Chdir(tmpDir); err != nil {
t.Fatal(err)
}
// Initialize a real git repo (required for git rev-parse) // Initialize a real git repo (required for git rev-parse)
if err := exec.Command("git", "init").Run(); err != nil { if err := exec.Command("git", "init").Run(); err != nil {
+20 -136
View File
@@ -56,15 +56,7 @@ func TestInitCommand(t *testing.T) {
initCmd.Flags().Set("quiet", "false") initCmd.Flags().Set("quiet", "false")
tmpDir := t.TempDir() tmpDir := t.TempDir()
originalWd, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
defer os.Chdir(originalWd)
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change to temp directory: %v", err)
}
// Capture output // Capture output
var buf bytes.Buffer var buf bytes.Buffer
@@ -87,6 +79,7 @@ func TestInitCommand(t *testing.T) {
rootCmd.SetArgs(args) rootCmd.SetArgs(args)
// Run command // Run command
var err error
err = rootCmd.Execute() err = rootCmd.Execute()
// Restore stdout and read output // Restore stdout and read output
@@ -198,15 +191,7 @@ func TestInitAlreadyInitialized(t *testing.T) {
dbPath = "" dbPath = ""
tmpDir := t.TempDir() tmpDir := t.TempDir()
originalWd, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
defer os.Chdir(originalWd)
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change to temp directory: %v", err)
}
// Initialize once // Initialize once
rootCmd.SetArgs([]string{"init", "--prefix", "test", "--quiet"}) rootCmd.SetArgs([]string{"init", "--prefix", "test", "--quiet"})
@@ -256,15 +241,7 @@ func TestInitWithCustomDBPath(t *testing.T) {
t.Fatalf("Failed to create work directory: %v", err) t.Fatalf("Failed to create work directory: %v", err)
} }
originalWd, err := os.Getwd() t.Chdir(workDir)
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
defer os.Chdir(originalWd)
if err := os.Chdir(workDir); err != nil {
t.Fatalf("Failed to change to work directory: %v", err)
}
customDBPath := filepath.Join(customDBDir, "test.db") customDBPath := filepath.Join(customDBDir, "test.db")
@@ -407,15 +384,7 @@ func TestInitNoDbMode(t *testing.T) {
noDb = false noDb = false
tmpDir := t.TempDir() tmpDir := t.TempDir()
originalWd, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
defer os.Chdir(originalWd)
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change to temp directory: %v", err)
}
// Initialize with --no-db flag // Initialize with --no-db flag
rootCmd.SetArgs([]string{"init", "--no-db", "--no-daemon", "--prefix", "test", "--quiet"}) rootCmd.SetArgs([]string{"init", "--no-db", "--no-daemon", "--prefix", "test", "--quiet"})
@@ -491,15 +460,7 @@ func TestInitMergeDriverAutoConfiguration(t *testing.T) {
dbPath = "" dbPath = ""
tmpDir := t.TempDir() tmpDir := t.TempDir()
originalWd, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
defer os.Chdir(originalWd)
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change to temp directory: %v", err)
}
// Initialize git repo first // Initialize git repo first
if err := runCommandInDir(tmpDir, "git", "init"); err != nil { if err := runCommandInDir(tmpDir, "git", "init"); err != nil {
@@ -539,15 +500,7 @@ func TestInitMergeDriverAutoConfiguration(t *testing.T) {
dbPath = "" dbPath = ""
tmpDir := t.TempDir() tmpDir := t.TempDir()
originalWd, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
defer os.Chdir(originalWd)
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change to temp directory: %v", err)
}
// Initialize git repo first // Initialize git repo first
if err := runCommandInDir(tmpDir, "git", "init"); err != nil { if err := runCommandInDir(tmpDir, "git", "init"); err != nil {
@@ -561,7 +514,7 @@ func TestInitMergeDriverAutoConfiguration(t *testing.T) {
} }
// Verify git config was NOT set locally (use --local to avoid picking up global config) // Verify git config was NOT set locally (use --local to avoid picking up global config)
_, err = runCommandInDirWithOutput(tmpDir, "git", "config", "--local", "merge.beads.driver") _, err := runCommandInDirWithOutput(tmpDir, "git", "config", "--local", "merge.beads.driver")
if err == nil { if err == nil {
t.Error("Expected git config to not be set with --skip-merge-driver") t.Error("Expected git config to not be set with --skip-merge-driver")
} }
@@ -580,15 +533,7 @@ func TestInitMergeDriverAutoConfiguration(t *testing.T) {
dbPath = "" dbPath = ""
tmpDir := t.TempDir() tmpDir := t.TempDir()
originalWd, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
defer os.Chdir(originalWd)
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change to temp directory: %v", err)
}
// DON'T initialize git repo // DON'T initialize git repo
@@ -612,15 +557,7 @@ func TestInitMergeDriverAutoConfiguration(t *testing.T) {
dbPath = "" dbPath = ""
tmpDir := t.TempDir() tmpDir := t.TempDir()
originalWd, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
defer os.Chdir(originalWd)
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change to temp directory: %v", err)
}
// Initialize git repo // Initialize git repo
if err := runCommandInDir(tmpDir, "git", "init"); err != nil { if err := runCommandInDir(tmpDir, "git", "init"); err != nil {
@@ -683,15 +620,7 @@ func TestInitMergeDriverAutoConfiguration(t *testing.T) {
initCmd.Flags().Set("skip-merge-driver", "false") initCmd.Flags().Set("skip-merge-driver", "false")
tmpDir := t.TempDir() tmpDir := t.TempDir()
originalWd, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
defer os.Chdir(originalWd)
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change to temp directory: %v", err)
}
// Initialize git repo // Initialize git repo
if err := runCommandInDir(tmpDir, "git", "init"); err != nil { if err := runCommandInDir(tmpDir, "git", "init"); err != nil {
@@ -750,15 +679,7 @@ func TestInitMergeDriverAutoConfiguration(t *testing.T) {
initCmd.Flags().Set("skip-merge-driver", "false") initCmd.Flags().Set("skip-merge-driver", "false")
tmpDir := t.TempDir() tmpDir := t.TempDir()
originalWd, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
defer os.Chdir(originalWd)
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change to temp directory: %v", err)
}
// Initialize git repo // Initialize git repo
if err := runCommandInDir(tmpDir, "git", "init"); err != nil { if err := runCommandInDir(tmpDir, "git", "init"); err != nil {
@@ -800,15 +721,7 @@ func TestInitMergeDriverAutoConfiguration(t *testing.T) {
dbPath = "" dbPath = ""
tmpDir := t.TempDir() tmpDir := t.TempDir()
originalWd, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
defer os.Chdir(originalWd)
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change to temp directory: %v", err)
}
// Initialize git repo // Initialize git repo
if err := runCommandInDir(tmpDir, "git", "init"); err != nil { if err := runCommandInDir(tmpDir, "git", "init"); err != nil {
@@ -857,15 +770,7 @@ func TestInitMergeDriverAutoConfiguration(t *testing.T) {
dbPath = "" dbPath = ""
tmpDir := t.TempDir() tmpDir := t.TempDir()
originalWd, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
defer os.Chdir(originalWd)
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change to temp directory: %v", err)
}
// Initialize git repo // Initialize git repo
if err := runCommandInDir(tmpDir, "git", "init"); err != nil { if err := runCommandInDir(tmpDir, "git", "init"); err != nil {
@@ -1003,15 +908,7 @@ func TestReadFirstIssueFromJSONL_EmptyFile(t *testing.T) {
// This is a regression test for bd-5bj where user settings were lost. // This is a regression test for bd-5bj where user settings were lost.
func TestSetupClaudeSettings_InvalidJSON(t *testing.T) { func TestSetupClaudeSettings_InvalidJSON(t *testing.T) {
tmpDir := t.TempDir() tmpDir := t.TempDir()
originalWd, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
defer os.Chdir(originalWd)
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change to temp directory: %v", err)
}
// Create .claude directory // Create .claude directory
claudeDir := filepath.Join(tmpDir, ".claude") claudeDir := filepath.Join(tmpDir, ".claude")
@@ -1037,6 +934,7 @@ func TestSetupClaudeSettings_InvalidJSON(t *testing.T) {
} }
// Call setupClaudeSettings - should return an error // Call setupClaudeSettings - should return an error
var err error
err = setupClaudeSettings(false) err = setupClaudeSettings(false)
if err == nil { if err == nil {
t.Fatal("Expected error for invalid JSON, got nil") t.Fatal("Expected error for invalid JSON, got nil")
@@ -1065,15 +963,7 @@ func TestSetupClaudeSettings_InvalidJSON(t *testing.T) {
// TestSetupClaudeSettings_ValidJSON verifies that valid JSON is properly updated // TestSetupClaudeSettings_ValidJSON verifies that valid JSON is properly updated
func TestSetupClaudeSettings_ValidJSON(t *testing.T) { func TestSetupClaudeSettings_ValidJSON(t *testing.T) {
tmpDir := t.TempDir() tmpDir := t.TempDir()
originalWd, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
defer os.Chdir(originalWd)
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change to temp directory: %v", err)
}
// Create .claude directory // Create .claude directory
claudeDir := filepath.Join(tmpDir, ".claude") claudeDir := filepath.Join(tmpDir, ".claude")
@@ -1098,6 +988,7 @@ func TestSetupClaudeSettings_ValidJSON(t *testing.T) {
} }
// Call setupClaudeSettings - should succeed // Call setupClaudeSettings - should succeed
var err error
err = setupClaudeSettings(false) err = setupClaudeSettings(false)
if err != nil { if err != nil {
t.Fatalf("Expected no error for valid JSON, got: %v", err) t.Fatalf("Expected no error for valid JSON, got: %v", err)
@@ -1134,19 +1025,12 @@ func TestSetupClaudeSettings_ValidJSON(t *testing.T) {
// TestSetupClaudeSettings_NoExistingFile verifies behavior when no file exists // TestSetupClaudeSettings_NoExistingFile verifies behavior when no file exists
func TestSetupClaudeSettings_NoExistingFile(t *testing.T) { func TestSetupClaudeSettings_NoExistingFile(t *testing.T) {
tmpDir := t.TempDir() tmpDir := t.TempDir()
originalWd, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
defer os.Chdir(originalWd)
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change to temp directory: %v", err)
}
// Don't create .claude directory - setupClaudeSettings should create it // Don't create .claude directory - setupClaudeSettings should create it
// Call setupClaudeSettings - should succeed // Call setupClaudeSettings - should succeed
var err error
err = setupClaudeSettings(false) err = setupClaudeSettings(false)
if err != nil { if err != nil {
t.Fatalf("Expected no error when no file exists, got: %v", err) t.Fatalf("Expected no error when no file exists, got: %v", err)
+1 -5
View File
@@ -95,11 +95,7 @@ func TestMigrateSyncDryRun(t *testing.T) {
// Test that branchExistsLocal returns false for non-existent branch // Test that branchExistsLocal returns false for non-existent branch
// Note: We need to run this from tmpDir context since branchExistsLocal uses git in cwd // Note: We need to run this from tmpDir context since branchExistsLocal uses git in cwd
ctx := context.Background() ctx := context.Background()
origDir, _ := os.Getwd() t.Chdir(tmpDir)
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("failed to chdir: %v", err)
}
defer os.Chdir(origDir)
if branchExistsLocal(ctx, "beads-sync") { if branchExistsLocal(ctx, "beads-sync") {
t.Error("branchExistsLocal should return false for non-existent branch") t.Error("branchExistsLocal should return false for non-existent branch")
+1 -5
View File
@@ -141,15 +141,11 @@ func TestDetectPrefix(t *testing.T) {
t.Run("empty database defaults to dir name", func(t *testing.T) { t.Run("empty database defaults to dir name", func(t *testing.T) {
// Change to temp dir so we can control directory name // Change to temp dir so we can control directory name
origWd, _ := os.Getwd()
namedDir := filepath.Join(tempDir, "myproject") namedDir := filepath.Join(tempDir, "myproject")
if err := os.MkdirAll(namedDir, 0o755); err != nil { if err := os.MkdirAll(namedDir, 0o755); err != nil {
t.Fatalf("Failed to create named dir: %v", err) t.Fatalf("Failed to create named dir: %v", err)
} }
if err := os.Chdir(namedDir); err != nil { t.Chdir(namedDir)
t.Fatalf("Failed to chdir: %v", err)
}
defer func() { _ = os.Chdir(origWd) }()
memStore := memory.New(filepath.Join(beadsDir, "issues.jsonl")) memStore := memory.New(filepath.Join(beadsDir, "issues.jsonl"))
prefix, err := detectPrefix(beadsDir, memStore) prefix, err := detectPrefix(beadsDir, memStore)
+5 -15
View File
@@ -89,9 +89,7 @@ func testFreshCloneAutoImport(t *testing.T) {
} }
// Test checkGitForIssues detects issues.jsonl // Test checkGitForIssues detects issues.jsonl
originalDir, _ := os.Getwd() t.Chdir(dir)
os.Chdir(dir)
defer os.Chdir(originalDir)
count, path := checkGitForIssues() count, path := checkGitForIssues()
if count != 1 { if count != 1 {
@@ -165,9 +163,7 @@ func testDatabaseRemovalScenario(t *testing.T) {
os.MkdirAll(beadsDir, 0755) os.MkdirAll(beadsDir, 0755)
// Change to test directory // Change to test directory
originalDir, _ := os.Getwd() t.Chdir(dir)
os.Chdir(dir)
defer os.Chdir(originalDir)
// Test checkGitForIssues finds issues.jsonl (canonical name) // Test checkGitForIssues finds issues.jsonl (canonical name)
count, path := checkGitForIssues() count, path := checkGitForIssues()
@@ -245,9 +241,7 @@ func testLegacyFilenameSupport(t *testing.T) {
runCmd(t, dir, "git", "commit", "-m", "Add legacy issue") runCmd(t, dir, "git", "commit", "-m", "Add legacy issue")
// Change to test directory // Change to test directory
originalDir, _ := os.Getwd() t.Chdir(dir)
os.Chdir(dir)
defer os.Chdir(originalDir)
// Test checkGitForIssues finds issues.jsonl // Test checkGitForIssues finds issues.jsonl
count, path := checkGitForIssues() count, path := checkGitForIssues()
@@ -323,9 +317,7 @@ func testPrecedenceTest(t *testing.T) {
runCmd(t, dir, "git", "commit", "-m", "Add both files") runCmd(t, dir, "git", "commit", "-m", "Add both files")
// Change to test directory // Change to test directory
originalDir, _ := os.Getwd() t.Chdir(dir)
os.Chdir(dir)
defer os.Chdir(originalDir)
// Test checkGitForIssues prefers issues.jsonl // Test checkGitForIssues prefers issues.jsonl
count, path := checkGitForIssues() count, path := checkGitForIssues()
@@ -371,9 +363,7 @@ func testInitSafetyCheck(t *testing.T) {
runCmd(t, dir, "git", "commit", "-m", "Add issue") runCmd(t, dir, "git", "commit", "-m", "Add issue")
// Change to test directory // Change to test directory
originalDir, _ := os.Getwd() t.Chdir(dir)
os.Chdir(dir)
defer os.Chdir(originalDir)
// Create empty database (simulating failed import) // Create empty database (simulating failed import)
dbPath := filepath.Join(beadsDir, "test.db") dbPath := filepath.Join(beadsDir, "test.db")
+2 -8
View File
@@ -118,10 +118,7 @@ incomplete line without brace
func TestGitHasUncommittedChanges_NotInGitRepo(t *testing.T) { func TestGitHasUncommittedChanges_NotInGitRepo(t *testing.T) {
tmpDir := t.TempDir() tmpDir := t.TempDir()
originalWd, _ := os.Getwd() t.Chdir(tmpDir)
defer os.Chdir(originalWd)
os.Chdir(tmpDir)
// Should error when not in a git repo // Should error when not in a git repo
_, err := gitHasUncommittedChanges() _, err := gitHasUncommittedChanges()
@@ -132,10 +129,7 @@ func TestGitHasUncommittedChanges_NotInGitRepo(t *testing.T) {
func TestGetCurrentGitHead_NotInGitRepo(t *testing.T) { func TestGetCurrentGitHead_NotInGitRepo(t *testing.T) {
tmpDir := t.TempDir() tmpDir := t.TempDir()
originalWd, _ := os.Getwd() t.Chdir(tmpDir)
defer os.Chdir(originalWd)
os.Chdir(tmpDir)
// Should error when not in a git repo // Should error when not in a git repo
_, err := getCurrentGitHead() _, err := getCurrentGitHead()
+2 -18
View File
@@ -26,15 +26,7 @@ func TestLocalOnlyMode(t *testing.T) {
runGitCmd(t, tempDir, "config", "user.name", "Test User") runGitCmd(t, tempDir, "config", "user.name", "Test User")
// Change to temp directory so git commands run in the test repo // Change to temp directory so git commands run in the test repo
oldDir, err := os.Getwd() t.Chdir(tempDir)
if err != nil {
t.Fatalf("Failed to get working dir: %v", err)
}
defer os.Chdir(oldDir)
if err := os.Chdir(tempDir); err != nil {
t.Fatalf("Failed to change to temp dir: %v", err)
}
// Verify no remote exists // Verify no remote exists
cmd := exec.Command("git", "remote") cmd := exec.Command("git", "remote")
@@ -112,15 +104,7 @@ func TestWithRemote(t *testing.T) {
runGitCmd(t, tempDir, "clone", remoteDir, cloneDir) runGitCmd(t, tempDir, "clone", remoteDir, cloneDir)
// Change to clone directory // Change to clone directory
oldDir, err := os.Getwd() t.Chdir(cloneDir)
if err != nil {
t.Fatalf("Failed to get working dir: %v", err)
}
defer os.Chdir(oldDir)
if err := os.Chdir(cloneDir); err != nil {
t.Fatalf("Failed to change to clone dir: %v", err)
}
ctx := context.Background() ctx := context.Background()
+2 -7
View File
@@ -24,10 +24,7 @@ func TestIsGitRepo_InGitRepo(t *testing.T) {
func TestIsGitRepo_NotInGitRepo(t *testing.T) { func TestIsGitRepo_NotInGitRepo(t *testing.T) {
tmpDir := t.TempDir() tmpDir := t.TempDir()
originalWd, _ := os.Getwd() t.Chdir(tmpDir)
defer os.Chdir(originalWd)
os.Chdir(tmpDir)
if isGitRepo() { if isGitRepo() {
t.Error("expected false when not in git repo") t.Error("expected false when not in git repo")
@@ -451,9 +448,7 @@ func TestZFCSkipsExportAfterImport(t *testing.T) {
} }
ctx := context.Background() ctx := context.Background()
tmpDir := t.TempDir() tmpDir := t.TempDir()
oldWd, _ := os.Getwd() t.Chdir(tmpDir)
defer os.Chdir(oldWd)
os.Chdir(tmpDir)
// Setup beads directory with JSONL // Setup beads directory with JSONL
beadsDir := filepath.Join(tmpDir, ".beads") beadsDir := filepath.Join(tmpDir, ".beads")
+2 -6
View File
@@ -77,9 +77,7 @@ func TestLoadBuiltinTemplateNotFound(t *testing.T) {
func TestLoadCustomTemplate(t *testing.T) { func TestLoadCustomTemplate(t *testing.T) {
// Create temporary directory for test // Create temporary directory for test
tmpDir := t.TempDir() tmpDir := t.TempDir()
oldWd, _ := os.Getwd() t.Chdir(tmpDir)
defer os.Chdir(oldWd)
os.Chdir(tmpDir)
// Create .beads/templates directory // Create .beads/templates directory
templatesDir := filepath.Join(".beads", "templates") templatesDir := filepath.Join(".beads", "templates")
@@ -129,9 +127,7 @@ acceptance_criteria: Test acceptance
func TestLoadTemplate_PreferCustomOverBuiltin(t *testing.T) { func TestLoadTemplate_PreferCustomOverBuiltin(t *testing.T) {
// Create temporary directory for test // Create temporary directory for test
tmpDir := t.TempDir() tmpDir := t.TempDir()
oldWd, _ := os.Getwd() t.Chdir(tmpDir)
defer os.Chdir(oldWd)
os.Chdir(tmpDir)
// Create .beads/templates directory // Create .beads/templates directory
templatesDir := filepath.Join(".beads", "templates") templatesDir := filepath.Join(".beads", "templates")
+4 -21
View File
@@ -106,12 +106,7 @@ func TestTrackBdVersion_NoBeadsDir(t *testing.T) {
// Change to temp directory with no .beads // Change to temp directory with no .beads
tmpDir := t.TempDir() tmpDir := t.TempDir()
origWd, _ := os.Getwd() t.Chdir(tmpDir)
defer os.Chdir(origWd)
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change to temp dir: %v", err)
}
// trackBdVersion should silently succeed // trackBdVersion should silently succeed
trackBdVersion() trackBdVersion()
@@ -137,11 +132,7 @@ func TestTrackBdVersion_FirstRun(t *testing.T) {
} }
// Change to temp directory // Change to temp directory
origWd, _ := os.Getwd() t.Chdir(tmpDir)
defer os.Chdir(origWd)
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change to temp dir: %v", err)
}
// Save original state // Save original state
origUpgradeDetected := versionUpgradeDetected origUpgradeDetected := versionUpgradeDetected
@@ -180,11 +171,7 @@ func TestTrackBdVersion_UpgradeDetection(t *testing.T) {
} }
// Change to temp directory // Change to temp directory
origWd, _ := os.Getwd() t.Chdir(tmpDir)
defer os.Chdir(origWd)
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change to temp dir: %v", err)
}
// Create minimal metadata.json so FindBeadsDir can find the directory (bd-420) // Create minimal metadata.json so FindBeadsDir can find the directory (bd-420)
metadataPath := filepath.Join(beadsDir, "metadata.json") metadataPath := filepath.Join(beadsDir, "metadata.json")
@@ -238,11 +225,7 @@ func TestTrackBdVersion_SameVersion(t *testing.T) {
} }
// Change to temp directory // Change to temp directory
origWd, _ := os.Getwd() t.Chdir(tmpDir)
defer os.Chdir(origWd)
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change to temp dir: %v", err)
}
// Create .local_version with current version // Create .local_version with current version
localVersionPath := filepath.Join(beadsDir, localVersionFile) localVersionPath := filepath.Join(beadsDir, localVersionFile)
+1 -6
View File
@@ -152,12 +152,7 @@ func TestFindDatabasePath(t *testing.T) {
f.Close() f.Close()
// Change to temp directory // Change to temp directory
originalWd, _ := os.Getwd() t.Chdir(tmpDir)
defer os.Chdir(originalWd)
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to chdir: %v", err)
}
// Test FindDatabasePath // Test FindDatabasePath
found := beads.FindDatabasePath() found := beads.FindDatabasePath()
+1 -5
View File
@@ -369,10 +369,6 @@ func TestBatchCreateIssues(t *testing.T) {
// TestFindDatabasePathIntegration tests the database discovery // TestFindDatabasePathIntegration tests the database discovery
func TestFindDatabasePathIntegration(t *testing.T) { func TestFindDatabasePathIntegration(t *testing.T) {
// Save original working directory
originalWd, _ := os.Getwd()
defer os.Chdir(originalWd)
// Create temporary directory with .beads // Create temporary directory with .beads
tmpDir, err := os.MkdirTemp("", "beads-find-*") tmpDir, err := os.MkdirTemp("", "beads-find-*")
if err != nil { if err != nil {
@@ -388,7 +384,7 @@ func TestFindDatabasePathIntegration(t *testing.T) {
f.Close() f.Close()
// Change to temp directory // Change to temp directory
os.Chdir(tmpDir) t.Chdir(tmpDir)
// Should find the database // Should find the database
found := beads.FindDatabasePath() found := beads.FindDatabasePath()
+3 -30
View File
@@ -58,17 +58,8 @@ func TestFindAllDatabases(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
// Save original working directory
origDir, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
defer os.Chdir(origDir)
// Change to subdir and test FindAllDatabases // Change to subdir and test FindAllDatabases
if err := os.Chdir(subdir); err != nil { t.Chdir(subdir)
t.Fatal(err)
}
databases := FindAllDatabases() databases := FindAllDatabases()
@@ -118,17 +109,8 @@ func TestFindAllDatabases_Single(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
// Save original working directory
origDir, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
defer os.Chdir(origDir)
// Change to tmpDir and test // Change to tmpDir and test
if err := os.Chdir(tmpDir); err != nil { t.Chdir(tmpDir)
t.Fatal(err)
}
databases := FindAllDatabases() databases := FindAllDatabases()
@@ -150,17 +132,8 @@ func TestFindAllDatabases_None(t *testing.T) {
} }
defer os.RemoveAll(tmpDir) defer os.RemoveAll(tmpDir)
// Save original working directory
origDir, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
defer os.Chdir(origDir)
// Change to tmpDir and test // Change to tmpDir and test
if err := os.Chdir(tmpDir); err != nil { t.Chdir(tmpDir)
t.Fatal(err)
}
databases := FindAllDatabases() databases := FindAllDatabases()
+3 -20
View File
@@ -61,17 +61,8 @@ func TestFindAllDatabases_SymlinkDeduplication(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
// Save original working directory
origDir, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
defer os.Chdir(origDir)
// Change to subdir (which is inside the symlinked directory) // Change to subdir (which is inside the symlinked directory)
if err := os.Chdir(subdir); err != nil { t.Chdir(subdir)
t.Fatal(err)
}
// Call FindAllDatabases // Call FindAllDatabases
databases := FindAllDatabases() databases := FindAllDatabases()
@@ -150,16 +141,8 @@ func TestFindAllDatabases_MultipleSymlinksToSameDB(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
// Save and change directory // Change to working directory
origDir, err := os.Getwd() t.Chdir(workdir)
if err != nil {
t.Fatal(err)
}
defer os.Chdir(origDir)
if err := os.Chdir(workdir); err != nil {
t.Fatal(err)
}
// Find databases // Find databases
databases := FindAllDatabases() databases := FindAllDatabases()
+8 -35
View File
@@ -30,16 +30,14 @@ func TestFindDatabasePathEnvVar(t *testing.T) {
} }
func TestFindDatabasePathInTree(t *testing.T) { func TestFindDatabasePathInTree(t *testing.T) {
// Save original env var and working directory // Save original env var
originalEnv := os.Getenv("BEADS_DB") originalEnv := os.Getenv("BEADS_DB")
originalWd, _ := os.Getwd()
defer func() { defer func() {
if originalEnv != "" { if originalEnv != "" {
os.Setenv("BEADS_DB", originalEnv) os.Setenv("BEADS_DB", originalEnv)
} else { } else {
os.Unsetenv("BEADS_DB") os.Unsetenv("BEADS_DB")
} }
os.Chdir(originalWd)
}() }()
// Clear env var // Clear env var
@@ -73,10 +71,7 @@ func TestFindDatabasePathInTree(t *testing.T) {
t.Fatalf("Failed to create subdirectory: %v", err) t.Fatalf("Failed to create subdirectory: %v", err)
} }
err = os.Chdir(subDir) t.Chdir(subDir)
if err != nil {
t.Fatalf("Failed to change directory: %v", err)
}
// Should find the database in the parent directory tree // Should find the database in the parent directory tree
result := FindDatabasePath() result := FindDatabasePath()
@@ -97,16 +92,14 @@ func TestFindDatabasePathInTree(t *testing.T) {
} }
func TestFindDatabasePathNotFound(t *testing.T) { func TestFindDatabasePathNotFound(t *testing.T) {
// Save original env var and working directory // Save original env var
originalEnv := os.Getenv("BEADS_DB") originalEnv := os.Getenv("BEADS_DB")
originalWd, _ := os.Getwd()
defer func() { defer func() {
if originalEnv != "" { if originalEnv != "" {
os.Setenv("BEADS_DB", originalEnv) os.Setenv("BEADS_DB", originalEnv)
} else { } else {
os.Unsetenv("BEADS_DB") os.Unsetenv("BEADS_DB")
} }
os.Chdir(originalWd)
}() }()
// Clear env var // Clear env var
@@ -119,10 +112,7 @@ func TestFindDatabasePathNotFound(t *testing.T) {
} }
defer os.RemoveAll(tmpDir) defer os.RemoveAll(tmpDir)
err = os.Chdir(tmpDir) t.Chdir(tmpDir)
if err != nil {
t.Fatalf("Failed to change directory: %v", err)
}
// Should return empty string (no database found) // Should return empty string (no database found)
result := FindDatabasePath() result := FindDatabasePath()
@@ -366,14 +356,12 @@ func TestHasBeadsProjectFiles(t *testing.T) {
func TestFindBeadsDirSkipsDaemonRegistry(t *testing.T) { func TestFindBeadsDirSkipsDaemonRegistry(t *testing.T) {
// Save original state // Save original state
originalEnv := os.Getenv("BEADS_DIR") originalEnv := os.Getenv("BEADS_DIR")
originalWd, _ := os.Getwd()
defer func() { defer func() {
if originalEnv != "" { if originalEnv != "" {
os.Setenv("BEADS_DIR", originalEnv) os.Setenv("BEADS_DIR", originalEnv)
} else { } else {
os.Unsetenv("BEADS_DIR") os.Unsetenv("BEADS_DIR")
} }
os.Chdir(originalWd)
}() }()
os.Unsetenv("BEADS_DIR") os.Unsetenv("BEADS_DIR")
@@ -394,9 +382,7 @@ func TestFindBeadsDirSkipsDaemonRegistry(t *testing.T) {
} }
// Change to temp dir // Change to temp dir
if err := os.Chdir(tmpDir); err != nil { t.Chdir(tmpDir)
t.Fatal(err)
}
// Should NOT find the daemon-only directory // Should NOT find the daemon-only directory
result := FindBeadsDir() result := FindBeadsDir()
@@ -465,14 +451,12 @@ func TestFindDatabasePathHomeDefault(t *testing.T) {
// creating the file and just verify the function doesn't crash // creating the file and just verify the function doesn't crash
originalEnv := os.Getenv("BEADS_DB") originalEnv := os.Getenv("BEADS_DB")
originalWd, _ := os.Getwd()
defer func() { defer func() {
if originalEnv != "" { if originalEnv != "" {
os.Setenv("BEADS_DB", originalEnv) os.Setenv("BEADS_DB", originalEnv)
} else { } else {
os.Unsetenv("BEADS_DB") os.Unsetenv("BEADS_DB")
} }
os.Chdir(originalWd)
}() }()
os.Unsetenv("BEADS_DB") os.Unsetenv("BEADS_DB")
@@ -484,10 +468,7 @@ func TestFindDatabasePathHomeDefault(t *testing.T) {
} }
defer os.RemoveAll(tmpDir) defer os.RemoveAll(tmpDir)
err = os.Chdir(tmpDir) t.Chdir(tmpDir)
if err != nil {
t.Fatalf("Failed to change directory: %v", err)
}
// Call FindDatabasePath - it might return home dir default or empty string // Call FindDatabasePath - it might return home dir default or empty string
result := FindDatabasePath() result := FindDatabasePath()
@@ -691,14 +672,12 @@ func TestFollowRedirect(t *testing.T) {
func TestFindDatabasePathWithRedirect(t *testing.T) { func TestFindDatabasePathWithRedirect(t *testing.T) {
// Save original state // Save original state
originalEnv := os.Getenv("BEADS_DIR") originalEnv := os.Getenv("BEADS_DIR")
originalWd, _ := os.Getwd()
defer func() { defer func() {
if originalEnv != "" { if originalEnv != "" {
os.Setenv("BEADS_DIR", originalEnv) os.Setenv("BEADS_DIR", originalEnv)
} else { } else {
os.Unsetenv("BEADS_DIR") os.Unsetenv("BEADS_DIR")
} }
os.Chdir(originalWd)
}() }()
os.Unsetenv("BEADS_DIR") os.Unsetenv("BEADS_DIR")
@@ -733,9 +712,7 @@ func TestFindDatabasePathWithRedirect(t *testing.T) {
// Change to project directory // Change to project directory
projectDir := filepath.Join(tmpDir, "project") projectDir := filepath.Join(tmpDir, "project")
if err := os.Chdir(projectDir); err != nil { t.Chdir(projectDir)
t.Fatal(err)
}
// FindDatabasePath should follow the redirect // FindDatabasePath should follow the redirect
result := FindDatabasePath() result := FindDatabasePath()
@@ -753,14 +730,12 @@ func TestFindDatabasePathWithRedirect(t *testing.T) {
func TestFindBeadsDirWithRedirect(t *testing.T) { func TestFindBeadsDirWithRedirect(t *testing.T) {
// Save original state // Save original state
originalEnv := os.Getenv("BEADS_DIR") originalEnv := os.Getenv("BEADS_DIR")
originalWd, _ := os.Getwd()
defer func() { defer func() {
if originalEnv != "" { if originalEnv != "" {
os.Setenv("BEADS_DIR", originalEnv) os.Setenv("BEADS_DIR", originalEnv)
} else { } else {
os.Unsetenv("BEADS_DIR") os.Unsetenv("BEADS_DIR")
} }
os.Chdir(originalWd)
}() }()
os.Unsetenv("BEADS_DIR") os.Unsetenv("BEADS_DIR")
@@ -794,9 +769,7 @@ func TestFindBeadsDirWithRedirect(t *testing.T) {
// Change to project directory // Change to project directory
projectDir := filepath.Join(tmpDir, "project") projectDir := filepath.Join(tmpDir, "project")
if err := os.Chdir(projectDir); err != nil { t.Chdir(projectDir)
t.Fatal(err)
}
// FindBeadsDir should follow the redirect // FindBeadsDir should follow the redirect
result := FindBeadsDir() result := FindBeadsDir()
+13 -41
View File
@@ -105,30 +105,23 @@ flush-debounce: 15s
t.Fatalf("failed to write config file: %v", err) t.Fatalf("failed to write config file: %v", err)
} }
// Change to tmp directory so config file is discovered
origDir, err := os.Getwd()
if err != nil {
t.Fatalf("failed to get working directory: %v", err)
}
defer os.Chdir(origDir)
// Create .beads directory // Create .beads directory
beadsDir := filepath.Join(tmpDir, ".beads") beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0750); err != nil { if err := os.MkdirAll(beadsDir, 0750); err != nil {
t.Fatalf("failed to create .beads directory: %v", err) t.Fatalf("failed to create .beads directory: %v", err)
} }
// Move config to .beads directory // Move config to .beads directory
beadsConfigPath := filepath.Join(beadsDir, "config.yaml") beadsConfigPath := filepath.Join(beadsDir, "config.yaml")
if err := os.Rename(configPath, beadsConfigPath); err != nil { if err := os.Rename(configPath, beadsConfigPath); err != nil {
t.Fatalf("failed to move config file: %v", err) t.Fatalf("failed to move config file: %v", err)
} }
if err := os.Chdir(tmpDir); err != nil { // Change to tmp directory so config file is discovered
t.Fatalf("failed to change directory: %v", err) t.Chdir(tmpDir)
}
// Initialize viper // Initialize viper
var err error
err = Initialize() err = Initialize()
if err != nil { if err != nil {
t.Fatalf("Initialize() returned error: %v", err) t.Fatalf("Initialize() returned error: %v", err)
@@ -169,17 +162,10 @@ func TestConfigPrecedence(t *testing.T) {
} }
// Change to tmp directory // Change to tmp directory
origDir, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
t.Fatalf("failed to get working directory: %v", err)
}
defer os.Chdir(origDir)
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("failed to change directory: %v", err)
}
// Test 1: Config file value (json: false) // Test 1: Config file value (json: false)
var err error
err = Initialize() err = Initialize()
if err != nil { if err != nil {
t.Fatalf("Initialize() returned error: %v", err) t.Fatalf("Initialize() returned error: %v", err)
@@ -288,17 +274,10 @@ repos:
} }
// Change to tmp directory // Change to tmp directory
origDir, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
t.Fatalf("failed to get working directory: %v", err)
}
defer os.Chdir(origDir)
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("failed to change directory: %v", err)
}
// Initialize viper // Initialize viper
var err error
err = Initialize() err = Initialize()
if err != nil { if err != nil {
t.Fatalf("Initialize() returned error: %v", err) t.Fatalf("Initialize() returned error: %v", err)
@@ -365,17 +344,10 @@ repos:
} }
// Change to tmp directory // Change to tmp directory
origDir, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
t.Fatalf("failed to get working directory: %v", err)
}
defer os.Chdir(origDir)
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("failed to change directory: %v", err)
}
// Initialize viper // Initialize viper
var err error
err = Initialize() err = Initialize()
if err != nil { if err != nil {
t.Fatalf("Initialize() returned error: %v", err) t.Fatalf("Initialize() returned error: %v", err)
+1 -17
View File
@@ -297,28 +297,13 @@ func setupBenchServer(b *testing.B) (*Server, *Client, func(), string) {
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
// Change to tmpDir so client's os.Getwd() finds the test database // Change to tmpDir so client's os.Getwd() finds the test database
originalWd, err := os.Getwd() b.Chdir(tmpDir)
if err != nil {
cancel()
server.Stop()
store.Close()
os.RemoveAll(tmpDir)
b.Fatalf("Failed to get working directory: %v", err)
}
if err := os.Chdir(tmpDir); err != nil {
cancel()
server.Stop()
store.Close()
os.RemoveAll(tmpDir)
b.Fatalf("Failed to change directory: %v", err)
}
client, err := TryConnect(socketPath) client, err := TryConnect(socketPath)
if err != nil { if err != nil {
cancel() cancel()
server.Stop() server.Stop()
store.Close() store.Close()
os.Chdir(originalWd)
os.RemoveAll(tmpDir) os.RemoveAll(tmpDir)
b.Fatalf("Failed to connect client: %v", err) b.Fatalf("Failed to connect client: %v", err)
} }
@@ -331,7 +316,6 @@ func setupBenchServer(b *testing.B) (*Server, *Client, func(), string) {
cancel() cancel()
server.Stop() server.Stop()
store.Close() store.Close()
os.Chdir(originalWd) // Restore original working directory
os.RemoveAll(tmpDir) os.RemoveAll(tmpDir)
} }
+1 -16
View File
@@ -68,21 +68,7 @@ func setupTestServerWithStore(t *testing.T) (*Server, *Client, *sqlitestorage.SQ
} }
} }
originalWd, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
cancel()
server.Stop()
store.Close()
os.RemoveAll(tmpDir)
t.Fatalf("Failed to get working directory: %v", err)
}
if err := os.Chdir(tmpDir); err != nil {
cancel()
server.Stop()
store.Close()
os.RemoveAll(tmpDir)
t.Fatalf("Failed to change directory: %v", err)
}
client, err := TryConnect(socketPath) client, err := TryConnect(socketPath)
if err != nil { if err != nil {
@@ -108,7 +94,6 @@ func setupTestServerWithStore(t *testing.T) (*Server, *Client, *sqlitestorage.SQ
cancel() cancel()
server.Stop() server.Stop()
store.Close() store.Close()
os.Chdir(originalWd)
os.RemoveAll(tmpDir) os.RemoveAll(tmpDir)
} }
+4 -23
View File
@@ -76,22 +76,8 @@ func setupTestServer(t *testing.T) (*Server, *Client, func()) {
} }
} }
// Change to tmpDir so client's os.Getwd() finds the test database // Change to tmpDir so client's os.Getwd() finds the test database.
originalWd, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
cancel()
server.Stop()
store.Close()
os.RemoveAll(tmpDir)
t.Fatalf("Failed to get working directory: %v", err)
}
if err := os.Chdir(tmpDir); err != nil {
cancel()
server.Stop()
store.Close()
os.RemoveAll(tmpDir)
t.Fatalf("Failed to change directory: %v", err)
}
client, err := TryConnect(socketPath) client, err := TryConnect(socketPath)
if err != nil { if err != nil {
@@ -118,7 +104,6 @@ func setupTestServer(t *testing.T) (*Server, *Client, func()) {
cancel() cancel()
server.Stop() server.Stop()
store.Close() store.Close()
os.Chdir(originalWd) // Restore original working directory
os.RemoveAll(tmpDir) os.RemoveAll(tmpDir)
} }
@@ -445,9 +430,6 @@ func TestConcurrentRequests(t *testing.T) {
} }
func TestDatabaseHandshake(t *testing.T) { func TestDatabaseHandshake(t *testing.T) {
// Save original directory and change to a temp directory for test isolation
origDir, _ := os.Getwd()
// Create two separate databases and daemons // Create two separate databases and daemons
tmpDir1, err := os.MkdirTemp("", "bd-test-db1-*") tmpDir1, err := os.MkdirTemp("", "bd-test-db1-*")
if err != nil { if err != nil {
@@ -492,9 +474,8 @@ func TestDatabaseHandshake(t *testing.T) {
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
// Test 1: Client with correct ExpectedDB should succeed // Test 1: Client with correct ExpectedDB should succeed
// Change to tmpDir1 so cwd resolution doesn't find other databases // Change to tmpDir1 so cwd resolution doesn't find other databases.
os.Chdir(tmpDir1) t.Chdir(tmpDir1)
defer os.Chdir(origDir)
client1, err := TryConnect(socketPath1) client1, err := TryConnect(socketPath1)
if err != nil { if err != nil {
+5 -41
View File
@@ -6,7 +6,6 @@ package rpc
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"os"
"testing" "testing"
"time" "time"
@@ -117,14 +116,7 @@ func TestVersionCompatibility(t *testing.T) {
defer func() { ClientVersion = originalClientVersion }() defer func() { ClientVersion = originalClientVersion }()
// Change to tmpDir so client's os.Getwd() finds the test database // Change to tmpDir so client's os.Getwd() finds the test database
originalWd, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change directory: %v", err)
}
defer os.Chdir(originalWd)
client, err := TryConnect(socketPath) client, err := TryConnect(socketPath)
if err != nil { if err != nil {
@@ -202,14 +194,7 @@ func TestHealthCheckIncludesVersionInfo(t *testing.T) {
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
// Change to tmpDir so client's os.Getwd() finds the test database // Change to tmpDir so client's os.Getwd() finds the test database
originalWd, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change directory: %v", err)
}
defer os.Chdir(originalWd)
client, err := TryConnect(socketPath) client, err := TryConnect(socketPath)
if err != nil { if err != nil {
@@ -266,14 +251,7 @@ func TestIncompatibleVersionInHealth(t *testing.T) {
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
// Change to tmpDir so client's os.Getwd() finds the test database // Change to tmpDir so client's os.Getwd() finds the test database
originalWd, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change directory: %v", err)
}
defer os.Chdir(originalWd)
client, err := TryConnect(socketPath) client, err := TryConnect(socketPath)
if err != nil { if err != nil {
@@ -386,14 +364,7 @@ func TestPingAndHealthBypassVersionCheck(t *testing.T) {
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
// Change to tmpDir so client's os.Getwd() finds the test database // Change to tmpDir so client's os.Getwd() finds the test database
originalWd, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change directory: %v", err)
}
defer os.Chdir(originalWd)
client, err := TryConnect(socketPath) client, err := TryConnect(socketPath)
if err != nil { if err != nil {
@@ -460,14 +431,7 @@ func TestMetricsOperation(t *testing.T) {
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
// Change to tmpDir so client's os.Getwd() finds the test database // Change to tmpDir so client's os.Getwd() finds the test database
originalWd, err := os.Getwd() t.Chdir(tmpDir)
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change directory: %v", err)
}
defer os.Chdir(originalWd)
client, err := TryConnect(socketPath) client, err := TryConnect(socketPath)
if err != nil { if err != nil {