Skip to content

test: use t.TempDir to create temporary test directory#1527

Merged
traefiker merged 1 commit into
traefik:masterfrom
Juneezee:test/t.TempDir
Mar 16, 2023
Merged

test: use t.TempDir to create temporary test directory#1527
traefiker merged 1 commit into
traefik:masterfrom
Juneezee:test/t.TempDir

Conversation

@Juneezee

Copy link
Copy Markdown
Contributor

This pull request replaces os.MkdirTemp with t.TempDir. We can use the t.TempDir function from the testing package to create temporary directory. The directory created by t.TempDir is automatically removed when the test and all its subtests complete.

Reference: https://pkg.go.dev/testing#T.TempDir

func TestFoo(t *testing.T) {
	// before
	tmpDir, err := os.MkdirTemp("", "")
	if err != nil {
		t.Fatalf("failed to create tmp directory: %v", err)
	}
	defer func() {
		if err := os.RemoveAll(dir); err != nil {
			t.Fatal(err)
		}
	}

	// now
	tmpDir := t.TempDir()
}

This commit replaces `os.MkdirTemp` with `t.TempDir` in tests. The
directory created by `t.TempDir` is automatically removed when the test
and all its subtests [complete.

Prior to this commit, temporary directory created using `os.MkdirTemp`
needs to be removed manually by calling `os.RemoveAll`, which is omitted
in some tests. The error handling boilerplate e.g.
	defer func() {
		if err := os.RemoveAll(dir); err != nil {
			t.Fatal(err)
		}
	}
is also tedious, but `t.TempDir` handles this for us nicely.

Reference: https://pkg.go.dev/testing#T.TempDir
Signed-off-by: Eng Zer Jun <[email protected]>
@CLAassistant

CLAassistant commented Mar 16, 2023

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@mvertes mvertes left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me. Thank you for this contribution.

@mvertes mvertes added this to the v0.15.x milestone Mar 16, 2023
@traefiker traefiker merged commit c473dce into traefik:master Mar 16, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/test enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants