Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

proposal: testing: add TB.Chdir #62516

Open
kolyshkin opened this issue Sep 7, 2023 · 2 comments
Open

proposal: testing: add TB.Chdir #62516

kolyshkin opened this issue Sep 7, 2023 · 2 comments
Labels
Milestone

Comments

@kolyshkin
Copy link
Contributor

kolyshkin commented Sep 7, 2023

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

@gopherbot
Copy link

Change https://go.dev/cl/526717 mentions this issue: testing: add Chdir

@gopherbot
Copy link

Change https://go.dev/cl/529895 mentions this issue: testing: add Chdir

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
Status: Incoming
Development

No branches or pull requests

2 participants