golang/go

testing: document that directories returned by TB.TempDir should not be accessed after cleanup

Closed

#43,547 opened on Jan 6, 2021

 (3 comments) (0 reactions) (0 assignees)Go (19,008 forks)batch import
DocumentationNeedsFixhelp wanted

Repository metrics

Stars
 (133,883 stars)
PR merge metrics
 (No merged PRs in 30d)

Description

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

Does this issue reproduce with the latest release?

Yes

What operating system and processor architecture are you using (go env)?

What did you do?

func TestTest(t *testing.T) {
	d := t.TempDir()
	go func() {
		c := 0
		for {
			ioutil.WriteFile(filepath.Join(d, fmt.Sprint(c)), nil, 0600)
			c++
		}
	}()
	t.TempDir()
}

What did you expect to see?

Test passes. Alternatively, this caveat is sufficiently documented in t.TempDir and/or RemoveAll.

What did you see instead?

Test fails with: testing.go:915: TempDir RemoveAll cleanup: unlinkat /tmp/TestTest064788875/001: directory not empty

This happens about 50% of the time in this case. In the real world scenario I am actually trying to test, it happens about 0.001% of the time, which makes it quite frustrating.

A manual version of t.TempDir which ignores this error passes, for what its worth.

func TestManual(t *testing.T) {
	d, err := ioutil.TempDir("", "test")
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() {
		if err := os.RemoveAll(d); err != nil {
			if err.(*os.PathError).Op != "unlinkat" {
				t.Errorf("TempDir RemoveAll cleanup: %v", err)
			}
		}
	})
	go func() {
		c := 0
		for {
			ioutil.WriteFile(filepath.Join(d, fmt.Sprint(c)), nil, 0600)
			c++
		}
	}()
}

I think I understand why it works this way, and unfortunately I don't see any great options here, so perhaps just some documentation around this is the best path forward.

Contributor guide