diff --git a/controllers/bucket_controller_fetch_test.go b/controllers/bucket_controller_fetch_test.go index acaa7e746..0dfaa005a 100644 --- a/controllers/bucket_controller_fetch_test.go +++ b/controllers/bucket_controller_fetch_test.go @@ -107,11 +107,7 @@ func Test_fetchEtagIndex(t *testing.T) { } t.Run("fetches etag index", func(t *testing.T) { - tmp, err := os.MkdirTemp("", "test-bucket") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmp) + tmp := t.TempDir() client := mockBucketClient{bucketName: bucketName} client.addObject("foo.yaml", mockBucketObject{data: "foo.yaml", etag: "etag1"}) @@ -119,7 +115,7 @@ func Test_fetchEtagIndex(t *testing.T) { client.addObject("baz.yaml", mockBucketObject{data: "baz.yaml", etag: "etag3"}) index := newEtagIndex() - err = fetchEtagIndex(context.TODO(), client, bucket.DeepCopy(), index, tmp) + err := fetchEtagIndex(context.TODO(), client, bucket.DeepCopy(), index, tmp) if err != nil { t.Fatal(err) } @@ -128,25 +124,17 @@ func Test_fetchEtagIndex(t *testing.T) { }) t.Run("an error while bucket does not exist", func(t *testing.T) { - tmp, err := os.MkdirTemp("", "test-bucket") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmp) + tmp := t.TempDir() client := mockBucketClient{bucketName: "other-bucket-name"} index := newEtagIndex() - err = fetchEtagIndex(context.TODO(), client, bucket.DeepCopy(), index, tmp) + err := fetchEtagIndex(context.TODO(), client, bucket.DeepCopy(), index, tmp) assert.ErrorContains(t, err, "not found") }) t.Run("filters with .sourceignore rules", func(t *testing.T) { - tmp, err := os.MkdirTemp("", "test-bucket") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmp) + tmp := t.TempDir() client := mockBucketClient{bucketName: bucketName} client.addObject(".sourceignore", mockBucketObject{etag: "sourceignore1", data: `*.txt`}) @@ -154,7 +142,7 @@ func Test_fetchEtagIndex(t *testing.T) { client.addObject("foo.txt", mockBucketObject{etag: "etag2", data: "foo.txt"}) index := newEtagIndex() - err = fetchEtagIndex(context.TODO(), client, bucket.DeepCopy(), index, tmp) + err := fetchEtagIndex(context.TODO(), client, bucket.DeepCopy(), index, tmp) if err != nil { t.Fatal(err) } @@ -170,11 +158,7 @@ func Test_fetchEtagIndex(t *testing.T) { }) t.Run("filters with ignore rules from object", func(t *testing.T) { - tmp, err := os.MkdirTemp("", "test-bucket") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmp) + tmp := t.TempDir() client := mockBucketClient{bucketName: bucketName} client.addObject(".sourceignore", mockBucketObject{etag: "sourceignore1", data: `*.txt`}) @@ -185,7 +169,7 @@ func Test_fetchEtagIndex(t *testing.T) { bucket.Spec.Ignore = &ignore index := newEtagIndex() - err = fetchEtagIndex(context.TODO(), client, bucket.DeepCopy(), index, tmp) + err := fetchEtagIndex(context.TODO(), client, bucket.DeepCopy(), index, tmp) if err != nil { t.Fatal(err) } @@ -212,11 +196,7 @@ func Test_fetchFiles(t *testing.T) { } t.Run("fetches files", func(t *testing.T) { - tmp, err := os.MkdirTemp("", "test-bucket") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmp) + tmp := t.TempDir() client := mockBucketClient{bucketName: bucketName} client.addObject("foo.yaml", mockBucketObject{data: "foo.yaml", etag: "etag1"}) @@ -225,7 +205,7 @@ func Test_fetchFiles(t *testing.T) { index := client.objectsToEtagIndex() - err = fetchIndexFiles(context.TODO(), client, bucket.DeepCopy(), index, tmp) + err := fetchIndexFiles(context.TODO(), client, bucket.DeepCopy(), index, tmp) if err != nil { t.Fatal(err) } @@ -240,34 +220,26 @@ func Test_fetchFiles(t *testing.T) { }) t.Run("an error while fetching returns an error for the whole procedure", func(t *testing.T) { - tmp, err := os.MkdirTemp("", "test-bucket") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmp) + tmp := t.TempDir() client := mockBucketClient{bucketName: bucketName, objects: map[string]mockBucketObject{}} client.objects["error"] = mockBucketObject{} - err = fetchIndexFiles(context.TODO(), client, bucket.DeepCopy(), client.objectsToEtagIndex(), tmp) + err := fetchIndexFiles(context.TODO(), client, bucket.DeepCopy(), client.objectsToEtagIndex(), tmp) if err == nil { t.Fatal("expected error but got nil") } }) t.Run("a changed etag updates the index", func(t *testing.T) { - tmp, err := os.MkdirTemp("", "test-bucket") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmp) + tmp := t.TempDir() client := mockBucketClient{bucketName: bucketName} client.addObject("foo.yaml", mockBucketObject{data: "foo.yaml", etag: "etag2"}) index := newEtagIndex() index.Add("foo.yaml", "etag1") - err = fetchIndexFiles(context.TODO(), client, bucket.DeepCopy(), index, tmp) + err := fetchIndexFiles(context.TODO(), client, bucket.DeepCopy(), index, tmp) if err != nil { t.Fatal(err) } @@ -276,11 +248,7 @@ func Test_fetchFiles(t *testing.T) { }) t.Run("a disappeared index entry is removed from the index", func(t *testing.T) { - tmp, err := os.MkdirTemp("", "test-bucket") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmp) + tmp := t.TempDir() client := mockBucketClient{bucketName: bucketName} client.addObject("foo.yaml", mockBucketObject{data: "foo.yaml", etag: "etag1"}) @@ -290,7 +258,7 @@ func Test_fetchFiles(t *testing.T) { // Does not exist on server index.Add("bar.yaml", "etag2") - err = fetchIndexFiles(context.TODO(), client, bucket.DeepCopy(), index, tmp) + err := fetchIndexFiles(context.TODO(), client, bucket.DeepCopy(), index, tmp) if err != nil { t.Fatal(err) } @@ -301,11 +269,7 @@ func Test_fetchFiles(t *testing.T) { t.Run("can fetch more than maxConcurrentFetches", func(t *testing.T) { // this will fail if, for example, the semaphore is not used correctly and blocks - tmp, err := os.MkdirTemp("", "test-bucket") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmp) + tmp := t.TempDir() client := mockBucketClient{bucketName: bucketName} for i := 0; i < 2*maxConcurrentBucketFetches; i++ { @@ -314,7 +278,7 @@ func Test_fetchFiles(t *testing.T) { } index := client.objectsToEtagIndex() - err = fetchIndexFiles(context.TODO(), client, bucket.DeepCopy(), index, tmp) + err := fetchIndexFiles(context.TODO(), client, bucket.DeepCopy(), index, tmp) if err != nil { t.Fatal(err) } diff --git a/controllers/bucket_controller_test.go b/controllers/bucket_controller_test.go index 02f98c144..0337df48e 100644 --- a/controllers/bucket_controller_test.go +++ b/controllers/bucket_controller_test.go @@ -539,9 +539,7 @@ func TestBucketReconciler_reconcileSource_generic(t *testing.T) { Client: builder.Build(), Storage: testStorage, } - tmpDir, err := os.MkdirTemp("", "reconcile-bucket-source-") - g.Expect(err).ToNot(HaveOccurred()) - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() obj := &sourcev1.Bucket{ TypeMeta: metav1.TypeMeta{ @@ -834,9 +832,7 @@ func TestBucketReconciler_reconcileSource_gcs(t *testing.T) { Client: builder.Build(), Storage: testStorage, } - tmpDir, err := os.MkdirTemp("", "reconcile-bucket-source-") - g.Expect(err).ToNot(HaveOccurred()) - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() // Test bucket object. obj := &sourcev1.Bucket{ @@ -992,9 +988,7 @@ func TestBucketReconciler_reconcileArtifact(t *testing.T) { Storage: testStorage, } - tmpDir, err := os.MkdirTemp("", "reconcile-bucket-artifact-") - g.Expect(err).ToNot(HaveOccurred()) - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() obj := &sourcev1.Bucket{ TypeMeta: metav1.TypeMeta{ diff --git a/controllers/gitrepository_controller_test.go b/controllers/gitrepository_controller_test.go index fb020d7ca..1ab7d4aa3 100644 --- a/controllers/gitrepository_controller_test.go +++ b/controllers/gitrepository_controller_test.go @@ -509,9 +509,7 @@ func TestGitRepositoryReconciler_reconcileSource_authStrategy(t *testing.T) { t.Skipf("Skipped for Git implementation %q", i) } - tmpDir, err := os.MkdirTemp("", "auth-strategy-") - g.Expect(err).To(BeNil()) - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() obj := obj.DeepCopy() obj.Spec.GitImplementation = i @@ -671,9 +669,7 @@ func TestGitRepositoryReconciler_reconcileSource_checkoutStrategy(t *testing.T) t.Skipf("Skipped for Git implementation %q", i) } - tmpDir, err := os.MkdirTemp("", "checkout-strategy-") - g.Expect(err).NotTo(HaveOccurred()) - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() obj := obj.DeepCopy() obj.Spec.GitImplementation = i @@ -1072,9 +1068,7 @@ func TestGitRepositoryReconciler_reconcileInclude(t *testing.T) { tt.beforeFunc(obj) } - tmpDir, err := os.MkdirTemp("", "include-") - g.Expect(err).NotTo(HaveOccurred()) - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() var commit git.Commit var includes artifactSet diff --git a/controllers/helmchart_controller_test.go b/controllers/helmchart_controller_test.go index 849be4d29..5fe93e86c 100644 --- a/controllers/helmchart_controller_test.go +++ b/controllers/helmchart_controller_test.go @@ -307,9 +307,7 @@ func TestHelmChartReconciler_reconcileStorage(t *testing.T) { func TestHelmChartReconciler_reconcileSource(t *testing.T) { g := NewWithT(t) - tmpDir, err := os.MkdirTemp("", "reconcile-tarball-") - g.Expect(err).ToNot(HaveOccurred()) - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() storage, err := NewStorage(tmpDir, "example.com", retentionTTL, retentionRecords) g.Expect(err).ToNot(HaveOccurred()) @@ -781,9 +779,7 @@ func TestHelmChartReconciler_buildFromHelmRepository(t *testing.T) { func TestHelmChartReconciler_buildFromTarballArtifact(t *testing.T) { g := NewWithT(t) - tmpDir, err := os.MkdirTemp("", "reconcile-tarball-") - g.Expect(err).ToNot(HaveOccurred()) - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() storage, err := NewStorage(tmpDir, "example.com", retentionTTL, retentionRecords) g.Expect(err).ToNot(HaveOccurred()) diff --git a/controllers/helmrepository_controller_test.go b/controllers/helmrepository_controller_test.go index 4d713d9ee..488ff1c4b 100644 --- a/controllers/helmrepository_controller_test.go +++ b/controllers/helmrepository_controller_test.go @@ -728,9 +728,7 @@ func TestHelmRepositoryReconciler_reconcileArtifact(t *testing.T) { }, } - tmpDir, err := os.MkdirTemp("", "test-reconcile-artifact-") - g.Expect(err).ToNot(HaveOccurred()) - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() // Create an empty cache file. cachePath := filepath.Join(tmpDir, "index.yaml") diff --git a/controllers/storage_test.go b/controllers/storage_test.go index e3550bd59..8e0e599a6 100644 --- a/controllers/storage_test.go +++ b/controllers/storage_test.go @@ -35,20 +35,8 @@ import ( sourcev1 "github.com/fluxcd/source-controller/api/v1beta2" ) -func createStoragePath() (string, error) { - return os.MkdirTemp("", "") -} - -func cleanupStoragePath(dir string) func() { - return func() { os.RemoveAll(dir) } -} - func TestStorageConstructor(t *testing.T) { - dir, err := createStoragePath() - if err != nil { - t.Fatal(err) - } - t.Cleanup(cleanupStoragePath(dir)) + dir := t.TempDir() if _, err := NewStorage("/nonexistent", "hostname", time.Minute, 2); err == nil { t.Fatal("nonexistent path was allowable in storage constructor") @@ -113,11 +101,7 @@ func walkTar(tarFile string, match string, dir bool) (int64, bool, error) { } func TestStorage_Archive(t *testing.T) { - dir, err := createStoragePath() - if err != nil { - t.Fatal(err) - } - t.Cleanup(cleanupStoragePath(dir)) + dir := t.TempDir() storage, err := NewStorage(dir, "hostname", time.Minute, 2) if err != nil { @@ -125,15 +109,7 @@ func TestStorage_Archive(t *testing.T) { } createFiles := func(files map[string][]byte) (dir string, err error) { - defer func() { - if err != nil && dir != "" { - os.RemoveAll(dir) - } - }() - dir, err = os.MkdirTemp("", "archive-test-files-") - if err != nil { - return - } + dir = t.TempDir() for name, b := range files { absPath := filepath.Join(dir, name) if err = os.MkdirAll(filepath.Dir(absPath), 0o750); err != nil { @@ -285,11 +261,7 @@ func TestStorage_Archive(t *testing.T) { func TestStorageRemoveAllButCurrent(t *testing.T) { t.Run("bad directory in archive", func(t *testing.T) { - dir, err := os.MkdirTemp("", "") - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { os.RemoveAll(dir) }) + dir := t.TempDir() s, err := NewStorage(dir, "hostname", time.Minute, 2) if err != nil { @@ -303,9 +275,7 @@ func TestStorageRemoveAllButCurrent(t *testing.T) { t.Run("collect names of deleted items", func(t *testing.T) { g := NewWithT(t) - dir, err := os.MkdirTemp("", "") - g.Expect(err).ToNot(HaveOccurred()) - t.Cleanup(func() { os.RemoveAll(dir) }) + dir := t.TempDir() s, err := NewStorage(dir, "hostname", time.Minute, 2) g.Expect(err).ToNot(HaveOccurred(), "failed to create new storage") @@ -366,9 +336,7 @@ func TestStorageRemoveAll(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { g := NewWithT(t) - dir, err := os.MkdirTemp("", "") - g.Expect(err).ToNot(HaveOccurred()) - t.Cleanup(func() { os.RemoveAll(dir) }) + dir := t.TempDir() s, err := NewStorage(dir, "hostname", time.Minute, 2) g.Expect(err).ToNot(HaveOccurred(), "failed to create new storage") @@ -394,11 +362,7 @@ func TestStorageCopyFromPath(t *testing.T) { Content []byte } - dir, err := createStoragePath() - if err != nil { - t.Fatal(err) - } - t.Cleanup(cleanupStoragePath(dir)) + dir := t.TempDir() storage, err := NewStorage(dir, "hostname", time.Minute, 2) if err != nil { @@ -406,11 +370,7 @@ func TestStorageCopyFromPath(t *testing.T) { } createFile := func(file *File) (absPath string, err error) { - dir, err = os.MkdirTemp("", "test-files-") - if err != nil { - return - } - t.Cleanup(cleanupStoragePath(dir)) + dir = t.TempDir() absPath = filepath.Join(dir, file.Name) if err = os.MkdirAll(filepath.Dir(absPath), 0o750); err != nil { return @@ -474,7 +434,6 @@ func TestStorageCopyFromPath(t *testing.T) { t.Error(err) return } - defer os.RemoveAll(absPath) artifact := sourcev1.Artifact{ Path: filepath.Join(randStringRunes(10), randStringRunes(10), randStringRunes(10)), } @@ -581,9 +540,7 @@ func TestStorage_getGarbageFiles(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { g := NewWithT(t) - dir, err := os.MkdirTemp("", "") - g.Expect(err).ToNot(HaveOccurred()) - t.Cleanup(func() { os.RemoveAll(dir) }) + dir := t.TempDir() s, err := NewStorage(dir, "hostname", tt.ttl, tt.maxItemsToBeRetained) g.Expect(err).ToNot(HaveOccurred(), "failed to create new storage") @@ -657,9 +614,7 @@ func TestStorage_GarbageCollect(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { g := NewWithT(t) - dir, err := os.MkdirTemp("", "") - g.Expect(err).ToNot(HaveOccurred()) - t.Cleanup(func() { os.RemoveAll(dir) }) + dir := t.TempDir() s, err := NewStorage(dir, "hostname", time.Second*2, 2) g.Expect(err).ToNot(HaveOccurred(), "failed to create new storage") diff --git a/internal/fs/fs_test.go b/internal/fs/fs_test.go index fa51eae4a..9a1c5ef99 100644 --- a/internal/fs/fs_test.go +++ b/internal/fs/fs_test.go @@ -19,13 +19,9 @@ var ( ) func TestRenameWithFallback(t *testing.T) { - dir, err := os.MkdirTemp("", "dep") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dir) + dir := t.TempDir() - if err = RenameWithFallback(filepath.Join(dir, "does_not_exists"), filepath.Join(dir, "dst")); err == nil { + if err := RenameWithFallback(filepath.Join(dir, "does_not_exists"), filepath.Join(dir, "dst")); err == nil { t.Fatal("expected an error for non existing file, but got nil") } @@ -37,31 +33,27 @@ func TestRenameWithFallback(t *testing.T) { srcf.Close() } - if err = RenameWithFallback(srcpath, filepath.Join(dir, "dst")); err != nil { + if err := RenameWithFallback(srcpath, filepath.Join(dir, "dst")); err != nil { t.Fatal(err) } srcpath = filepath.Join(dir, "a") - if err = os.MkdirAll(srcpath, 0o770); err != nil { + if err := os.MkdirAll(srcpath, 0o770); err != nil { t.Fatal(err) } dstpath := filepath.Join(dir, "b") - if err = os.MkdirAll(dstpath, 0o770); err != nil { + if err := os.MkdirAll(dstpath, 0o770); err != nil { t.Fatal(err) } - if err = RenameWithFallback(srcpath, dstpath); err == nil { + if err := RenameWithFallback(srcpath, dstpath); err == nil { t.Fatal("expected an error if dst is an existing directory, but got nil") } } func TestCopyDir(t *testing.T) { - dir, err := os.MkdirTemp("", "dep") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dir) + dir := t.TempDir() srcdir := filepath.Join(dir, "src") if err := os.MkdirAll(srcdir, 0o750); err != nil { @@ -81,7 +73,7 @@ func TestCopyDir(t *testing.T) { for i, file := range files { fn := filepath.Join(srcdir, file.path) dn := filepath.Dir(fn) - if err = os.MkdirAll(dn, 0o750); err != nil { + if err := os.MkdirAll(dn, 0o750); err != nil { t.Fatal(err) } @@ -149,20 +141,15 @@ func TestCopyDirFail_SrcInaccessible(t *testing.T) { var srcdir, dstdir string - cleanup := setupInaccessibleDir(t, func(dir string) error { + setupInaccessibleDir(t, func(dir string) error { srcdir = filepath.Join(dir, "src") return os.MkdirAll(srcdir, 0o750) }) - defer cleanup() - dir, err := os.MkdirTemp("", "dep") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dir) + dir := t.TempDir() dstdir = filepath.Join(dir, "dst") - if err = CopyDir(srcdir, dstdir); err == nil { + if err := CopyDir(srcdir, dstdir); err == nil { t.Fatalf("expected error for CopyDir(%s, %s), got none", srcdir, dstdir) } } @@ -177,22 +164,17 @@ func TestCopyDirFail_DstInaccessible(t *testing.T) { var srcdir, dstdir string - dir, err := os.MkdirTemp("", "dep") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dir) + dir := t.TempDir() srcdir = filepath.Join(dir, "src") - if err = os.MkdirAll(srcdir, 0o750); err != nil { + if err := os.MkdirAll(srcdir, 0o750); err != nil { t.Fatal(err) } - cleanup := setupInaccessibleDir(t, func(dir string) error { + setupInaccessibleDir(t, func(dir string) error { dstdir = filepath.Join(dir, "dst") return nil }) - defer cleanup() if err := CopyDir(srcdir, dstdir); err == nil { t.Fatalf("expected error for CopyDir(%s, %s), got none", srcdir, dstdir) @@ -202,20 +184,17 @@ func TestCopyDirFail_DstInaccessible(t *testing.T) { func TestCopyDirFail_SrcIsNotDir(t *testing.T) { var srcdir, dstdir string - dir, err := os.MkdirTemp("", "dep") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dir) + dir := t.TempDir() srcdir = filepath.Join(dir, "src") - if _, err = os.Create(srcdir); err != nil { + if _, err := os.Create(srcdir); err != nil { t.Fatal(err) } dstdir = filepath.Join(dir, "dst") - if err = CopyDir(srcdir, dstdir); err == nil { + err := CopyDir(srcdir, dstdir) + if err == nil { t.Fatalf("expected error for CopyDir(%s, %s), got none", srcdir, dstdir) } @@ -228,23 +207,20 @@ func TestCopyDirFail_SrcIsNotDir(t *testing.T) { func TestCopyDirFail_DstExists(t *testing.T) { var srcdir, dstdir string - dir, err := os.MkdirTemp("", "dep") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dir) + dir := t.TempDir() srcdir = filepath.Join(dir, "src") - if err = os.MkdirAll(srcdir, 0o750); err != nil { + if err := os.MkdirAll(srcdir, 0o750); err != nil { t.Fatal(err) } dstdir = filepath.Join(dir, "dst") - if err = os.MkdirAll(dstdir, 0o750); err != nil { + if err := os.MkdirAll(dstdir, 0o750); err != nil { t.Fatal(err) } - if err = CopyDir(srcdir, dstdir); err == nil { + err := CopyDir(srcdir, dstdir) + if err == nil { t.Fatalf("expected error for CopyDir(%s, %s), got none", srcdir, dstdir) } @@ -266,14 +242,10 @@ func TestCopyDirFailOpen(t *testing.T) { var srcdir, dstdir string - dir, err := os.MkdirTemp("", "dep") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dir) + dir := t.TempDir() srcdir = filepath.Join(dir, "src") - if err = os.MkdirAll(srcdir, 0o750); err != nil { + if err := os.MkdirAll(srcdir, 0o750); err != nil { t.Fatal(err) } @@ -297,11 +269,7 @@ func TestCopyDirFailOpen(t *testing.T) { } func TestCopyFile(t *testing.T) { - dir, err := os.MkdirTemp("", "dep") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dir) + dir := t.TempDir() srcf, err := os.Create(filepath.Join(dir, "srcfile")) if err != nil { @@ -344,10 +312,7 @@ func TestCopyFile(t *testing.T) { } func TestCopyFileSymlink(t *testing.T) { - dir, err := os.MkdirTemp("", "dep") - if err != nil { - t.Fatal(err) - } + dir := t.TempDir() defer cleanUpDir(dir) testcases := map[string]string{ @@ -406,11 +371,7 @@ func TestCopyFileLongFilePath(t *testing.T) { t.Skip("skipping on non-windows") } - dir, err := os.MkdirTemp("", "dep") - if err != nil { - t.Fatal(err) - } - defer cleanUpDir(dir) + dir := t.TempDir() // Create a directory with a long-enough path name to cause the bug in #774. dirName := "" @@ -423,7 +384,7 @@ func TestCopyFileLongFilePath(t *testing.T) { t.Fatalf("%+v", fmt.Errorf("unable to create temp directory: %s", fullPath)) } - err = os.WriteFile(fullPath+"src", []byte(nil), 0o640) + err := os.WriteFile(fullPath+"src", []byte(nil), 0o640) if err != nil { t.Fatalf("%+v", err) } @@ -444,11 +405,7 @@ func TestCopyFileFail(t *testing.T) { t.Skip("skipping on windows") } - dir, err := os.MkdirTemp("", "dep") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dir) + dir := t.TempDir() srcf, err := os.Create(filepath.Join(dir, "srcfile")) if err != nil { @@ -458,11 +415,10 @@ func TestCopyFileFail(t *testing.T) { var dstdir string - cleanup := setupInaccessibleDir(t, func(dir string) error { + setupInaccessibleDir(t, func(dir string) error { dstdir = filepath.Join(dir, "dir") return os.Mkdir(dstdir, 0o770) }) - defer cleanup() fn := filepath.Join(dstdir, "file") if err := copyFile(srcf.Name(), fn); err == nil { @@ -479,47 +435,31 @@ func TestCopyFileFail(t *testing.T) { // // If setupInaccessibleDir fails in its preparation, or op fails, t.Fatal // will be invoked. -// -// This function returns a cleanup function that removes all the temporary -// files this function creates. It is the caller's responsibility to call -// this function before the test is done running, whether there's an error or not. -func setupInaccessibleDir(t *testing.T, op func(dir string) error) func() { +func setupInaccessibleDir(t *testing.T, op func(dir string) error) { dir, err := os.MkdirTemp("", "dep") if err != nil { t.Fatal(err) - return nil // keep compiler happy } subdir := filepath.Join(dir, "dir") - cleanup := func() { + t.Cleanup(func() { if err := os.Chmod(subdir, 0o770); err != nil { t.Error(err) } - if err := os.RemoveAll(dir); err != nil { - t.Error(err) - } - } + }) if err := os.Mkdir(subdir, 0o770); err != nil { - cleanup() t.Fatal(err) - return nil } if err := op(subdir); err != nil { - cleanup() t.Fatal(err) - return nil } if err := os.Chmod(subdir, 0o660); err != nil { - cleanup() t.Fatal(err) - return nil } - - return cleanup } func TestIsDir(t *testing.T) { @@ -530,11 +470,10 @@ func TestIsDir(t *testing.T) { var dn string - cleanup := setupInaccessibleDir(t, func(dir string) error { + setupInaccessibleDir(t, func(dir string) error { dn = filepath.Join(dir, "dir") return os.Mkdir(dn, 0o770) }) - defer cleanup() tests := map[string]struct { exists bool @@ -568,14 +507,10 @@ func TestIsDir(t *testing.T) { } func TestIsSymlink(t *testing.T) { - dir, err := os.MkdirTemp("", "dep") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dir) + dir := t.TempDir() dirPath := filepath.Join(dir, "directory") - if err = os.MkdirAll(dirPath, 0o770); err != nil { + if err := os.MkdirAll(dirPath, 0o770); err != nil { t.Fatal(err) } @@ -601,7 +536,7 @@ func TestIsSymlink(t *testing.T) { inaccessibleSymlink string ) - cleanup := setupInaccessibleDir(t, func(dir string) error { + setupInaccessibleDir(t, func(dir string) error { inaccessibleFile = filepath.Join(dir, "file") if fh, err := os.Create(inaccessibleFile); err != nil { return err @@ -612,7 +547,6 @@ func TestIsSymlink(t *testing.T) { inaccessibleSymlink = filepath.Join(dir, "symlink") return os.Symlink(inaccessibleFile, inaccessibleSymlink) }) - defer cleanup() tests := map[string]struct{ expected, err bool }{ dirPath: {false, false}, diff --git a/internal/helm/chart/builder_local_test.go b/internal/helm/chart/builder_local_test.go index 57f828f4c..655b1709b 100644 --- a/internal/helm/chart/builder_local_test.go +++ b/internal/helm/chart/builder_local_test.go @@ -177,9 +177,7 @@ fullnameOverride: "full-foo-name-override"`), t.Run(tt.name, func(t *testing.T) { g := NewWithT(t) - workDir, err := os.MkdirTemp("", "local-builder-") - g.Expect(err).ToNot(HaveOccurred()) - defer os.RemoveAll(workDir) + workDir := t.TempDir() // Only if the reference is a LocalReference, set the WorkDir. localRef, ok := tt.reference.(LocalReference) @@ -213,7 +211,6 @@ fullnameOverride: "full-foo-name-override"`), // Target path with name similar to the workDir. targetPath := workDir + ".tgz" - defer os.RemoveAll(targetPath) dm := NewDependencyManager( WithRepositories(tt.repositories), @@ -247,18 +244,14 @@ fullnameOverride: "full-foo-name-override"`), func TestLocalBuilder_Build_CachedChart(t *testing.T) { g := NewWithT(t) - workDir, err := os.MkdirTemp("", "local-builder-") - g.Expect(err).ToNot(HaveOccurred()) - defer os.RemoveAll(workDir) + workDir := t.TempDir() testChartPath := "./../testdata/charts/helmchart" dm := NewDependencyManager() b := NewLocalBuilder(dm) - tmpDir, err := os.MkdirTemp("", "local-chart-") - g.Expect(err).ToNot(HaveOccurred()) - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() // Copy the source chart into the workdir. g.Expect(copy.Copy(testChartPath, filepath.Join(workDir, "testdata", "charts", filepath.Base("helmchart")))).ToNot(HaveOccurred()) @@ -275,7 +268,6 @@ func TestLocalBuilder_Build_CachedChart(t *testing.T) { buildOpts.CachedChart = cb.Path targetPath2 := filepath.Join(tmpDir, "chart2.tgz") - defer os.RemoveAll(targetPath2) cb, err = b.Build(context.TODO(), reference, targetPath2, buildOpts) g.Expect(err).ToNot(HaveOccurred()) g.Expect(cb.Path).To(Equal(targetPath)) @@ -331,9 +323,7 @@ func Test_mergeFileValues(t *testing.T) { t.Run(tt.name, func(t *testing.T) { g := NewWithT(t) - baseDir, err := os.MkdirTemp("", "merge-file-values-*") - g.Expect(err).ToNot(HaveOccurred()) - defer os.RemoveAll(baseDir) + baseDir := t.TempDir() for _, f := range tt.files { g.Expect(os.WriteFile(filepath.Join(baseDir, f.Name), f.Data, 0o640)).To(Succeed()) diff --git a/internal/helm/chart/builder_remote_test.go b/internal/helm/chart/builder_remote_test.go index 604aa6006..f1b669bff 100644 --- a/internal/helm/chart/builder_remote_test.go +++ b/internal/helm/chart/builder_remote_test.go @@ -159,9 +159,7 @@ entries: t.Run(tt.name, func(t *testing.T) { g := NewWithT(t) - tmpDir, err := os.MkdirTemp("", "remote-chart-builder-") - g.Expect(err).ToNot(HaveOccurred()) - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() targetPath := filepath.Join(tmpDir, "chart.tgz") if tt.repository != nil { @@ -237,13 +235,10 @@ entries: b := NewRemoteBuilder(repository) - tmpDir, err := os.MkdirTemp("", "remote-chart-") - g.Expect(err).ToNot(HaveOccurred()) - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() // Build first time. targetPath := filepath.Join(tmpDir, "chart1.tgz") - defer os.RemoveAll(targetPath) buildOpts := BuildOptions{} cb, err := b.Build(context.TODO(), reference, targetPath, buildOpts) g.Expect(err).ToNot(HaveOccurred()) @@ -253,7 +248,6 @@ entries: // Rebuild with a new path. targetPath2 := filepath.Join(tmpDir, "chart2.tgz") - defer os.RemoveAll(targetPath2) cb, err = b.Build(context.TODO(), reference, targetPath2, buildOpts) g.Expect(err).ToNot(HaveOccurred()) g.Expect(cb.Path).To(Equal(targetPath)) @@ -342,16 +336,13 @@ func Test_mergeChartValues(t *testing.T) { func Test_validatePackageAndWriteToPath(t *testing.T) { g := NewWithT(t) - tmpDir, err := os.MkdirTemp("", "validate-pkg-chart-") - g.Expect(err).ToNot(HaveOccurred()) - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() validF, err := os.Open("./../testdata/charts/helmchart-0.1.0.tgz") g.Expect(err).ToNot(HaveOccurred()) defer validF.Close() chartPath := filepath.Join(tmpDir, "chart.tgz") - defer os.Remove(chartPath) err = validatePackageAndWriteToPath(validF, chartPath) g.Expect(err).ToNot(HaveOccurred()) g.Expect(chartPath).To(BeARegularFile()) diff --git a/internal/helm/chart/metadata_test.go b/internal/helm/chart/metadata_test.go index 20c39bc7a..1c002a1df 100644 --- a/internal/helm/chart/metadata_test.go +++ b/internal/helm/chart/metadata_test.go @@ -134,9 +134,7 @@ func TestLoadChartMetadataFromDir(t *testing.T) { g := NewWithT(t) // Create a chart file that exceeds the max chart file size. - tmpDir, err := os.MkdirTemp("", "load-chart-") - g.Expect(err).ToNot(HaveOccurred()) - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() copy.Copy("../testdata/charts/helmchart", tmpDir) bigRequirementsFile := filepath.Join(tmpDir, "requirements.yaml") data := make([]byte, helm.MaxChartFileSize+10) @@ -200,9 +198,7 @@ func TestLoadChartMetadataFromArchive(t *testing.T) { g := NewWithT(t) // Create a chart archive that exceeds the max chart size. - tmpDir, err := os.MkdirTemp("", "load-chart-") - g.Expect(err).ToNot(HaveOccurred()) - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() bigArchiveFile := filepath.Join(tmpDir, "chart.tgz") data := make([]byte, helm.MaxChartSize+10) g.Expect(os.WriteFile(bigArchiveFile, data, 0o640)).ToNot(HaveOccurred()) diff --git a/internal/helm/repository/chart_repository_test.go b/internal/helm/repository/chart_repository_test.go index ce33d8f0f..5bd8600f3 100644 --- a/internal/helm/repository/chart_repository_test.go +++ b/internal/helm/repository/chart_repository_test.go @@ -358,9 +358,7 @@ func TestChartRepository_LoadIndexFromFile(t *testing.T) { g := NewWithT(t) // Create an index file that exceeds the max index size. - tmpDir, err := os.MkdirTemp("", "load-index-") - g.Expect(err).ToNot(HaveOccurred()) - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() bigIndexFile := filepath.Join(tmpDir, "index.yaml") data := make([]byte, helm.MaxIndexSize+10) g.Expect(os.WriteFile(bigIndexFile, data, 0o640)).ToNot(HaveOccurred()) diff --git a/pkg/gcp/gcp_test.go b/pkg/gcp/gcp_test.go index ad1f1dc86..4ab98b7a5 100644 --- a/pkg/gcp/gcp_test.go +++ b/pkg/gcp/gcp_test.go @@ -202,9 +202,7 @@ func TestVisitObjectsCallbackErr(t *testing.T) { } func TestFGetObject(t *testing.T) { - tempDir, err := os.MkdirTemp("", bucketName) - assert.NilError(t, err) - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() gcpClient := &GCSClient{ Client: client, } @@ -218,9 +216,7 @@ func TestFGetObject(t *testing.T) { func TestFGetObjectNotExists(t *testing.T) { object := "notexists.txt" - tempDir, err := os.MkdirTemp("", bucketName) - assert.NilError(t, err) - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() gcsClient := &GCSClient{ Client: client, } @@ -233,9 +229,7 @@ func TestFGetObjectNotExists(t *testing.T) { } func TestFGetObjectDirectoryIsFileName(t *testing.T) { - tempDir, err := os.MkdirTemp("", bucketName) - assert.NilError(t, err) - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() gcpClient := &GCSClient{ Client: client, } diff --git a/pkg/git/gogit/checkout_test.go b/pkg/git/gogit/checkout_test.go index 6307c7ecb..019036b0b 100644 --- a/pkg/git/gogit/checkout_test.go +++ b/pkg/git/gogit/checkout_test.go @@ -35,11 +35,10 @@ import ( ) func TestCheckoutBranch_Checkout(t *testing.T) { - repo, path, err := initRepo() + repo, path, err := initRepo(t) if err != nil { t.Fatal(err) } - defer os.RemoveAll(path) firstCommit, err := commitFile(repo, "branch", "init", time.Now()) if err != nil { @@ -88,8 +87,7 @@ func TestCheckoutBranch_Checkout(t *testing.T) { branch := CheckoutBranch{ Branch: tt.branch, } - tmpDir, _ := os.MkdirTemp("", "test") - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() cc, err := branch.Checkout(context.TODO(), tmpDir, path, nil) if tt.expectedErr != "" { @@ -142,11 +140,10 @@ func TestCheckoutTag_Checkout(t *testing.T) { t.Run(tt.name, func(t *testing.T) { g := NewWithT(t) - repo, path, err := initRepo() + repo, path, err := initRepo(t) if err != nil { t.Fatal(err) } - defer os.RemoveAll(path) var h plumbing.Hash if tt.tag != "" { @@ -163,8 +160,7 @@ func TestCheckoutTag_Checkout(t *testing.T) { tag := CheckoutTag{ Tag: tt.checkoutTag, } - tmpDir, _ := os.MkdirTemp("", "test") - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() cc, err := tag.Checkout(context.TODO(), tmpDir, path, nil) if tt.expectErr != "" { @@ -182,11 +178,10 @@ func TestCheckoutTag_Checkout(t *testing.T) { } func TestCheckoutCommit_Checkout(t *testing.T) { - repo, path, err := initRepo() + repo, path, err := initRepo(t) if err != nil { t.Fatal(err) } - defer os.RemoveAll(path) firstCommit, err := commitFile(repo, "commit", "init", time.Now()) if err != nil { @@ -242,11 +237,7 @@ func TestCheckoutCommit_Checkout(t *testing.T) { Branch: tt.branch, } - tmpDir, err := os.MkdirTemp("", "git2go") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() cc, err := commit.Checkout(context.TODO(), tmpDir, path, nil) if tt.expectError != "" { @@ -326,11 +317,10 @@ func TestCheckoutTagSemVer_Checkout(t *testing.T) { }, } - repo, path, err := initRepo() + repo, path, err := initRepo(t) if err != nil { t.Fatal(err) } - defer os.RemoveAll(path) refs := make(map[string]string, len(tags)) for _, tt := range tags { @@ -352,8 +342,7 @@ func TestCheckoutTagSemVer_Checkout(t *testing.T) { semVer := CheckoutSemVer{ SemVer: tt.constraint, } - tmpDir, _ := os.MkdirTemp("", "test") - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() cc, err := semVer.Checkout(context.TODO(), tmpDir, path, nil) if tt.expectErr != nil { @@ -370,16 +359,11 @@ func TestCheckoutTagSemVer_Checkout(t *testing.T) { } } -func initRepo() (*extgogit.Repository, string, error) { - tmpDir, err := os.MkdirTemp("", "gogit") - if err != nil { - os.RemoveAll(tmpDir) - return nil, "", err - } +func initRepo(t *testing.T) (*extgogit.Repository, string, error) { + tmpDir := t.TempDir() sto := filesystem.NewStorage(osfs.New(tmpDir), cache.NewObjectLRUDefault()) repo, err := extgogit.Init(sto, memfs.New()) if err != nil { - os.RemoveAll(tmpDir) return nil, "", err } return repo, tmpDir, err diff --git a/pkg/git/libgit2/checkout_test.go b/pkg/git/libgit2/checkout_test.go index 3f9e451db..a649607fa 100644 --- a/pkg/git/libgit2/checkout_test.go +++ b/pkg/git/libgit2/checkout_test.go @@ -37,12 +37,11 @@ import ( ) func TestCheckoutBranch_Checkout(t *testing.T) { - repo, err := initBareRepo() + repo, err := initBareRepo(t) if err != nil { t.Fatal(err) } defer repo.Free() - defer os.RemoveAll(filepath.Join(repo.Path(), "..")) cfg, err := git2go.OpenDefault() if err != nil { @@ -105,8 +104,7 @@ func TestCheckoutBranch_Checkout(t *testing.T) { branch := CheckoutBranch{ Branch: tt.branch, } - tmpDir, _ := os.MkdirTemp("", "test") - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() cc, err := branch.Checkout(context.TODO(), tmpDir, repo.Path(), nil) if tt.expectedErr != "" { @@ -158,12 +156,11 @@ func TestCheckoutTag_Checkout(t *testing.T) { t.Run(tt.name, func(t *testing.T) { g := NewWithT(t) - repo, err := initBareRepo() + repo, err := initBareRepo(t) if err != nil { t.Fatal(err) } defer repo.Free() - defer os.RemoveAll(filepath.Join(repo.Path(), "..")) var commit *git2go.Commit if tt.tag != "" { @@ -183,8 +180,7 @@ func TestCheckoutTag_Checkout(t *testing.T) { tag := CheckoutTag{ Tag: tt.checkoutTag, } - tmpDir, _ := os.MkdirTemp("", "test") - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() cc, err := tag.Checkout(context.TODO(), tmpDir, repo.Path(), nil) if tt.expectErr != "" { @@ -205,12 +201,11 @@ func TestCheckoutTag_Checkout(t *testing.T) { func TestCheckoutCommit_Checkout(t *testing.T) { g := NewWithT(t) - repo, err := initBareRepo() + repo, err := initBareRepo(t) if err != nil { t.Fatal(err) } defer repo.Free() - defer os.RemoveAll(filepath.Join(repo.Path(), "..")) c, err := commitFile(repo, "commit", "init", time.Now()) if err != nil { @@ -223,11 +218,7 @@ func TestCheckoutCommit_Checkout(t *testing.T) { commit := CheckoutCommit{ Commit: c.String(), } - tmpDir, err := os.MkdirTemp("", "git2go") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() cc, err := commit.Checkout(context.TODO(), tmpDir, repo.Path(), nil) g.Expect(err).ToNot(HaveOccurred()) @@ -239,11 +230,7 @@ func TestCheckoutCommit_Checkout(t *testing.T) { commit = CheckoutCommit{ Commit: "4dc3185c5fc94eb75048376edeb44571cece25f4", } - tmpDir2, err := os.MkdirTemp("", "git2go") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmpDir2) + tmpDir2 := t.TempDir() cc, err = commit.Checkout(context.TODO(), tmpDir2, repo.Path(), nil) g.Expect(err).To(HaveOccurred()) @@ -313,12 +300,11 @@ func TestCheckoutTagSemVer_Checkout(t *testing.T) { }, } - repo, err := initBareRepo() + repo, err := initBareRepo(t) if err != nil { t.Fatal(err) } defer repo.Free() - defer os.RemoveAll(filepath.Join(repo.Path(), "..")) refs := make(map[string]string, len(tags)) for _, tt := range tags { @@ -349,8 +335,7 @@ func TestCheckoutTagSemVer_Checkout(t *testing.T) { semVer := CheckoutSemVer{ SemVer: tt.constraint, } - tmpDir, _ := os.MkdirTemp("", "test") - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() cc, err := semVer.Checkout(context.TODO(), tmpDir, repo.Path(), nil) if tt.expectErr != nil { @@ -367,14 +352,10 @@ func TestCheckoutTagSemVer_Checkout(t *testing.T) { } } -func initBareRepo() (*git2go.Repository, error) { - tmpDir, err := os.MkdirTemp("", "git2go-") - if err != nil { - return nil, err - } +func initBareRepo(t *testing.T) (*git2go.Repository, error) { + tmpDir := t.TempDir() repo, err := git2go.InitRepository(tmpDir, false) if err != nil { - _ = os.RemoveAll(tmpDir) return nil, err } return repo, nil @@ -514,8 +495,7 @@ func TestCheckout_ED25519(t *testing.T) { // Prepare for checkout. branchCheckoutStrat := &CheckoutBranch{Branch: git.DefaultBranch} - tmpDir, _ := os.MkdirTemp("", "test") - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() ctx, cancel := context.WithTimeout(context.TODO(), timeout) defer cancel() diff --git a/pkg/git/libgit2/managed/managed_test.go b/pkg/git/libgit2/managed/managed_test.go index 14c473852..63afb6721 100644 --- a/pkg/git/libgit2/managed/managed_test.go +++ b/pkg/git/libgit2/managed/managed_test.go @@ -258,8 +258,7 @@ func TestManagedTransport_E2E(t *testing.T) { err = server.InitRepo("../testdata/git/repo", git.DefaultBranch, repoPath) g.Expect(err).ToNot(HaveOccurred()) - tmpDir, _ := os.MkdirTemp("", "test") - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() // Test HTTP transport @@ -285,8 +284,7 @@ func TestManagedTransport_E2E(t *testing.T) { g.Expect(err).ToNot(HaveOccurred()) repo.Free() - tmpDir2, _ := os.MkdirTemp("", "test") - defer os.RemoveAll(tmpDir2) + tmpDir2 := t.TempDir() kp, err := ssh.NewEd25519Generator().Generate() g.Expect(err).ToNot(HaveOccurred()) @@ -313,8 +311,7 @@ func TestManagedTransport_E2E(t *testing.T) { func TestManagedTransport_HandleRedirect(t *testing.T) { g := NewWithT(t) - tmpDir, _ := os.MkdirTemp("", "test") - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() // Force managed transport to be enabled InitManagedTransport(logr.Discard()) diff --git a/pkg/git/strategy/proxy/strategy_proxy_test.go b/pkg/git/strategy/proxy/strategy_proxy_test.go index e61dfa921..8c3133598 100644 --- a/pkg/git/strategy/proxy/strategy_proxy_test.go +++ b/pkg/git/strategy/proxy/strategy_proxy_test.go @@ -264,9 +264,7 @@ func TestCheckoutStrategyForImplementation_Proxied(t *testing.T) { }) g.Expect(err).ToNot(HaveOccurred()) - tmpDir, err := os.MkdirTemp("", "test-checkout") - g.Expect(err).ToNot(HaveOccurred()) - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() // for the NO_PROXY test we dont want to wait the 30s for it to timeout/fail, so shorten the timeout checkoutCtx := context.TODO() diff --git a/pkg/git/strategy/strategy_test.go b/pkg/git/strategy/strategy_test.go index 32f2741a6..055c44f63 100644 --- a/pkg/git/strategy/strategy_test.go +++ b/pkg/git/strategy/strategy_test.go @@ -180,9 +180,7 @@ func TestCheckoutStrategyForImplementation_Auth(t *testing.T) { checkoutStrategy, err := CheckoutStrategyForImplementation(context.TODO(), impl, checkoutOpts) g.Expect(err).ToNot(HaveOccurred()) - tmpDir, err := os.MkdirTemp("", "test-checkout") - g.Expect(err).ToNot(HaveOccurred()) - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() tt.wantFunc(g, checkoutStrategy, tmpDir, repoURL, authOpts) } @@ -271,9 +269,7 @@ func TestCheckoutStrategyForImplementation_SemVerCheckout(t *testing.T) { } // Clone the repo locally. - cloneDir, err := os.MkdirTemp("", "test-clone") - g.Expect(err).ToNot(HaveOccurred()) - defer os.RemoveAll(cloneDir) + cloneDir := t.TempDir() repo, err := extgogit.PlainClone(cloneDir, false, &extgogit.CloneOptions{ URL: repoURL, }) @@ -332,9 +328,7 @@ func TestCheckoutStrategyForImplementation_SemVerCheckout(t *testing.T) { g.Expect(err).ToNot(HaveOccurred()) // Checkout and verify. - tmpDir, err := os.MkdirTemp("", "test-checkout") - g.Expect(err).ToNot(HaveOccurred()) - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() cc, err := checkoutStrategy.Checkout(context.TODO(), tmpDir, repoURL, authOpts) if tt.expectErr != nil { @@ -425,9 +419,7 @@ func TestCheckoutStrategyForImplementation_WithCtxTimeout(t *testing.T) { checkoutStrategy, err := CheckoutStrategyForImplementation(context.TODO(), impl, checkoutOpts) g.Expect(err).ToNot(HaveOccurred()) - tmpDir, err := os.MkdirTemp("", "test-checkout") - g.Expect(err).ToNot(HaveOccurred()) - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() checkoutCtx, cancel := context.WithTimeout(context.TODO(), tt.timeout) defer cancel() diff --git a/pkg/minio/minio_test.go b/pkg/minio/minio_test.go index d391b1278..d1c3caed8 100644 --- a/pkg/minio/minio_test.go +++ b/pkg/minio/minio_test.go @@ -144,22 +144,18 @@ func TestBucketNotExists(t *testing.T) { func TestFGetObject(t *testing.T) { ctx := context.Background() - tempDir, err := os.MkdirTemp("", bucketName) - assert.NilError(t, err) - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() path := filepath.Join(tempDir, sourceignore.IgnoreFile) - _, err = minioClient.FGetObject(ctx, bucketName, objectName, path) + _, err := minioClient.FGetObject(ctx, bucketName, objectName, path) assert.NilError(t, err) } func TestFGetObjectNotExists(t *testing.T) { ctx := context.Background() - tempDir, err := os.MkdirTemp("", bucketName) - assert.NilError(t, err) - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() badKey := "invalid.txt" path := filepath.Join(tempDir, badKey) - _, err = minioClient.FGetObject(ctx, bucketName, badKey, path) + _, err := minioClient.FGetObject(ctx, bucketName, badKey, path) assert.Error(t, err, "The specified key does not exist.") assert.Check(t, minioClient.ObjectIsNotFound(err)) } diff --git a/pkg/sourceignore/sourceignore_test.go b/pkg/sourceignore/sourceignore_test.go index cbd73352d..5ba78cda8 100644 --- a/pkg/sourceignore/sourceignore_test.go +++ b/pkg/sourceignore/sourceignore_test.go @@ -197,11 +197,7 @@ func TestDefaultPatterns(t *testing.T) { } func TestLoadExcludePatterns(t *testing.T) { - tmpDir, err := os.MkdirTemp("", "sourceignore-load-") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() files := map[string]string{ ".sourceignore": "root.txt", "d/.gitignore": "ignored", @@ -209,10 +205,10 @@ func TestLoadExcludePatterns(t *testing.T) { "a/b/.sourceignore": "subdir.txt", } for n, c := range files { - if err = os.MkdirAll(filepath.Join(tmpDir, filepath.Dir(n)), 0o750); err != nil { + if err := os.MkdirAll(filepath.Join(tmpDir, filepath.Dir(n)), 0o750); err != nil { t.Fatal(err) } - if err = os.WriteFile(filepath.Join(tmpDir, n), []byte(c), 0o640); err != nil { + if err := os.WriteFile(filepath.Join(tmpDir, n), []byte(c), 0o640); err != nil { t.Fatal(err) } }