From 45592a9881899ac6823cf12c681ca29808072614 Mon Sep 17 00:00:00 2001 From: Brian McGee Date: Sat, 19 Oct 2024 10:39:21 +0100 Subject: [PATCH] feat: add test helper for changing work directory Signed-off-by: Brian McGee --- cmd/root_test.go | 22 ++-------------------- test/test.go | 24 ++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 20 deletions(-) diff --git a/cmd/root_test.go b/cmd/root_test.go index 8343deec..5dc5abb7 100644 --- a/cmd/root_test.go +++ b/cmd/root_test.go @@ -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", @@ -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") diff --git a/test/test.go b/test/test.go index 6939474a..909cb3ec 100644 --- a/test/test.go +++ b/test/test.go @@ -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)) + } +}