golang/go

all: tests that change the working directory should use defer to restore it

Open

#45.182 aperta il 23 mar 2021

Vedi su GitHub
 (20 commenti) (4 reazioni) (0 assegnatari)Go (19.008 fork)batch import
NeedsFixTestinghelp wanted

Metriche repository

Star
 (133.883 star)
Metriche merge PR
 (Nessuna PR mergiata in 30 g)

Descrizione

What version of Go are you using (go version)?

I have noted that the tests that need to change the current working directory use the following pattern:

  1. call os.Getwd to get the current working directory
  2. some code
  3. call os.Chdir to change the current working directory
  4. some code
  5. call os.Chdir to restore the original working directory

An example is: https://github.com/golang/go/blob/master/src/os/removeall_test.go#L159

The code should probably use defer, using a support function like:

// chdir changes the current working directory to the named directory and
// returns a function that, when called, restores the original working
// directory.
func chdir(t *testing.T, dir string) func() {
	wd, err := os.Getwd()
	if err != nil {
		t.Fatalf("chdir %s: %v", dir, err)
	}
	if err := os.Chdir(dir); err != nil {
		t.Fatal(err)
	}

	return func() {
		if err := os.Chdir(wd); err != nil {
			t.Fatalf("restoring working directory: %v", err)
		}
	}
}

The new pattern is:

  1. call defer chdir(dir)()
  2. some code

This is more readable and ensures that the working directory is restored in case of test failures.

Guida contributor