Description
Sometimes a test need to call os.Chdir()
. Here is a bare minimum implementation of what's needed from a test to do that:
oldwd, err := Getwd()
if err != nil {
t.Fatal(err)
}
if err := Chdir(dir); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := Chdir(oldwd); err != nil {
// It's not safe to continue with tests if we can't get back to
// the original working directory.
panic(err)
}
})
The code above can be used as a test helper; in fact, this repository already contains at least 5 helpers similar to the one above:
Line 35 in 1d538f1
Line 917 in 1d538f1
go/src/path/filepath/path_test.go
Line 510 in 1d538f1
go/src/path/filepath/path_test.go
Line 527 in 1d538f1
go/src/syscall/syscall_linux_test.go
Line 27 in 1d538f1
In addition, there are a few in-line implementations of the same functionality, another implementation in golang.org/x/sys/unix and so on.
The problem with this (except for multiple implementations and re-implementations) is, tests that use it can not use t.Parallel
. Currently, there is no way to ensure that.
The issue is very similar to one for os.Setenv
(#41260, fixed by https://golang.org/cl/326790); thus the solution is also similar.
The proposal is to add a Chdir method to the testing package, which will take care about all of the above.
The implementation may look like this: https://go-review.googlesource.com/c/go/+/529895