From f90bf84ba7a4108df6727ea523f7638d190ac5e6 Mon Sep 17 00:00:00 2001
From: greatroar <61184462+greatroar@users.noreply.github.com>
Date: Fri, 9 Dec 2022 13:42:33 +0100
Subject: [PATCH] test: Use testing.T.Cleanup to remove tempdirs

---
 cmd/restic/cmd_backup_test.go                 |  3 +--
 cmd/restic/exclude_test.go                    |  9 +++----
 cmd/restic/global_test.go                     |  3 +--
 cmd/restic/secondary_repo_test.go             |  6 ++---
 internal/archiver/archiver_test.go            | 24 ++++++-------------
 internal/archiver/file_saver_test.go          |  9 ++++---
 internal/archiver/scanner_test.go             | 12 +++-------
 internal/archiver/testing_test.go             | 13 ++++------
 internal/archiver/tree_test.go                |  4 +---
 internal/backend/layout/layout_test.go        | 18 +++++---------
 internal/backend/local/layout_test.go         |  3 +--
 internal/backend/local/local_internal_test.go |  3 +--
 internal/backend/local/local_test.go          |  3 +--
 internal/backend/rclone/backend_test.go       |  9 +------
 internal/backend/rclone/internal_test.go      |  4 +---
 internal/backend/rest/rest_test.go            |  8 ++-----
 internal/backend/s3/s3_test.go                | 10 +++-----
 internal/backend/sftp/layout_test.go          |  3 +--
 internal/backend/test/suite.go                |  6 +++--
 internal/cache/backend_test.go                | 14 +++--------
 internal/cache/file_test.go                   | 10 +++-----
 internal/cache/testing.go                     |  6 ++---
 internal/dump/common_test.go                  |  9 ++-----
 internal/fs/stat_test.go                      |  4 +---
 internal/restic/rewind_reader_test.go         |  4 +---
 internal/restorer/filerestorer_test.go        | 12 ++++------
 internal/restorer/fileswriter_test.go         |  4 +---
 internal/restorer/preallocate_test.go         |  3 +--
 internal/restorer/restorer_test.go            | 24 +++++--------------
 internal/restorer/restorer_unix_test.go       |  4 +---
 internal/test/helpers.go                      | 11 +++++----
 31 files changed, 79 insertions(+), 176 deletions(-)

diff --git a/cmd/restic/cmd_backup_test.go b/cmd/restic/cmd_backup_test.go
index 49642b872..5cbc42436 100644
--- a/cmd/restic/cmd_backup_test.go
+++ b/cmd/restic/cmd_backup_test.go
@@ -14,8 +14,7 @@ import (
 )
 
 func TestCollectTargets(t *testing.T) {
-	dir, cleanup := rtest.TempDir(t)
-	defer cleanup()
+	dir := rtest.TempDir(t)
 
 	fooSpace := "foo "
 	barStar := "bar*"              // Must sort before the others, below.
diff --git a/cmd/restic/exclude_test.go b/cmd/restic/exclude_test.go
index 5ae82d8f6..050a083e4 100644
--- a/cmd/restic/exclude_test.go
+++ b/cmd/restic/exclude_test.go
@@ -84,8 +84,7 @@ func TestIsExcludedByFile(t *testing.T) {
 	}
 	for _, tc := range tests {
 		t.Run(tc.name, func(t *testing.T) {
-			tempDir, cleanup := test.TempDir(t)
-			defer cleanup()
+			tempDir := test.TempDir(t)
 
 			foo := filepath.Join(tempDir, "foo")
 			err := os.WriteFile(foo, []byte("foo"), 0666)
@@ -115,8 +114,7 @@ func TestIsExcludedByFile(t *testing.T) {
 // cancel each other out. It was initially written to demonstrate a bug in
 // rejectIfPresent.
 func TestMultipleIsExcludedByFile(t *testing.T) {
-	tempDir, cleanup := test.TempDir(t)
-	defer cleanup()
+	tempDir := test.TempDir(t)
 
 	// Create some files in a temporary directory.
 	// Files in UPPERCASE will be used as exclusion triggers later on.
@@ -240,8 +238,7 @@ func TestParseInvalidSizeStr(t *testing.T) {
 // TestIsExcludedByFileSize is for testing the instance of
 // --exclude-larger-than parameters
 func TestIsExcludedByFileSize(t *testing.T) {
-	tempDir, cleanup := test.TempDir(t)
-	defer cleanup()
+	tempDir := test.TempDir(t)
 
 	// Max size of file is set to be 1k
 	maxSizeStr := "1k"
diff --git a/cmd/restic/global_test.go b/cmd/restic/global_test.go
index e14c77bd1..85a9514b9 100644
--- a/cmd/restic/global_test.go
+++ b/cmd/restic/global_test.go
@@ -31,8 +31,7 @@ func Test_PrintFunctionsRespectsGlobalStdout(t *testing.T) {
 }
 
 func TestReadRepo(t *testing.T) {
-	tempDir, cleanup := test.TempDir(t)
-	defer cleanup()
+	tempDir := test.TempDir(t)
 
 	// test --repo option
 	var opts GlobalOptions
diff --git a/cmd/restic/secondary_repo_test.go b/cmd/restic/secondary_repo_test.go
index a69081ea7..ff1a10b03 100644
--- a/cmd/restic/secondary_repo_test.go
+++ b/cmd/restic/secondary_repo_test.go
@@ -160,10 +160,8 @@ func TestFillSecondaryGlobalOpts(t *testing.T) {
 	}
 
 	//Create temp dir to create password file.
-	dir, cleanup := rtest.TempDir(t)
-	defer cleanup()
-
-	cleanup = rtest.Chdir(t, dir)
+	dir := rtest.TempDir(t)
+	cleanup := rtest.Chdir(t, dir)
 	defer cleanup()
 
 	//Create temporary password file
diff --git a/internal/archiver/archiver_test.go b/internal/archiver/archiver_test.go
index abdc212d0..2af6facd7 100644
--- a/internal/archiver/archiver_test.go
+++ b/internal/archiver/archiver_test.go
@@ -26,17 +26,12 @@ import (
 )
 
 func prepareTempdirRepoSrc(t testing.TB, src TestDir) (tempdir string, repo restic.Repository, cleanup func()) {
-	tempdir, removeTempdir := restictest.TempDir(t)
+	tempdir = restictest.TempDir(t)
 	repo, removeRepository := repository.TestRepository(t)
 
 	TestCreateFiles(t, tempdir, src)
 
-	cleanup = func() {
-		removeRepository()
-		removeTempdir()
-	}
-
-	return tempdir, repo, cleanup
+	return tempdir, repo, removeRepository
 }
 
 func saveFile(t testing.TB, repo restic.Repository, filename string, filesystem fs.FS) (*restic.Node, ItemStats) {
@@ -470,8 +465,7 @@ func appendToFile(t testing.TB, filename string, data []byte) {
 }
 
 func TestArchiverSaveFileIncremental(t *testing.T) {
-	tempdir, removeTempdir := restictest.TempDir(t)
-	defer removeTempdir()
+	tempdir := restictest.TempDir(t)
 
 	testRepo, removeRepository := repository.TestRepository(t)
 	defer removeRepository()
@@ -688,8 +682,7 @@ func TestFileChanged(t *testing.T) {
 				t.Skip("don't run test on Windows")
 			}
 
-			tempdir, cleanup := restictest.TempDir(t)
-			defer cleanup()
+			tempdir := restictest.TempDir(t)
 
 			filename := filepath.Join(tempdir, "file")
 			content := defaultContent
@@ -725,8 +718,7 @@ func TestFileChanged(t *testing.T) {
 }
 
 func TestFilChangedSpecialCases(t *testing.T) {
-	tempdir, cleanup := restictest.TempDir(t)
-	defer cleanup()
+	tempdir := restictest.TempDir(t)
 
 	filename := filepath.Join(tempdir, "file")
 	content := []byte("foobar")
@@ -913,8 +905,7 @@ func TestArchiverSaveDir(t *testing.T) {
 }
 
 func TestArchiverSaveDirIncremental(t *testing.T) {
-	tempdir, removeTempdir := restictest.TempDir(t)
-	defer removeTempdir()
+	tempdir := restictest.TempDir(t)
 
 	testRepo, removeRepository := repository.TestRepository(t)
 	defer removeRepository()
@@ -1901,11 +1892,10 @@ func TestArchiverContextCanceled(t *testing.T) {
 	ctx, cancel := context.WithCancel(context.Background())
 	cancel()
 
-	tempdir, removeTempdir := restictest.TempDir(t)
+	tempdir := restictest.TempDir(t)
 	TestCreateFiles(t, tempdir, TestDir{
 		"targetfile": TestFile{Content: "foobar"},
 	})
-	defer removeTempdir()
 
 	// Ensure that the archiver itself reports the canceled context and not just the backend
 	repo, _ := repository.TestRepositoryWithBackend(t, &noCancelBackend{mem.New()}, 0)
diff --git a/internal/archiver/file_saver_test.go b/internal/archiver/file_saver_test.go
index e5332d746..5c4472c62 100644
--- a/internal/archiver/file_saver_test.go
+++ b/internal/archiver/file_saver_test.go
@@ -15,8 +15,8 @@ import (
 	"golang.org/x/sync/errgroup"
 )
 
-func createTestFiles(t testing.TB, num int) (files []string, cleanup func()) {
-	tempdir, cleanup := test.TempDir(t)
+func createTestFiles(t testing.TB, num int) (files []string) {
+	tempdir := test.TempDir(t)
 
 	for i := 0; i < 15; i++ {
 		filename := fmt.Sprintf("testfile-%d", i)
@@ -27,7 +27,7 @@ func createTestFiles(t testing.TB, num int) (files []string, cleanup func()) {
 		files = append(files, filepath.Join(tempdir, filename))
 	}
 
-	return files, cleanup
+	return files
 }
 
 func startFileSaver(ctx context.Context, t testing.TB) (*FileSaver, context.Context, *errgroup.Group) {
@@ -60,8 +60,7 @@ func TestFileSaver(t *testing.T) {
 	ctx, cancel := context.WithCancel(context.Background())
 	defer cancel()
 
-	files, cleanup := createTestFiles(t, 15)
-	defer cleanup()
+	files := createTestFiles(t, 15)
 
 	startFn := func() {}
 	completeReadingFn := func() {}
diff --git a/internal/archiver/scanner_test.go b/internal/archiver/scanner_test.go
index 87d8c887d..1b4cd1f7f 100644
--- a/internal/archiver/scanner_test.go
+++ b/internal/archiver/scanner_test.go
@@ -81,9 +81,7 @@ func TestScanner(t *testing.T) {
 			ctx, cancel := context.WithCancel(context.Background())
 			defer cancel()
 
-			tempdir, cleanup := restictest.TempDir(t)
-			defer cleanup()
-
+			tempdir := restictest.TempDir(t)
 			TestCreateFiles(t, tempdir, test.src)
 
 			back := restictest.Chdir(t, tempdir)
@@ -218,9 +216,7 @@ func TestScannerError(t *testing.T) {
 			ctx, cancel := context.WithCancel(context.Background())
 			defer cancel()
 
-			tempdir, cleanup := restictest.TempDir(t)
-			defer cleanup()
-
+			tempdir := restictest.TempDir(t)
 			TestCreateFiles(t, tempdir, test.src)
 
 			back := restictest.Chdir(t, tempdir)
@@ -292,9 +288,7 @@ func TestScannerCancel(t *testing.T) {
 	ctx, cancel := context.WithCancel(context.Background())
 	defer cancel()
 
-	tempdir, cleanup := restictest.TempDir(t)
-	defer cleanup()
-
+	tempdir := restictest.TempDir(t)
 	TestCreateFiles(t, tempdir, src)
 
 	back := restictest.Chdir(t, tempdir)
diff --git a/internal/archiver/testing_test.go b/internal/archiver/testing_test.go
index f9009223b..12f54cbec 100644
--- a/internal/archiver/testing_test.go
+++ b/internal/archiver/testing_test.go
@@ -101,8 +101,7 @@ func TestTestCreateFiles(t *testing.T) {
 	}
 
 	for i, test := range tests {
-		tempdir, cleanup := restictest.TempDir(t)
-		defer cleanup()
+		tempdir := restictest.TempDir(t)
 
 		t.Run("", func(t *testing.T) {
 			tempdir := filepath.Join(tempdir, fmt.Sprintf("test-%d", i))
@@ -192,8 +191,7 @@ func TestTestWalkFiles(t *testing.T) {
 
 	for _, test := range tests {
 		t.Run("", func(t *testing.T) {
-			tempdir, cleanup := restictest.TempDir(t)
-			defer cleanup()
+			tempdir := restictest.TempDir(t)
 
 			got := make(map[string]string)
 
@@ -323,9 +321,7 @@ func TestTestEnsureFiles(t *testing.T) {
 
 	for _, test := range tests {
 		t.Run("", func(t *testing.T) {
-			tempdir, cleanup := restictest.TempDir(t)
-			defer cleanup()
-
+			tempdir := restictest.TempDir(t)
 			createFilesAt(t, tempdir, test.files)
 
 			subtestT := testing.TB(t)
@@ -456,8 +452,7 @@ func TestTestEnsureSnapshot(t *testing.T) {
 			ctx, cancel := context.WithCancel(context.Background())
 			defer cancel()
 
-			tempdir, cleanup := restictest.TempDir(t)
-			defer cleanup()
+			tempdir := restictest.TempDir(t)
 
 			targetDir := filepath.Join(tempdir, "target")
 			err := fs.Mkdir(targetDir, 0700)
diff --git a/internal/archiver/tree_test.go b/internal/archiver/tree_test.go
index 488f74b8c..7852a4c2e 100644
--- a/internal/archiver/tree_test.go
+++ b/internal/archiver/tree_test.go
@@ -439,9 +439,7 @@ func TestTree(t *testing.T) {
 				t.Skip("skip test on unix")
 			}
 
-			tempdir, cleanup := restictest.TempDir(t)
-			defer cleanup()
-
+			tempdir := restictest.TempDir(t)
 			TestCreateFiles(t, tempdir, test.src)
 
 			back := restictest.Chdir(t, tempdir)
diff --git a/internal/backend/layout/layout_test.go b/internal/backend/layout/layout_test.go
index 554f8a418..fc9c6e214 100644
--- a/internal/backend/layout/layout_test.go
+++ b/internal/backend/layout/layout_test.go
@@ -14,8 +14,7 @@ import (
 )
 
 func TestDefaultLayout(t *testing.T) {
-	tempdir, cleanup := rtest.TempDir(t)
-	defer cleanup()
+	tempdir := rtest.TempDir(t)
 
 	var tests = []struct {
 		path string
@@ -141,8 +140,7 @@ func TestDefaultLayout(t *testing.T) {
 }
 
 func TestRESTLayout(t *testing.T) {
-	path, cleanup := rtest.TempDir(t)
-	defer cleanup()
+	path := rtest.TempDir(t)
 
 	var tests = []struct {
 		restic.Handle
@@ -287,8 +285,7 @@ func TestRESTLayoutURLs(t *testing.T) {
 }
 
 func TestS3LegacyLayout(t *testing.T) {
-	path, cleanup := rtest.TempDir(t)
-	defer cleanup()
+	path := rtest.TempDir(t)
 
 	var tests = []struct {
 		restic.Handle
@@ -355,8 +352,7 @@ func TestS3LegacyLayout(t *testing.T) {
 }
 
 func TestDetectLayout(t *testing.T) {
-	path, cleanup := rtest.TempDir(t)
-	defer cleanup()
+	path := rtest.TempDir(t)
 
 	var tests = []struct {
 		filename string
@@ -393,8 +389,7 @@ func TestDetectLayout(t *testing.T) {
 }
 
 func TestParseLayout(t *testing.T) {
-	path, cleanup := rtest.TempDir(t)
-	defer cleanup()
+	path := rtest.TempDir(t)
 
 	var tests = []struct {
 		layoutName        string
@@ -433,8 +428,7 @@ func TestParseLayout(t *testing.T) {
 }
 
 func TestParseLayoutInvalid(t *testing.T) {
-	path, cleanup := rtest.TempDir(t)
-	defer cleanup()
+	path := rtest.TempDir(t)
 
 	var invalidNames = []string{
 		"foo", "bar", "local",
diff --git a/internal/backend/local/layout_test.go b/internal/backend/local/layout_test.go
index 9da702877..a4fccd2cb 100644
--- a/internal/backend/local/layout_test.go
+++ b/internal/backend/local/layout_test.go
@@ -10,8 +10,7 @@ import (
 )
 
 func TestLayout(t *testing.T) {
-	path, cleanup := rtest.TempDir(t)
-	defer cleanup()
+	path := rtest.TempDir(t)
 
 	var tests = []struct {
 		filename        string
diff --git a/internal/backend/local/local_internal_test.go b/internal/backend/local/local_internal_test.go
index 8de3d3c2f..1e80e72ed 100644
--- a/internal/backend/local/local_internal_test.go
+++ b/internal/backend/local/local_internal_test.go
@@ -24,8 +24,7 @@ func TestNoSpacePermanent(t *testing.T) {
 		return nil, fmt.Errorf("not creating tempfile, %w", syscall.ENOSPC)
 	}
 
-	dir, cleanup := rtest.TempDir(t)
-	defer cleanup()
+	dir := rtest.TempDir(t)
 
 	be, err := Open(context.Background(), Config{Path: dir, Connections: 2})
 	rtest.OK(t, err)
diff --git a/internal/backend/local/local_test.go b/internal/backend/local/local_test.go
index 906475d49..495f220a0 100644
--- a/internal/backend/local/local_test.go
+++ b/internal/backend/local/local_test.go
@@ -120,8 +120,7 @@ func removeAll(t testing.TB, dir string) {
 }
 
 func TestOpenNotExistingDirectory(t *testing.T) {
-	dir, cleanup := rtest.TempDir(t)
-	defer cleanup()
+	dir := rtest.TempDir(t)
 
 	// local.Open must not create any files dirs in the repo
 	openclose(t, filepath.Join(dir, "repo"))
diff --git a/internal/backend/rclone/backend_test.go b/internal/backend/rclone/backend_test.go
index 9708c6af2..12fed6274 100644
--- a/internal/backend/rclone/backend_test.go
+++ b/internal/backend/rclone/backend_test.go
@@ -13,7 +13,7 @@ import (
 )
 
 func newTestSuite(t testing.TB) *test.Suite {
-	dir, cleanup := rtest.TempDir(t)
+	dir := rtest.TempDir(t)
 
 	return &test.Suite{
 		// NewConfig returns a config for a new temporary backend that will be used in tests.
@@ -43,13 +43,6 @@ func newTestSuite(t testing.TB) *test.Suite {
 			cfg := config.(rclone.Config)
 			return rclone.Open(cfg, nil)
 		},
-
-		// CleanupFn removes data created during the tests.
-		Cleanup: func(config interface{}) error {
-			t.Logf("cleanup dir %v", dir)
-			cleanup()
-			return nil
-		},
 	}
 }
 
diff --git a/internal/backend/rclone/internal_test.go b/internal/backend/rclone/internal_test.go
index a606596bb..bfec2b98c 100644
--- a/internal/backend/rclone/internal_test.go
+++ b/internal/backend/rclone/internal_test.go
@@ -12,9 +12,7 @@ import (
 
 // restic should detect rclone exiting.
 func TestRcloneExit(t *testing.T) {
-	dir, cleanup := rtest.TempDir(t)
-	defer cleanup()
-
+	dir := rtest.TempDir(t)
 	cfg := NewConfig()
 	cfg.Remote = dir
 	be, err := Open(cfg, nil)
diff --git a/internal/backend/rest/rest_test.go b/internal/backend/rest/rest_test.go
index 45aeabb99..a473e4440 100644
--- a/internal/backend/rest/rest_test.go
+++ b/internal/backend/rest/rest_test.go
@@ -112,9 +112,7 @@ func TestBackendREST(t *testing.T) {
 	ctx, cancel := context.WithCancel(context.Background())
 	defer cancel()
 
-	dir, cleanup := rtest.TempDir(t)
-	defer cleanup()
-
+	dir := rtest.TempDir(t)
 	serverURL, cleanup := runRESTServer(ctx, t, dir)
 	defer cleanup()
 
@@ -144,9 +142,7 @@ func BenchmarkBackendREST(t *testing.B) {
 	ctx, cancel := context.WithCancel(context.Background())
 	defer cancel()
 
-	dir, cleanup := rtest.TempDir(t)
-	defer cleanup()
-
+	dir := rtest.TempDir(t)
 	serverURL, cleanup := runRESTServer(ctx, t, dir)
 	defer cleanup()
 
diff --git a/internal/backend/s3/s3_test.go b/internal/backend/s3/s3_test.go
index 65313f8d4..c024251a9 100644
--- a/internal/backend/s3/s3_test.go
+++ b/internal/backend/s3/s3_test.go
@@ -101,9 +101,8 @@ func newRandomCredentials(t testing.TB) (key, secret string) {
 type MinioTestConfig struct {
 	s3.Config
 
-	tempdir       string
-	removeTempdir func()
-	stopServer    func()
+	tempdir    string
+	stopServer func()
 }
 
 func createS3(t testing.TB, cfg MinioTestConfig, tr http.RoundTripper) (be restic.Backend, err error) {
@@ -132,7 +131,7 @@ func newMinioTestSuite(ctx context.Context, t testing.TB) *test.Suite {
 		NewConfig: func() (interface{}, error) {
 			cfg := MinioTestConfig{}
 
-			cfg.tempdir, cfg.removeTempdir = rtest.TempDir(t)
+			cfg.tempdir = rtest.TempDir(t)
 			key, secret := newRandomCredentials(t)
 			cfg.stopServer = runMinio(ctx, t, cfg.tempdir, key, secret)
 
@@ -179,9 +178,6 @@ func newMinioTestSuite(ctx context.Context, t testing.TB) *test.Suite {
 			if cfg.stopServer != nil {
 				cfg.stopServer()
 			}
-			if cfg.removeTempdir != nil {
-				cfg.removeTempdir()
-			}
 			return nil
 		},
 	}
diff --git a/internal/backend/sftp/layout_test.go b/internal/backend/sftp/layout_test.go
index 3b654b1bb..fc8d80928 100644
--- a/internal/backend/sftp/layout_test.go
+++ b/internal/backend/sftp/layout_test.go
@@ -16,8 +16,7 @@ func TestLayout(t *testing.T) {
 		t.Skip("sftp server binary not available")
 	}
 
-	path, cleanup := rtest.TempDir(t)
-	defer cleanup()
+	path := rtest.TempDir(t)
 
 	var tests = []struct {
 		filename        string
diff --git a/internal/backend/test/suite.go b/internal/backend/test/suite.go
index 342ac38e4..45c6d96bd 100644
--- a/internal/backend/test/suite.go
+++ b/internal/backend/test/suite.go
@@ -60,8 +60,10 @@ func (s *Suite) RunTests(t *testing.T) {
 		return
 	}
 
-	if err = s.Cleanup(s.Config); err != nil {
-		t.Fatal(err)
+	if s.Cleanup != nil {
+		if err = s.Cleanup(s.Config); err != nil {
+			t.Fatal(err)
+		}
 	}
 }
 
diff --git a/internal/cache/backend_test.go b/internal/cache/backend_test.go
index 9aca90e71..3ddab5952 100644
--- a/internal/cache/backend_test.go
+++ b/internal/cache/backend_test.go
@@ -57,10 +57,7 @@ func randomData(n int) (restic.Handle, []byte) {
 
 func TestBackend(t *testing.T) {
 	be := mem.New()
-
-	c, cleanup := TestNewCache(t)
-	defer cleanup()
-
+	c := TestNewCache(t)
 	wbe := c.Wrap(be)
 
 	h, data := randomData(5234142)
@@ -128,10 +125,7 @@ func (be loadErrorBackend) Load(ctx context.Context, h restic.Handle, length int
 
 func TestErrorBackend(t *testing.T) {
 	be := mem.New()
-
-	c, cleanup := TestNewCache(t)
-	defer cleanup()
-
+	c := TestNewCache(t)
 	h, data := randomData(5234142)
 
 	// save directly in backend
@@ -174,9 +168,7 @@ func TestErrorBackend(t *testing.T) {
 
 func TestBackendRemoveBroken(t *testing.T) {
 	be := mem.New()
-
-	c, cleanup := TestNewCache(t)
-	defer cleanup()
+	c := TestNewCache(t)
 
 	h, data := randomData(5234142)
 	// save directly in backend
diff --git a/internal/cache/file_test.go b/internal/cache/file_test.go
index 1200c4ab3..111a2430f 100644
--- a/internal/cache/file_test.go
+++ b/internal/cache/file_test.go
@@ -87,8 +87,7 @@ func TestFiles(t *testing.T) {
 	t.Logf("seed is %v", seed)
 	rand.Seed(seed)
 
-	c, cleanup := TestNewCache(t)
-	defer cleanup()
+	c := TestNewCache(t)
 
 	var tests = []restic.FileType{
 		restic.SnapshotFile,
@@ -140,8 +139,7 @@ func TestFileLoad(t *testing.T) {
 	t.Logf("seed is %v", seed)
 	rand.Seed(seed)
 
-	c, cleanup := TestNewCache(t)
-	defer cleanup()
+	c := TestNewCache(t)
 
 	// save about 5 MiB of data in the cache
 	data := test.Random(rand.Int(), 5234142)
@@ -223,10 +221,8 @@ func TestFileSaveConcurrent(t *testing.T) {
 
 	const nproc = 40
 
-	c, cleanup := TestNewCache(t)
-	defer cleanup()
-
 	var (
+		c    = TestNewCache(t)
 		data = test.Random(1, 10000)
 		g    errgroup.Group
 		id   restic.ID
diff --git a/internal/cache/testing.go b/internal/cache/testing.go
index b3156374d..d4ce8c2ff 100644
--- a/internal/cache/testing.go
+++ b/internal/cache/testing.go
@@ -9,12 +9,12 @@ import (
 
 // TestNewCache returns a cache in a temporary directory which is removed when
 // cleanup is called.
-func TestNewCache(t testing.TB) (*Cache, func()) {
-	dir, cleanup := test.TempDir(t)
+func TestNewCache(t testing.TB) *Cache {
+	dir := test.TempDir(t)
 	t.Logf("created new cache at %v", dir)
 	cache, err := New(restic.NewRandomID().String(), dir)
 	if err != nil {
 		t.Fatal(err)
 	}
-	return cache, cleanup
+	return cache
 }
diff --git a/internal/dump/common_test.go b/internal/dump/common_test.go
index 7892a4fa9..1af0265fb 100644
--- a/internal/dump/common_test.go
+++ b/internal/dump/common_test.go
@@ -13,17 +13,12 @@ import (
 )
 
 func prepareTempdirRepoSrc(t testing.TB, src archiver.TestDir) (tempdir string, repo restic.Repository, cleanup func()) {
-	tempdir, removeTempdir := rtest.TempDir(t)
+	tempdir = rtest.TempDir(t)
 	repo, removeRepository := repository.TestRepository(t)
 
 	archiver.TestCreateFiles(t, tempdir, src)
 
-	cleanup = func() {
-		removeRepository()
-		removeTempdir()
-	}
-
-	return tempdir, repo, cleanup
+	return tempdir, repo, removeRepository
 }
 
 type CheckDump func(t *testing.T, testDir string, testDump *bytes.Buffer) error
diff --git a/internal/fs/stat_test.go b/internal/fs/stat_test.go
index 414d97337..a5ec77c7a 100644
--- a/internal/fs/stat_test.go
+++ b/internal/fs/stat_test.go
@@ -9,9 +9,7 @@ import (
 )
 
 func TestExtendedStat(t *testing.T) {
-	tempdir, cleanup := restictest.TempDir(t)
-	defer cleanup()
-
+	tempdir := restictest.TempDir(t)
 	filename := filepath.Join(tempdir, "file")
 	err := os.WriteFile(filename, []byte("foobar"), 0640)
 	if err != nil {
diff --git a/internal/restic/rewind_reader_test.go b/internal/restic/rewind_reader_test.go
index fdcbf8507..8ec79ddcd 100644
--- a/internal/restic/rewind_reader_test.go
+++ b/internal/restic/rewind_reader_test.go
@@ -27,9 +27,7 @@ func TestByteReader(t *testing.T) {
 func TestFileReader(t *testing.T) {
 	buf := []byte("foobar")
 
-	d, cleanup := test.TempDir(t)
-	defer cleanup()
-
+	d := test.TempDir(t)
 	filename := filepath.Join(d, "file-reader-test")
 	err := os.WriteFile(filename, buf, 0600)
 	if err != nil {
diff --git a/internal/restorer/filerestorer_test.go b/internal/restorer/filerestorer_test.go
index 737673292..b39afa249 100644
--- a/internal/restorer/filerestorer_test.go
+++ b/internal/restorer/filerestorer_test.go
@@ -185,8 +185,7 @@ func verifyRestore(t *testing.T, r *fileRestorer, repo *TestRepo) {
 }
 
 func TestFileRestorerBasic(t *testing.T) {
-	tempdir, cleanup := rtest.TempDir(t)
-	defer cleanup()
+	tempdir := rtest.TempDir(t)
 
 	for _, sparse := range []bool{false, true} {
 		restoreAndVerify(t, tempdir, []TestFile{
@@ -217,8 +216,7 @@ func TestFileRestorerBasic(t *testing.T) {
 }
 
 func TestFileRestorerPackSkip(t *testing.T) {
-	tempdir, cleanup := rtest.TempDir(t)
-	defer cleanup()
+	tempdir := rtest.TempDir(t)
 
 	files := make(map[string]bool)
 	files["file2"] = true
@@ -250,8 +248,7 @@ func TestFileRestorerPackSkip(t *testing.T) {
 }
 
 func TestErrorRestoreFiles(t *testing.T) {
-	tempdir, cleanup := rtest.TempDir(t)
-	defer cleanup()
+	tempdir := rtest.TempDir(t)
 	content := []TestFile{
 		{
 			name: "file1",
@@ -282,8 +279,7 @@ func TestDownloadError(t *testing.T) {
 }
 
 func testPartialDownloadError(t *testing.T, part int) {
-	tempdir, cleanup := rtest.TempDir(t)
-	defer cleanup()
+	tempdir := rtest.TempDir(t)
 	content := []TestFile{
 		{
 			name: "file1",
diff --git a/internal/restorer/fileswriter_test.go b/internal/restorer/fileswriter_test.go
index fd5f20d56..7beb9a2dc 100644
--- a/internal/restorer/fileswriter_test.go
+++ b/internal/restorer/fileswriter_test.go
@@ -8,9 +8,7 @@ import (
 )
 
 func TestFilesWriterBasic(t *testing.T) {
-	dir, cleanup := rtest.TempDir(t)
-	defer cleanup()
-
+	dir := rtest.TempDir(t)
 	w := newFilesWriter(1)
 
 	f1 := dir + "/f1"
diff --git a/internal/restorer/preallocate_test.go b/internal/restorer/preallocate_test.go
index 158b8a74c..0cc2b3f5d 100644
--- a/internal/restorer/preallocate_test.go
+++ b/internal/restorer/preallocate_test.go
@@ -14,8 +14,7 @@ import (
 func TestPreallocate(t *testing.T) {
 	for _, i := range []int64{0, 1, 4096, 1024 * 1024} {
 		t.Run(strconv.FormatInt(i, 10), func(t *testing.T) {
-			dirpath, cleanup := test.TempDir(t)
-			defer cleanup()
+			dirpath := test.TempDir(t)
 
 			flags := os.O_CREATE | os.O_TRUNC | os.O_WRONLY
 			wr, err := os.OpenFile(path.Join(dirpath, "test"), flags, 0600)
diff --git a/internal/restorer/restorer_test.go b/internal/restorer/restorer_test.go
index de40c3e8c..08e32d30b 100644
--- a/internal/restorer/restorer_test.go
+++ b/internal/restorer/restorer_test.go
@@ -328,9 +328,7 @@ func TestRestorer(t *testing.T) {
 
 			res := NewRestorer(context.TODO(), repo, sn, false)
 
-			tempdir, cleanup := rtest.TempDir(t)
-			defer cleanup()
-
+			tempdir := rtest.TempDir(t)
 			// make sure we're creating a new subdir of the tempdir
 			tempdir = filepath.Join(tempdir, "target")
 
@@ -448,9 +446,7 @@ func TestRestorerRelative(t *testing.T) {
 
 			res := NewRestorer(context.TODO(), repo, sn, false)
 
-			tempdir, cleanup := rtest.TempDir(t)
-			defer cleanup()
-
+			tempdir := rtest.TempDir(t)
 			cleanup = rtest.Chdir(t, tempdir)
 			defer cleanup()
 
@@ -682,9 +678,7 @@ func TestRestorerTraverseTree(t *testing.T) {
 
 			res.SelectFilter = test.Select
 
-			tempdir, cleanup := rtest.TempDir(t)
-			defer cleanup()
-
+			tempdir := rtest.TempDir(t)
 			ctx, cancel := context.WithCancel(context.Background())
 			defer cancel()
 
@@ -776,9 +770,7 @@ func TestRestorerConsistentTimestampsAndPermissions(t *testing.T) {
 		return selectedForRestore, childMayBeSelected
 	}
 
-	tempdir, cleanup := rtest.TempDir(t)
-	defer cleanup()
-
+	tempdir := rtest.TempDir(t)
 	ctx, cancel := context.WithCancel(context.Background())
 	defer cancel()
 
@@ -818,9 +810,7 @@ func TestVerifyCancel(t *testing.T) {
 
 	res := NewRestorer(context.TODO(), repo, sn, false)
 
-	tempdir, cleanup := rtest.TempDir(t)
-	defer cleanup()
-
+	tempdir := rtest.TempDir(t)
 	ctx, cancel := context.WithCancel(context.Background())
 	defer cancel()
 
@@ -863,9 +853,7 @@ func TestRestorerSparseFiles(t *testing.T) {
 
 	res := NewRestorer(context.TODO(), repo, sn, true)
 
-	tempdir, cleanup := rtest.TempDir(t)
-	defer cleanup()
-
+	tempdir := rtest.TempDir(t)
 	ctx, cancel := context.WithCancel(context.Background())
 	defer cancel()
 
diff --git a/internal/restorer/restorer_unix_test.go b/internal/restorer/restorer_unix_test.go
index fc9ffe9a6..8aedd772b 100644
--- a/internal/restorer/restorer_unix_test.go
+++ b/internal/restorer/restorer_unix_test.go
@@ -36,9 +36,7 @@ func TestRestorerRestoreEmptyHardlinkedFileds(t *testing.T) {
 		return true, true
 	}
 
-	tempdir, cleanup := rtest.TempDir(t)
-	defer cleanup()
-
+	tempdir := rtest.TempDir(t)
 	ctx, cancel := context.WithCancel(context.Background())
 	defer cancel()
 
diff --git a/internal/test/helpers.go b/internal/test/helpers.go
index d883b022c..93178ae10 100644
--- a/internal/test/helpers.go
+++ b/internal/test/helpers.go
@@ -191,22 +191,23 @@ func RemoveAll(t testing.TB, path string) {
 	OK(t, err)
 }
 
-// TempDir returns a temporary directory that is removed when cleanup is
-// called, except if TestCleanupTempDirs is set to false.
-func TempDir(t testing.TB) (path string, cleanup func()) {
+// TempDir returns a temporary directory that is removed by t.Cleanup,
+// except if TestCleanupTempDirs is set to false.
+func TempDir(t testing.TB) string {
 	tempdir, err := os.MkdirTemp(TestTempDir, "restic-test-")
 	if err != nil {
 		t.Fatal(err)
 	}
 
-	return tempdir, func() {
+	t.Cleanup(func() {
 		if !TestCleanupTempDirs {
 			t.Logf("leaving temporary directory %v used for test", tempdir)
 			return
 		}
 
 		RemoveAll(t, tempdir)
-	}
+	})
+	return tempdir
 }
 
 // Chdir changes the current directory to dest.