testutil: add testutil.Chdir() helper

A tiny helper to run a specific function inside a different dir,
useful in our testsuite.
This commit is contained in:
Michael Vogt 2025-03-13 21:21:28 +01:00 committed by Simon de Vlieger
parent ccb4269b62
commit 2f0caddf91
2 changed files with 28 additions and 0 deletions

View file

@ -110,3 +110,19 @@ func CaptureStdio(t *testing.T, f func()) (string, string) {
wg.Wait()
return stdout.String(), stderr.String()
}
func Chdir(t *testing.T, dir string, f func()) {
cwd, err := os.Getwd()
if err != nil {
t.Errorf("%s", err.Error())
}
defer func() {
os.Chdir(cwd)
}()
err = os.Chdir(dir)
if err != nil {
t.Errorf("%s", err.Error())
}
f()
}

View file

@ -34,3 +34,15 @@ func TestCaptureStdout(t *testing.T) {
assert.Equal(t, "output on stdout", stdout)
assert.Equal(t, "output on stderr", stderr)
}
func TestChroot(t *testing.T) {
tmpdir := t.TempDir()
testutil.Chdir(t, tmpdir, func() {
cwd, err := os.Getwd()
assert.NoError(t, err)
assert.Equal(t, tmpdir, cwd)
})
cwd, err := os.Getwd()
assert.NoError(t, err)
assert.NotEqual(t, tmpdir, cwd)
}