Skip to content

testing: add TB.Chdir #62516

Closed
Closed
@kolyshkin

Description

@kolyshkin

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:

  1. func chdir(t *testing.T, dir string) {
  2. func chtmpdir(t *testing.T) func() {
  3. func chdir(t *testing.T, dir string) {
  4. func chtmpdir(t *testing.T) (restore func()) {
  5. func chtmpdir(t *testing.T) func() {

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    Accepted

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions