Skip to content

Commit

Permalink
feat: add test helper for changing work directory
Browse files Browse the repository at this point in the history
Signed-off-by: Brian McGee <[email protected]>
  • Loading branch information
brianmcgee committed Oct 21, 2024
1 parent 500c356 commit 45592a9
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 20 deletions.
22 changes: 2 additions & 20 deletions cmd/root_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,18 +27,9 @@ import (
func TestOnUnmatched(t *testing.T) {
as := require.New(t)

// capture current cwd, so we can replace it after the test is finished
cwd, err := os.Getwd()
as.NoError(err)

t.Cleanup(func() {
// return to the previous working directory
as.NoError(os.Chdir(cwd))
})

tempDir := test.TempExamples(t)

as.NoError(os.Chdir(tempDir), "failed to change to temp dir")
test.ChangeWorkDir(t, tempDir)

paths := []string{
"go/go.mod",
Expand Down Expand Up @@ -130,17 +121,8 @@ func TestCpuProfile(t *testing.T) {
as := require.New(t)
tempDir := test.TempExamples(t)

// capture current cwd, so we can replace it after the test is finished
cwd, err := os.Getwd()
as.NoError(err)

t.Cleanup(func() {
// return to the previous working directory
as.NoError(os.Chdir(cwd))
})
test.ChangeWorkDir(t, tempDir)

// change to temp dir
as.NoError(os.Chdir(tempDir), "failed to change to temp dir")
// allow missing formatter
t.Setenv("TREEFMT_ALLOW_MISSING_FORMATTER", "true")

Expand Down
24 changes: 24 additions & 0 deletions test/test.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,27 @@ func Lutimes(t *testing.T, path string, atime time.Time, mtime time.Time) error

return nil
}

// ChangeWorkDir changes the current working directory for the duration of the test.
// The original directory is restored when the test ends.
func ChangeWorkDir(t *testing.T, dir string) {
t.Helper()

// capture current cwd, so we can replace it after the test is finished
cwd, err := os.Getwd()
if err != nil {
t.Fatal(fmt.Errorf("failed to get current working directory: %w", err))
}

t.Cleanup(func() {
// return to the previous working directory
if err := os.Chdir(cwd); err != nil {
t.Fatal(fmt.Errorf("failed to return to the previous working directory: %w", err))
}
})

// change to the new directory
if err := os.Chdir(dir); err != nil {
t.Fatal(fmt.Errorf("failed to change working directory to %s: %w", dir, err))
}
}

0 comments on commit 45592a9

Please sign in to comment.