Merge pull request #701 from Juneezee/test/t.TempDir

This commit is contained in:
Hidde Beydals 2022-04-29 17:39:23 +02:00 committed by GitHub
commit 89a4e52fe3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
19 changed files with 125 additions and 378 deletions

View File

@ -107,11 +107,7 @@ func Test_fetchEtagIndex(t *testing.T) {
} }
t.Run("fetches etag index", func(t *testing.T) { t.Run("fetches etag index", func(t *testing.T) {
tmp, err := os.MkdirTemp("", "test-bucket") tmp := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmp)
client := mockBucketClient{bucketName: bucketName} client := mockBucketClient{bucketName: bucketName}
client.addObject("foo.yaml", mockBucketObject{data: "foo.yaml", etag: "etag1"}) 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"}) client.addObject("baz.yaml", mockBucketObject{data: "baz.yaml", etag: "etag3"})
index := newEtagIndex() index := newEtagIndex()
err = fetchEtagIndex(context.TODO(), client, bucket.DeepCopy(), index, tmp) err := fetchEtagIndex(context.TODO(), client, bucket.DeepCopy(), index, tmp)
if err != nil { if err != nil {
t.Fatal(err) 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) { t.Run("an error while bucket does not exist", func(t *testing.T) {
tmp, err := os.MkdirTemp("", "test-bucket") tmp := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmp)
client := mockBucketClient{bucketName: "other-bucket-name"} client := mockBucketClient{bucketName: "other-bucket-name"}
index := newEtagIndex() 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") assert.ErrorContains(t, err, "not found")
}) })
t.Run("filters with .sourceignore rules", func(t *testing.T) { t.Run("filters with .sourceignore rules", func(t *testing.T) {
tmp, err := os.MkdirTemp("", "test-bucket") tmp := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmp)
client := mockBucketClient{bucketName: bucketName} client := mockBucketClient{bucketName: bucketName}
client.addObject(".sourceignore", mockBucketObject{etag: "sourceignore1", data: `*.txt`}) 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"}) client.addObject("foo.txt", mockBucketObject{etag: "etag2", data: "foo.txt"})
index := newEtagIndex() index := newEtagIndex()
err = fetchEtagIndex(context.TODO(), client, bucket.DeepCopy(), index, tmp) err := fetchEtagIndex(context.TODO(), client, bucket.DeepCopy(), index, tmp)
if err != nil { if err != nil {
t.Fatal(err) 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) { t.Run("filters with ignore rules from object", func(t *testing.T) {
tmp, err := os.MkdirTemp("", "test-bucket") tmp := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmp)
client := mockBucketClient{bucketName: bucketName} client := mockBucketClient{bucketName: bucketName}
client.addObject(".sourceignore", mockBucketObject{etag: "sourceignore1", data: `*.txt`}) client.addObject(".sourceignore", mockBucketObject{etag: "sourceignore1", data: `*.txt`})
@ -185,7 +169,7 @@ func Test_fetchEtagIndex(t *testing.T) {
bucket.Spec.Ignore = &ignore bucket.Spec.Ignore = &ignore
index := newEtagIndex() index := newEtagIndex()
err = fetchEtagIndex(context.TODO(), client, bucket.DeepCopy(), index, tmp) err := fetchEtagIndex(context.TODO(), client, bucket.DeepCopy(), index, tmp)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -212,11 +196,7 @@ func Test_fetchFiles(t *testing.T) {
} }
t.Run("fetches files", func(t *testing.T) { t.Run("fetches files", func(t *testing.T) {
tmp, err := os.MkdirTemp("", "test-bucket") tmp := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmp)
client := mockBucketClient{bucketName: bucketName} client := mockBucketClient{bucketName: bucketName}
client.addObject("foo.yaml", mockBucketObject{data: "foo.yaml", etag: "etag1"}) client.addObject("foo.yaml", mockBucketObject{data: "foo.yaml", etag: "etag1"})
@ -225,7 +205,7 @@ func Test_fetchFiles(t *testing.T) {
index := client.objectsToEtagIndex() index := client.objectsToEtagIndex()
err = fetchIndexFiles(context.TODO(), client, bucket.DeepCopy(), index, tmp) err := fetchIndexFiles(context.TODO(), client, bucket.DeepCopy(), index, tmp)
if err != nil { if err != nil {
t.Fatal(err) 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) { t.Run("an error while fetching returns an error for the whole procedure", func(t *testing.T) {
tmp, err := os.MkdirTemp("", "test-bucket") tmp := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmp)
client := mockBucketClient{bucketName: bucketName, objects: map[string]mockBucketObject{}} client := mockBucketClient{bucketName: bucketName, objects: map[string]mockBucketObject{}}
client.objects["error"] = 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 { if err == nil {
t.Fatal("expected error but got nil") t.Fatal("expected error but got nil")
} }
}) })
t.Run("a changed etag updates the index", func(t *testing.T) { t.Run("a changed etag updates the index", func(t *testing.T) {
tmp, err := os.MkdirTemp("", "test-bucket") tmp := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmp)
client := mockBucketClient{bucketName: bucketName} client := mockBucketClient{bucketName: bucketName}
client.addObject("foo.yaml", mockBucketObject{data: "foo.yaml", etag: "etag2"}) client.addObject("foo.yaml", mockBucketObject{data: "foo.yaml", etag: "etag2"})
index := newEtagIndex() index := newEtagIndex()
index.Add("foo.yaml", "etag1") 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 { if err != nil {
t.Fatal(err) 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) { t.Run("a disappeared index entry is removed from the index", func(t *testing.T) {
tmp, err := os.MkdirTemp("", "test-bucket") tmp := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmp)
client := mockBucketClient{bucketName: bucketName} client := mockBucketClient{bucketName: bucketName}
client.addObject("foo.yaml", mockBucketObject{data: "foo.yaml", etag: "etag1"}) 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 // Does not exist on server
index.Add("bar.yaml", "etag2") 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 { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -301,11 +269,7 @@ func Test_fetchFiles(t *testing.T) {
t.Run("can fetch more than maxConcurrentFetches", func(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 // this will fail if, for example, the semaphore is not used correctly and blocks
tmp, err := os.MkdirTemp("", "test-bucket") tmp := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmp)
client := mockBucketClient{bucketName: bucketName} client := mockBucketClient{bucketName: bucketName}
for i := 0; i < 2*maxConcurrentBucketFetches; i++ { for i := 0; i < 2*maxConcurrentBucketFetches; i++ {
@ -314,7 +278,7 @@ func Test_fetchFiles(t *testing.T) {
} }
index := client.objectsToEtagIndex() index := client.objectsToEtagIndex()
err = fetchIndexFiles(context.TODO(), client, bucket.DeepCopy(), index, tmp) err := fetchIndexFiles(context.TODO(), client, bucket.DeepCopy(), index, tmp)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View File

@ -539,9 +539,7 @@ func TestBucketReconciler_reconcileSource_generic(t *testing.T) {
Client: builder.Build(), Client: builder.Build(),
Storage: testStorage, Storage: testStorage,
} }
tmpDir, err := os.MkdirTemp("", "reconcile-bucket-source-") tmpDir := t.TempDir()
g.Expect(err).ToNot(HaveOccurred())
defer os.RemoveAll(tmpDir)
obj := &sourcev1.Bucket{ obj := &sourcev1.Bucket{
TypeMeta: metav1.TypeMeta{ TypeMeta: metav1.TypeMeta{
@ -834,9 +832,7 @@ func TestBucketReconciler_reconcileSource_gcs(t *testing.T) {
Client: builder.Build(), Client: builder.Build(),
Storage: testStorage, Storage: testStorage,
} }
tmpDir, err := os.MkdirTemp("", "reconcile-bucket-source-") tmpDir := t.TempDir()
g.Expect(err).ToNot(HaveOccurred())
defer os.RemoveAll(tmpDir)
// Test bucket object. // Test bucket object.
obj := &sourcev1.Bucket{ obj := &sourcev1.Bucket{
@ -992,9 +988,7 @@ func TestBucketReconciler_reconcileArtifact(t *testing.T) {
Storage: testStorage, Storage: testStorage,
} }
tmpDir, err := os.MkdirTemp("", "reconcile-bucket-artifact-") tmpDir := t.TempDir()
g.Expect(err).ToNot(HaveOccurred())
defer os.RemoveAll(tmpDir)
obj := &sourcev1.Bucket{ obj := &sourcev1.Bucket{
TypeMeta: metav1.TypeMeta{ TypeMeta: metav1.TypeMeta{

View File

@ -509,9 +509,7 @@ func TestGitRepositoryReconciler_reconcileSource_authStrategy(t *testing.T) {
t.Skipf("Skipped for Git implementation %q", i) t.Skipf("Skipped for Git implementation %q", i)
} }
tmpDir, err := os.MkdirTemp("", "auth-strategy-") tmpDir := t.TempDir()
g.Expect(err).To(BeNil())
defer os.RemoveAll(tmpDir)
obj := obj.DeepCopy() obj := obj.DeepCopy()
obj.Spec.GitImplementation = i obj.Spec.GitImplementation = i
@ -671,9 +669,7 @@ func TestGitRepositoryReconciler_reconcileSource_checkoutStrategy(t *testing.T)
t.Skipf("Skipped for Git implementation %q", i) t.Skipf("Skipped for Git implementation %q", i)
} }
tmpDir, err := os.MkdirTemp("", "checkout-strategy-") tmpDir := t.TempDir()
g.Expect(err).NotTo(HaveOccurred())
defer os.RemoveAll(tmpDir)
obj := obj.DeepCopy() obj := obj.DeepCopy()
obj.Spec.GitImplementation = i obj.Spec.GitImplementation = i
@ -1072,9 +1068,7 @@ func TestGitRepositoryReconciler_reconcileInclude(t *testing.T) {
tt.beforeFunc(obj) tt.beforeFunc(obj)
} }
tmpDir, err := os.MkdirTemp("", "include-") tmpDir := t.TempDir()
g.Expect(err).NotTo(HaveOccurred())
defer os.RemoveAll(tmpDir)
var commit git.Commit var commit git.Commit
var includes artifactSet var includes artifactSet

View File

@ -307,9 +307,7 @@ func TestHelmChartReconciler_reconcileStorage(t *testing.T) {
func TestHelmChartReconciler_reconcileSource(t *testing.T) { func TestHelmChartReconciler_reconcileSource(t *testing.T) {
g := NewWithT(t) g := NewWithT(t)
tmpDir, err := os.MkdirTemp("", "reconcile-tarball-") tmpDir := t.TempDir()
g.Expect(err).ToNot(HaveOccurred())
defer os.RemoveAll(tmpDir)
storage, err := NewStorage(tmpDir, "example.com", retentionTTL, retentionRecords) storage, err := NewStorage(tmpDir, "example.com", retentionTTL, retentionRecords)
g.Expect(err).ToNot(HaveOccurred()) g.Expect(err).ToNot(HaveOccurred())
@ -781,9 +779,7 @@ func TestHelmChartReconciler_buildFromHelmRepository(t *testing.T) {
func TestHelmChartReconciler_buildFromTarballArtifact(t *testing.T) { func TestHelmChartReconciler_buildFromTarballArtifact(t *testing.T) {
g := NewWithT(t) g := NewWithT(t)
tmpDir, err := os.MkdirTemp("", "reconcile-tarball-") tmpDir := t.TempDir()
g.Expect(err).ToNot(HaveOccurred())
defer os.RemoveAll(tmpDir)
storage, err := NewStorage(tmpDir, "example.com", retentionTTL, retentionRecords) storage, err := NewStorage(tmpDir, "example.com", retentionTTL, retentionRecords)
g.Expect(err).ToNot(HaveOccurred()) g.Expect(err).ToNot(HaveOccurred())

View File

@ -728,9 +728,7 @@ func TestHelmRepositoryReconciler_reconcileArtifact(t *testing.T) {
}, },
} }
tmpDir, err := os.MkdirTemp("", "test-reconcile-artifact-") tmpDir := t.TempDir()
g.Expect(err).ToNot(HaveOccurred())
defer os.RemoveAll(tmpDir)
// Create an empty cache file. // Create an empty cache file.
cachePath := filepath.Join(tmpDir, "index.yaml") cachePath := filepath.Join(tmpDir, "index.yaml")

View File

@ -35,20 +35,8 @@ import (
sourcev1 "github.com/fluxcd/source-controller/api/v1beta2" 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) { func TestStorageConstructor(t *testing.T) {
dir, err := createStoragePath() dir := t.TempDir()
if err != nil {
t.Fatal(err)
}
t.Cleanup(cleanupStoragePath(dir))
if _, err := NewStorage("/nonexistent", "hostname", time.Minute, 2); err == nil { if _, err := NewStorage("/nonexistent", "hostname", time.Minute, 2); err == nil {
t.Fatal("nonexistent path was allowable in storage constructor") 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) { func TestStorage_Archive(t *testing.T) {
dir, err := createStoragePath() dir := t.TempDir()
if err != nil {
t.Fatal(err)
}
t.Cleanup(cleanupStoragePath(dir))
storage, err := NewStorage(dir, "hostname", time.Minute, 2) storage, err := NewStorage(dir, "hostname", time.Minute, 2)
if err != nil { if err != nil {
@ -125,15 +109,7 @@ func TestStorage_Archive(t *testing.T) {
} }
createFiles := func(files map[string][]byte) (dir string, err error) { createFiles := func(files map[string][]byte) (dir string, err error) {
defer func() { dir = t.TempDir()
if err != nil && dir != "" {
os.RemoveAll(dir)
}
}()
dir, err = os.MkdirTemp("", "archive-test-files-")
if err != nil {
return
}
for name, b := range files { for name, b := range files {
absPath := filepath.Join(dir, name) absPath := filepath.Join(dir, name)
if err = os.MkdirAll(filepath.Dir(absPath), 0o750); err != nil { 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) { func TestStorageRemoveAllButCurrent(t *testing.T) {
t.Run("bad directory in archive", func(t *testing.T) { t.Run("bad directory in archive", func(t *testing.T) {
dir, err := os.MkdirTemp("", "") dir := t.TempDir()
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.RemoveAll(dir) })
s, err := NewStorage(dir, "hostname", time.Minute, 2) s, err := NewStorage(dir, "hostname", time.Minute, 2)
if err != nil { if err != nil {
@ -303,9 +275,7 @@ func TestStorageRemoveAllButCurrent(t *testing.T) {
t.Run("collect names of deleted items", func(t *testing.T) { t.Run("collect names of deleted items", func(t *testing.T) {
g := NewWithT(t) g := NewWithT(t)
dir, err := os.MkdirTemp("", "") dir := t.TempDir()
g.Expect(err).ToNot(HaveOccurred())
t.Cleanup(func() { os.RemoveAll(dir) })
s, err := NewStorage(dir, "hostname", time.Minute, 2) s, err := NewStorage(dir, "hostname", time.Minute, 2)
g.Expect(err).ToNot(HaveOccurred(), "failed to create new storage") g.Expect(err).ToNot(HaveOccurred(), "failed to create new storage")
@ -366,9 +336,7 @@ func TestStorageRemoveAll(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
g := NewWithT(t) g := NewWithT(t)
dir, err := os.MkdirTemp("", "") dir := t.TempDir()
g.Expect(err).ToNot(HaveOccurred())
t.Cleanup(func() { os.RemoveAll(dir) })
s, err := NewStorage(dir, "hostname", time.Minute, 2) s, err := NewStorage(dir, "hostname", time.Minute, 2)
g.Expect(err).ToNot(HaveOccurred(), "failed to create new storage") g.Expect(err).ToNot(HaveOccurred(), "failed to create new storage")
@ -394,11 +362,7 @@ func TestStorageCopyFromPath(t *testing.T) {
Content []byte Content []byte
} }
dir, err := createStoragePath() dir := t.TempDir()
if err != nil {
t.Fatal(err)
}
t.Cleanup(cleanupStoragePath(dir))
storage, err := NewStorage(dir, "hostname", time.Minute, 2) storage, err := NewStorage(dir, "hostname", time.Minute, 2)
if err != nil { if err != nil {
@ -406,11 +370,7 @@ func TestStorageCopyFromPath(t *testing.T) {
} }
createFile := func(file *File) (absPath string, err error) { createFile := func(file *File) (absPath string, err error) {
dir, err = os.MkdirTemp("", "test-files-") dir = t.TempDir()
if err != nil {
return
}
t.Cleanup(cleanupStoragePath(dir))
absPath = filepath.Join(dir, file.Name) absPath = filepath.Join(dir, file.Name)
if err = os.MkdirAll(filepath.Dir(absPath), 0o750); err != nil { if err = os.MkdirAll(filepath.Dir(absPath), 0o750); err != nil {
return return
@ -474,7 +434,6 @@ func TestStorageCopyFromPath(t *testing.T) {
t.Error(err) t.Error(err)
return return
} }
defer os.RemoveAll(absPath)
artifact := sourcev1.Artifact{ artifact := sourcev1.Artifact{
Path: filepath.Join(randStringRunes(10), randStringRunes(10), randStringRunes(10)), Path: filepath.Join(randStringRunes(10), randStringRunes(10), randStringRunes(10)),
} }
@ -581,9 +540,7 @@ func TestStorage_getGarbageFiles(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
g := NewWithT(t) g := NewWithT(t)
dir, err := os.MkdirTemp("", "") dir := t.TempDir()
g.Expect(err).ToNot(HaveOccurred())
t.Cleanup(func() { os.RemoveAll(dir) })
s, err := NewStorage(dir, "hostname", tt.ttl, tt.maxItemsToBeRetained) s, err := NewStorage(dir, "hostname", tt.ttl, tt.maxItemsToBeRetained)
g.Expect(err).ToNot(HaveOccurred(), "failed to create new storage") g.Expect(err).ToNot(HaveOccurred(), "failed to create new storage")
@ -657,9 +614,7 @@ func TestStorage_GarbageCollect(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
g := NewWithT(t) g := NewWithT(t)
dir, err := os.MkdirTemp("", "") dir := t.TempDir()
g.Expect(err).ToNot(HaveOccurred())
t.Cleanup(func() { os.RemoveAll(dir) })
s, err := NewStorage(dir, "hostname", time.Second*2, 2) s, err := NewStorage(dir, "hostname", time.Second*2, 2)
g.Expect(err).ToNot(HaveOccurred(), "failed to create new storage") g.Expect(err).ToNot(HaveOccurred(), "failed to create new storage")

View File

@ -19,13 +19,9 @@ var (
) )
func TestRenameWithFallback(t *testing.T) { func TestRenameWithFallback(t *testing.T) {
dir, err := os.MkdirTemp("", "dep") dir := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)
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") t.Fatal("expected an error for non existing file, but got nil")
} }
@ -37,31 +33,27 @@ func TestRenameWithFallback(t *testing.T) {
srcf.Close() 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) t.Fatal(err)
} }
srcpath = filepath.Join(dir, "a") srcpath = filepath.Join(dir, "a")
if err = os.MkdirAll(srcpath, 0o770); err != nil { if err := os.MkdirAll(srcpath, 0o770); err != nil {
t.Fatal(err) t.Fatal(err)
} }
dstpath := filepath.Join(dir, "b") dstpath := filepath.Join(dir, "b")
if err = os.MkdirAll(dstpath, 0o770); err != nil { if err := os.MkdirAll(dstpath, 0o770); err != nil {
t.Fatal(err) 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") t.Fatal("expected an error if dst is an existing directory, but got nil")
} }
} }
func TestCopyDir(t *testing.T) { func TestCopyDir(t *testing.T) {
dir, err := os.MkdirTemp("", "dep") dir := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)
srcdir := filepath.Join(dir, "src") srcdir := filepath.Join(dir, "src")
if err := os.MkdirAll(srcdir, 0o750); err != nil { if err := os.MkdirAll(srcdir, 0o750); err != nil {
@ -81,7 +73,7 @@ func TestCopyDir(t *testing.T) {
for i, file := range files { for i, file := range files {
fn := filepath.Join(srcdir, file.path) fn := filepath.Join(srcdir, file.path)
dn := filepath.Dir(fn) dn := filepath.Dir(fn)
if err = os.MkdirAll(dn, 0o750); err != nil { if err := os.MkdirAll(dn, 0o750); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -149,20 +141,15 @@ func TestCopyDirFail_SrcInaccessible(t *testing.T) {
var srcdir, dstdir string var srcdir, dstdir string
cleanup := setupInaccessibleDir(t, func(dir string) error { setupInaccessibleDir(t, func(dir string) error {
srcdir = filepath.Join(dir, "src") srcdir = filepath.Join(dir, "src")
return os.MkdirAll(srcdir, 0o750) return os.MkdirAll(srcdir, 0o750)
}) })
defer cleanup()
dir, err := os.MkdirTemp("", "dep") dir := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)
dstdir = filepath.Join(dir, "dst") 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) 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 var srcdir, dstdir string
dir, err := os.MkdirTemp("", "dep") dir := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)
srcdir = filepath.Join(dir, "src") srcdir = filepath.Join(dir, "src")
if err = os.MkdirAll(srcdir, 0o750); err != nil { if err := os.MkdirAll(srcdir, 0o750); err != nil {
t.Fatal(err) t.Fatal(err)
} }
cleanup := setupInaccessibleDir(t, func(dir string) error { setupInaccessibleDir(t, func(dir string) error {
dstdir = filepath.Join(dir, "dst") dstdir = filepath.Join(dir, "dst")
return nil return nil
}) })
defer cleanup()
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) 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) { func TestCopyDirFail_SrcIsNotDir(t *testing.T) {
var srcdir, dstdir string var srcdir, dstdir string
dir, err := os.MkdirTemp("", "dep") dir := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)
srcdir = filepath.Join(dir, "src") srcdir = filepath.Join(dir, "src")
if _, err = os.Create(srcdir); err != nil { if _, err := os.Create(srcdir); err != nil {
t.Fatal(err) t.Fatal(err)
} }
dstdir = filepath.Join(dir, "dst") 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) 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) { func TestCopyDirFail_DstExists(t *testing.T) {
var srcdir, dstdir string var srcdir, dstdir string
dir, err := os.MkdirTemp("", "dep") dir := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)
srcdir = filepath.Join(dir, "src") srcdir = filepath.Join(dir, "src")
if err = os.MkdirAll(srcdir, 0o750); err != nil { if err := os.MkdirAll(srcdir, 0o750); err != nil {
t.Fatal(err) t.Fatal(err)
} }
dstdir = filepath.Join(dir, "dst") dstdir = filepath.Join(dir, "dst")
if err = os.MkdirAll(dstdir, 0o750); err != nil { if err := os.MkdirAll(dstdir, 0o750); err != nil {
t.Fatal(err) 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) 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 var srcdir, dstdir string
dir, err := os.MkdirTemp("", "dep") dir := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)
srcdir = filepath.Join(dir, "src") srcdir = filepath.Join(dir, "src")
if err = os.MkdirAll(srcdir, 0o750); err != nil { if err := os.MkdirAll(srcdir, 0o750); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -297,11 +269,7 @@ func TestCopyDirFailOpen(t *testing.T) {
} }
func TestCopyFile(t *testing.T) { func TestCopyFile(t *testing.T) {
dir, err := os.MkdirTemp("", "dep") dir := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)
srcf, err := os.Create(filepath.Join(dir, "srcfile")) srcf, err := os.Create(filepath.Join(dir, "srcfile"))
if err != nil { if err != nil {
@ -344,10 +312,7 @@ func TestCopyFile(t *testing.T) {
} }
func TestCopyFileSymlink(t *testing.T) { func TestCopyFileSymlink(t *testing.T) {
dir, err := os.MkdirTemp("", "dep") dir := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer cleanUpDir(dir) defer cleanUpDir(dir)
testcases := map[string]string{ testcases := map[string]string{
@ -406,11 +371,7 @@ func TestCopyFileLongFilePath(t *testing.T) {
t.Skip("skipping on non-windows") t.Skip("skipping on non-windows")
} }
dir, err := os.MkdirTemp("", "dep") dir := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer cleanUpDir(dir)
// Create a directory with a long-enough path name to cause the bug in #774. // Create a directory with a long-enough path name to cause the bug in #774.
dirName := "" dirName := ""
@ -423,7 +384,7 @@ func TestCopyFileLongFilePath(t *testing.T) {
t.Fatalf("%+v", fmt.Errorf("unable to create temp directory: %s", fullPath)) 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 { if err != nil {
t.Fatalf("%+v", err) t.Fatalf("%+v", err)
} }
@ -444,11 +405,7 @@ func TestCopyFileFail(t *testing.T) {
t.Skip("skipping on windows") t.Skip("skipping on windows")
} }
dir, err := os.MkdirTemp("", "dep") dir := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)
srcf, err := os.Create(filepath.Join(dir, "srcfile")) srcf, err := os.Create(filepath.Join(dir, "srcfile"))
if err != nil { if err != nil {
@ -458,11 +415,10 @@ func TestCopyFileFail(t *testing.T) {
var dstdir string var dstdir string
cleanup := setupInaccessibleDir(t, func(dir string) error { setupInaccessibleDir(t, func(dir string) error {
dstdir = filepath.Join(dir, "dir") dstdir = filepath.Join(dir, "dir")
return os.Mkdir(dstdir, 0o770) return os.Mkdir(dstdir, 0o770)
}) })
defer cleanup()
fn := filepath.Join(dstdir, "file") fn := filepath.Join(dstdir, "file")
if err := copyFile(srcf.Name(), fn); err == nil { 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 // If setupInaccessibleDir fails in its preparation, or op fails, t.Fatal
// will be invoked. // will be invoked.
// func setupInaccessibleDir(t *testing.T, op func(dir string) error) {
// 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() {
dir, err := os.MkdirTemp("", "dep") dir, err := os.MkdirTemp("", "dep")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
return nil // keep compiler happy
} }
subdir := filepath.Join(dir, "dir") subdir := filepath.Join(dir, "dir")
cleanup := func() { t.Cleanup(func() {
if err := os.Chmod(subdir, 0o770); err != nil { if err := os.Chmod(subdir, 0o770); err != nil {
t.Error(err) t.Error(err)
} }
if err := os.RemoveAll(dir); err != nil { })
t.Error(err)
}
}
if err := os.Mkdir(subdir, 0o770); err != nil { if err := os.Mkdir(subdir, 0o770); err != nil {
cleanup()
t.Fatal(err) t.Fatal(err)
return nil
} }
if err := op(subdir); err != nil { if err := op(subdir); err != nil {
cleanup()
t.Fatal(err) t.Fatal(err)
return nil
} }
if err := os.Chmod(subdir, 0o660); err != nil { if err := os.Chmod(subdir, 0o660); err != nil {
cleanup()
t.Fatal(err) t.Fatal(err)
return nil
} }
return cleanup
} }
func TestIsDir(t *testing.T) { func TestIsDir(t *testing.T) {
@ -530,11 +470,10 @@ func TestIsDir(t *testing.T) {
var dn string var dn string
cleanup := setupInaccessibleDir(t, func(dir string) error { setupInaccessibleDir(t, func(dir string) error {
dn = filepath.Join(dir, "dir") dn = filepath.Join(dir, "dir")
return os.Mkdir(dn, 0o770) return os.Mkdir(dn, 0o770)
}) })
defer cleanup()
tests := map[string]struct { tests := map[string]struct {
exists bool exists bool
@ -568,14 +507,10 @@ func TestIsDir(t *testing.T) {
} }
func TestIsSymlink(t *testing.T) { func TestIsSymlink(t *testing.T) {
dir, err := os.MkdirTemp("", "dep") dir := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)
dirPath := filepath.Join(dir, "directory") dirPath := filepath.Join(dir, "directory")
if err = os.MkdirAll(dirPath, 0o770); err != nil { if err := os.MkdirAll(dirPath, 0o770); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -601,7 +536,7 @@ func TestIsSymlink(t *testing.T) {
inaccessibleSymlink string inaccessibleSymlink string
) )
cleanup := setupInaccessibleDir(t, func(dir string) error { setupInaccessibleDir(t, func(dir string) error {
inaccessibleFile = filepath.Join(dir, "file") inaccessibleFile = filepath.Join(dir, "file")
if fh, err := os.Create(inaccessibleFile); err != nil { if fh, err := os.Create(inaccessibleFile); err != nil {
return err return err
@ -612,7 +547,6 @@ func TestIsSymlink(t *testing.T) {
inaccessibleSymlink = filepath.Join(dir, "symlink") inaccessibleSymlink = filepath.Join(dir, "symlink")
return os.Symlink(inaccessibleFile, inaccessibleSymlink) return os.Symlink(inaccessibleFile, inaccessibleSymlink)
}) })
defer cleanup()
tests := map[string]struct{ expected, err bool }{ tests := map[string]struct{ expected, err bool }{
dirPath: {false, false}, dirPath: {false, false},

View File

@ -177,9 +177,7 @@ fullnameOverride: "full-foo-name-override"`),
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
g := NewWithT(t) g := NewWithT(t)
workDir, err := os.MkdirTemp("", "local-builder-") workDir := t.TempDir()
g.Expect(err).ToNot(HaveOccurred())
defer os.RemoveAll(workDir)
// Only if the reference is a LocalReference, set the WorkDir. // Only if the reference is a LocalReference, set the WorkDir.
localRef, ok := tt.reference.(LocalReference) localRef, ok := tt.reference.(LocalReference)
@ -213,7 +211,6 @@ fullnameOverride: "full-foo-name-override"`),
// Target path with name similar to the workDir. // Target path with name similar to the workDir.
targetPath := workDir + ".tgz" targetPath := workDir + ".tgz"
defer os.RemoveAll(targetPath)
dm := NewDependencyManager( dm := NewDependencyManager(
WithRepositories(tt.repositories), WithRepositories(tt.repositories),
@ -247,18 +244,14 @@ fullnameOverride: "full-foo-name-override"`),
func TestLocalBuilder_Build_CachedChart(t *testing.T) { func TestLocalBuilder_Build_CachedChart(t *testing.T) {
g := NewWithT(t) g := NewWithT(t)
workDir, err := os.MkdirTemp("", "local-builder-") workDir := t.TempDir()
g.Expect(err).ToNot(HaveOccurred())
defer os.RemoveAll(workDir)
testChartPath := "./../testdata/charts/helmchart" testChartPath := "./../testdata/charts/helmchart"
dm := NewDependencyManager() dm := NewDependencyManager()
b := NewLocalBuilder(dm) b := NewLocalBuilder(dm)
tmpDir, err := os.MkdirTemp("", "local-chart-") tmpDir := t.TempDir()
g.Expect(err).ToNot(HaveOccurred())
defer os.RemoveAll(tmpDir)
// Copy the source chart into the workdir. // Copy the source chart into the workdir.
g.Expect(copy.Copy(testChartPath, filepath.Join(workDir, "testdata", "charts", filepath.Base("helmchart")))).ToNot(HaveOccurred()) 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 buildOpts.CachedChart = cb.Path
targetPath2 := filepath.Join(tmpDir, "chart2.tgz") targetPath2 := filepath.Join(tmpDir, "chart2.tgz")
defer os.RemoveAll(targetPath2)
cb, err = b.Build(context.TODO(), reference, targetPath2, buildOpts) cb, err = b.Build(context.TODO(), reference, targetPath2, buildOpts)
g.Expect(err).ToNot(HaveOccurred()) g.Expect(err).ToNot(HaveOccurred())
g.Expect(cb.Path).To(Equal(targetPath)) 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) { t.Run(tt.name, func(t *testing.T) {
g := NewWithT(t) g := NewWithT(t)
baseDir, err := os.MkdirTemp("", "merge-file-values-*") baseDir := t.TempDir()
g.Expect(err).ToNot(HaveOccurred())
defer os.RemoveAll(baseDir)
for _, f := range tt.files { for _, f := range tt.files {
g.Expect(os.WriteFile(filepath.Join(baseDir, f.Name), f.Data, 0o640)).To(Succeed()) g.Expect(os.WriteFile(filepath.Join(baseDir, f.Name), f.Data, 0o640)).To(Succeed())

View File

@ -159,9 +159,7 @@ entries:
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
g := NewWithT(t) g := NewWithT(t)
tmpDir, err := os.MkdirTemp("", "remote-chart-builder-") tmpDir := t.TempDir()
g.Expect(err).ToNot(HaveOccurred())
defer os.RemoveAll(tmpDir)
targetPath := filepath.Join(tmpDir, "chart.tgz") targetPath := filepath.Join(tmpDir, "chart.tgz")
if tt.repository != nil { if tt.repository != nil {
@ -237,13 +235,10 @@ entries:
b := NewRemoteBuilder(repository) b := NewRemoteBuilder(repository)
tmpDir, err := os.MkdirTemp("", "remote-chart-") tmpDir := t.TempDir()
g.Expect(err).ToNot(HaveOccurred())
defer os.RemoveAll(tmpDir)
// Build first time. // Build first time.
targetPath := filepath.Join(tmpDir, "chart1.tgz") targetPath := filepath.Join(tmpDir, "chart1.tgz")
defer os.RemoveAll(targetPath)
buildOpts := BuildOptions{} buildOpts := BuildOptions{}
cb, err := b.Build(context.TODO(), reference, targetPath, buildOpts) cb, err := b.Build(context.TODO(), reference, targetPath, buildOpts)
g.Expect(err).ToNot(HaveOccurred()) g.Expect(err).ToNot(HaveOccurred())
@ -253,7 +248,6 @@ entries:
// Rebuild with a new path. // Rebuild with a new path.
targetPath2 := filepath.Join(tmpDir, "chart2.tgz") targetPath2 := filepath.Join(tmpDir, "chart2.tgz")
defer os.RemoveAll(targetPath2)
cb, err = b.Build(context.TODO(), reference, targetPath2, buildOpts) cb, err = b.Build(context.TODO(), reference, targetPath2, buildOpts)
g.Expect(err).ToNot(HaveOccurred()) g.Expect(err).ToNot(HaveOccurred())
g.Expect(cb.Path).To(Equal(targetPath)) g.Expect(cb.Path).To(Equal(targetPath))
@ -342,16 +336,13 @@ func Test_mergeChartValues(t *testing.T) {
func Test_validatePackageAndWriteToPath(t *testing.T) { func Test_validatePackageAndWriteToPath(t *testing.T) {
g := NewWithT(t) g := NewWithT(t)
tmpDir, err := os.MkdirTemp("", "validate-pkg-chart-") tmpDir := t.TempDir()
g.Expect(err).ToNot(HaveOccurred())
defer os.RemoveAll(tmpDir)
validF, err := os.Open("./../testdata/charts/helmchart-0.1.0.tgz") validF, err := os.Open("./../testdata/charts/helmchart-0.1.0.tgz")
g.Expect(err).ToNot(HaveOccurred()) g.Expect(err).ToNot(HaveOccurred())
defer validF.Close() defer validF.Close()
chartPath := filepath.Join(tmpDir, "chart.tgz") chartPath := filepath.Join(tmpDir, "chart.tgz")
defer os.Remove(chartPath)
err = validatePackageAndWriteToPath(validF, chartPath) err = validatePackageAndWriteToPath(validF, chartPath)
g.Expect(err).ToNot(HaveOccurred()) g.Expect(err).ToNot(HaveOccurred())
g.Expect(chartPath).To(BeARegularFile()) g.Expect(chartPath).To(BeARegularFile())

View File

@ -134,9 +134,7 @@ func TestLoadChartMetadataFromDir(t *testing.T) {
g := NewWithT(t) g := NewWithT(t)
// Create a chart file that exceeds the max chart file size. // Create a chart file that exceeds the max chart file size.
tmpDir, err := os.MkdirTemp("", "load-chart-") tmpDir := t.TempDir()
g.Expect(err).ToNot(HaveOccurred())
defer os.RemoveAll(tmpDir)
copy.Copy("../testdata/charts/helmchart", tmpDir) copy.Copy("../testdata/charts/helmchart", tmpDir)
bigRequirementsFile := filepath.Join(tmpDir, "requirements.yaml") bigRequirementsFile := filepath.Join(tmpDir, "requirements.yaml")
data := make([]byte, helm.MaxChartFileSize+10) data := make([]byte, helm.MaxChartFileSize+10)
@ -200,9 +198,7 @@ func TestLoadChartMetadataFromArchive(t *testing.T) {
g := NewWithT(t) g := NewWithT(t)
// Create a chart archive that exceeds the max chart size. // Create a chart archive that exceeds the max chart size.
tmpDir, err := os.MkdirTemp("", "load-chart-") tmpDir := t.TempDir()
g.Expect(err).ToNot(HaveOccurred())
defer os.RemoveAll(tmpDir)
bigArchiveFile := filepath.Join(tmpDir, "chart.tgz") bigArchiveFile := filepath.Join(tmpDir, "chart.tgz")
data := make([]byte, helm.MaxChartSize+10) data := make([]byte, helm.MaxChartSize+10)
g.Expect(os.WriteFile(bigArchiveFile, data, 0o640)).ToNot(HaveOccurred()) g.Expect(os.WriteFile(bigArchiveFile, data, 0o640)).ToNot(HaveOccurred())

View File

@ -358,9 +358,7 @@ func TestChartRepository_LoadIndexFromFile(t *testing.T) {
g := NewWithT(t) g := NewWithT(t)
// Create an index file that exceeds the max index size. // Create an index file that exceeds the max index size.
tmpDir, err := os.MkdirTemp("", "load-index-") tmpDir := t.TempDir()
g.Expect(err).ToNot(HaveOccurred())
defer os.RemoveAll(tmpDir)
bigIndexFile := filepath.Join(tmpDir, "index.yaml") bigIndexFile := filepath.Join(tmpDir, "index.yaml")
data := make([]byte, helm.MaxIndexSize+10) data := make([]byte, helm.MaxIndexSize+10)
g.Expect(os.WriteFile(bigIndexFile, data, 0o640)).ToNot(HaveOccurred()) g.Expect(os.WriteFile(bigIndexFile, data, 0o640)).ToNot(HaveOccurred())

View File

@ -202,9 +202,7 @@ func TestVisitObjectsCallbackErr(t *testing.T) {
} }
func TestFGetObject(t *testing.T) { func TestFGetObject(t *testing.T) {
tempDir, err := os.MkdirTemp("", bucketName) tempDir := t.TempDir()
assert.NilError(t, err)
defer os.RemoveAll(tempDir)
gcpClient := &GCSClient{ gcpClient := &GCSClient{
Client: client, Client: client,
} }
@ -218,9 +216,7 @@ func TestFGetObject(t *testing.T) {
func TestFGetObjectNotExists(t *testing.T) { func TestFGetObjectNotExists(t *testing.T) {
object := "notexists.txt" object := "notexists.txt"
tempDir, err := os.MkdirTemp("", bucketName) tempDir := t.TempDir()
assert.NilError(t, err)
defer os.RemoveAll(tempDir)
gcsClient := &GCSClient{ gcsClient := &GCSClient{
Client: client, Client: client,
} }
@ -233,9 +229,7 @@ func TestFGetObjectNotExists(t *testing.T) {
} }
func TestFGetObjectDirectoryIsFileName(t *testing.T) { func TestFGetObjectDirectoryIsFileName(t *testing.T) {
tempDir, err := os.MkdirTemp("", bucketName) tempDir := t.TempDir()
assert.NilError(t, err)
defer os.RemoveAll(tempDir)
gcpClient := &GCSClient{ gcpClient := &GCSClient{
Client: client, Client: client,
} }

View File

@ -35,11 +35,10 @@ import (
) )
func TestCheckoutBranch_Checkout(t *testing.T) { func TestCheckoutBranch_Checkout(t *testing.T) {
repo, path, err := initRepo() repo, path, err := initRepo(t)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
defer os.RemoveAll(path)
firstCommit, err := commitFile(repo, "branch", "init", time.Now()) firstCommit, err := commitFile(repo, "branch", "init", time.Now())
if err != nil { if err != nil {
@ -88,8 +87,7 @@ func TestCheckoutBranch_Checkout(t *testing.T) {
branch := CheckoutBranch{ branch := CheckoutBranch{
Branch: tt.branch, Branch: tt.branch,
} }
tmpDir, _ := os.MkdirTemp("", "test") tmpDir := t.TempDir()
defer os.RemoveAll(tmpDir)
cc, err := branch.Checkout(context.TODO(), tmpDir, path, nil) cc, err := branch.Checkout(context.TODO(), tmpDir, path, nil)
if tt.expectedErr != "" { if tt.expectedErr != "" {
@ -142,11 +140,10 @@ func TestCheckoutTag_Checkout(t *testing.T) {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
g := NewWithT(t) g := NewWithT(t)
repo, path, err := initRepo() repo, path, err := initRepo(t)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
defer os.RemoveAll(path)
var h plumbing.Hash var h plumbing.Hash
if tt.tag != "" { if tt.tag != "" {
@ -163,8 +160,7 @@ func TestCheckoutTag_Checkout(t *testing.T) {
tag := CheckoutTag{ tag := CheckoutTag{
Tag: tt.checkoutTag, Tag: tt.checkoutTag,
} }
tmpDir, _ := os.MkdirTemp("", "test") tmpDir := t.TempDir()
defer os.RemoveAll(tmpDir)
cc, err := tag.Checkout(context.TODO(), tmpDir, path, nil) cc, err := tag.Checkout(context.TODO(), tmpDir, path, nil)
if tt.expectErr != "" { if tt.expectErr != "" {
@ -182,11 +178,10 @@ func TestCheckoutTag_Checkout(t *testing.T) {
} }
func TestCheckoutCommit_Checkout(t *testing.T) { func TestCheckoutCommit_Checkout(t *testing.T) {
repo, path, err := initRepo() repo, path, err := initRepo(t)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
defer os.RemoveAll(path)
firstCommit, err := commitFile(repo, "commit", "init", time.Now()) firstCommit, err := commitFile(repo, "commit", "init", time.Now())
if err != nil { if err != nil {
@ -242,11 +237,7 @@ func TestCheckoutCommit_Checkout(t *testing.T) {
Branch: tt.branch, Branch: tt.branch,
} }
tmpDir, err := os.MkdirTemp("", "git2go") tmpDir := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpDir)
cc, err := commit.Checkout(context.TODO(), tmpDir, path, nil) cc, err := commit.Checkout(context.TODO(), tmpDir, path, nil)
if tt.expectError != "" { 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 { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
defer os.RemoveAll(path)
refs := make(map[string]string, len(tags)) refs := make(map[string]string, len(tags))
for _, tt := range tags { for _, tt := range tags {
@ -352,8 +342,7 @@ func TestCheckoutTagSemVer_Checkout(t *testing.T) {
semVer := CheckoutSemVer{ semVer := CheckoutSemVer{
SemVer: tt.constraint, SemVer: tt.constraint,
} }
tmpDir, _ := os.MkdirTemp("", "test") tmpDir := t.TempDir()
defer os.RemoveAll(tmpDir)
cc, err := semVer.Checkout(context.TODO(), tmpDir, path, nil) cc, err := semVer.Checkout(context.TODO(), tmpDir, path, nil)
if tt.expectErr != nil { if tt.expectErr != nil {
@ -370,16 +359,11 @@ func TestCheckoutTagSemVer_Checkout(t *testing.T) {
} }
} }
func initRepo() (*extgogit.Repository, string, error) { func initRepo(t *testing.T) (*extgogit.Repository, string, error) {
tmpDir, err := os.MkdirTemp("", "gogit") tmpDir := t.TempDir()
if err != nil {
os.RemoveAll(tmpDir)
return nil, "", err
}
sto := filesystem.NewStorage(osfs.New(tmpDir), cache.NewObjectLRUDefault()) sto := filesystem.NewStorage(osfs.New(tmpDir), cache.NewObjectLRUDefault())
repo, err := extgogit.Init(sto, memfs.New()) repo, err := extgogit.Init(sto, memfs.New())
if err != nil { if err != nil {
os.RemoveAll(tmpDir)
return nil, "", err return nil, "", err
} }
return repo, tmpDir, err return repo, tmpDir, err

View File

@ -37,12 +37,11 @@ import (
) )
func TestCheckoutBranch_Checkout(t *testing.T) { func TestCheckoutBranch_Checkout(t *testing.T) {
repo, err := initBareRepo() repo, err := initBareRepo(t)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
defer repo.Free() defer repo.Free()
defer os.RemoveAll(filepath.Join(repo.Path(), ".."))
cfg, err := git2go.OpenDefault() cfg, err := git2go.OpenDefault()
if err != nil { if err != nil {
@ -105,8 +104,7 @@ func TestCheckoutBranch_Checkout(t *testing.T) {
branch := CheckoutBranch{ branch := CheckoutBranch{
Branch: tt.branch, Branch: tt.branch,
} }
tmpDir, _ := os.MkdirTemp("", "test") tmpDir := t.TempDir()
defer os.RemoveAll(tmpDir)
cc, err := branch.Checkout(context.TODO(), tmpDir, repo.Path(), nil) cc, err := branch.Checkout(context.TODO(), tmpDir, repo.Path(), nil)
if tt.expectedErr != "" { if tt.expectedErr != "" {
@ -158,12 +156,11 @@ func TestCheckoutTag_Checkout(t *testing.T) {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
g := NewWithT(t) g := NewWithT(t)
repo, err := initBareRepo() repo, err := initBareRepo(t)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
defer repo.Free() defer repo.Free()
defer os.RemoveAll(filepath.Join(repo.Path(), ".."))
var commit *git2go.Commit var commit *git2go.Commit
if tt.tag != "" { if tt.tag != "" {
@ -183,8 +180,7 @@ func TestCheckoutTag_Checkout(t *testing.T) {
tag := CheckoutTag{ tag := CheckoutTag{
Tag: tt.checkoutTag, Tag: tt.checkoutTag,
} }
tmpDir, _ := os.MkdirTemp("", "test") tmpDir := t.TempDir()
defer os.RemoveAll(tmpDir)
cc, err := tag.Checkout(context.TODO(), tmpDir, repo.Path(), nil) cc, err := tag.Checkout(context.TODO(), tmpDir, repo.Path(), nil)
if tt.expectErr != "" { if tt.expectErr != "" {
@ -205,12 +201,11 @@ func TestCheckoutTag_Checkout(t *testing.T) {
func TestCheckoutCommit_Checkout(t *testing.T) { func TestCheckoutCommit_Checkout(t *testing.T) {
g := NewWithT(t) g := NewWithT(t)
repo, err := initBareRepo() repo, err := initBareRepo(t)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
defer repo.Free() defer repo.Free()
defer os.RemoveAll(filepath.Join(repo.Path(), ".."))
c, err := commitFile(repo, "commit", "init", time.Now()) c, err := commitFile(repo, "commit", "init", time.Now())
if err != nil { if err != nil {
@ -223,11 +218,7 @@ func TestCheckoutCommit_Checkout(t *testing.T) {
commit := CheckoutCommit{ commit := CheckoutCommit{
Commit: c.String(), Commit: c.String(),
} }
tmpDir, err := os.MkdirTemp("", "git2go") tmpDir := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpDir)
cc, err := commit.Checkout(context.TODO(), tmpDir, repo.Path(), nil) cc, err := commit.Checkout(context.TODO(), tmpDir, repo.Path(), nil)
g.Expect(err).ToNot(HaveOccurred()) g.Expect(err).ToNot(HaveOccurred())
@ -239,11 +230,7 @@ func TestCheckoutCommit_Checkout(t *testing.T) {
commit = CheckoutCommit{ commit = CheckoutCommit{
Commit: "4dc3185c5fc94eb75048376edeb44571cece25f4", Commit: "4dc3185c5fc94eb75048376edeb44571cece25f4",
} }
tmpDir2, err := os.MkdirTemp("", "git2go") tmpDir2 := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpDir2)
cc, err = commit.Checkout(context.TODO(), tmpDir2, repo.Path(), nil) cc, err = commit.Checkout(context.TODO(), tmpDir2, repo.Path(), nil)
g.Expect(err).To(HaveOccurred()) 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 { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
defer repo.Free() defer repo.Free()
defer os.RemoveAll(filepath.Join(repo.Path(), ".."))
refs := make(map[string]string, len(tags)) refs := make(map[string]string, len(tags))
for _, tt := range tags { for _, tt := range tags {
@ -349,8 +335,7 @@ func TestCheckoutTagSemVer_Checkout(t *testing.T) {
semVer := CheckoutSemVer{ semVer := CheckoutSemVer{
SemVer: tt.constraint, SemVer: tt.constraint,
} }
tmpDir, _ := os.MkdirTemp("", "test") tmpDir := t.TempDir()
defer os.RemoveAll(tmpDir)
cc, err := semVer.Checkout(context.TODO(), tmpDir, repo.Path(), nil) cc, err := semVer.Checkout(context.TODO(), tmpDir, repo.Path(), nil)
if tt.expectErr != nil { if tt.expectErr != nil {
@ -367,14 +352,10 @@ func TestCheckoutTagSemVer_Checkout(t *testing.T) {
} }
} }
func initBareRepo() (*git2go.Repository, error) { func initBareRepo(t *testing.T) (*git2go.Repository, error) {
tmpDir, err := os.MkdirTemp("", "git2go-") tmpDir := t.TempDir()
if err != nil {
return nil, err
}
repo, err := git2go.InitRepository(tmpDir, false) repo, err := git2go.InitRepository(tmpDir, false)
if err != nil { if err != nil {
_ = os.RemoveAll(tmpDir)
return nil, err return nil, err
} }
return repo, nil return repo, nil
@ -514,8 +495,7 @@ func TestCheckout_ED25519(t *testing.T) {
// Prepare for checkout. // Prepare for checkout.
branchCheckoutStrat := &CheckoutBranch{Branch: git.DefaultBranch} branchCheckoutStrat := &CheckoutBranch{Branch: git.DefaultBranch}
tmpDir, _ := os.MkdirTemp("", "test") tmpDir := t.TempDir()
defer os.RemoveAll(tmpDir)
ctx, cancel := context.WithTimeout(context.TODO(), timeout) ctx, cancel := context.WithTimeout(context.TODO(), timeout)
defer cancel() defer cancel()

View File

@ -258,8 +258,7 @@ func TestManagedTransport_E2E(t *testing.T) {
err = server.InitRepo("../testdata/git/repo", git.DefaultBranch, repoPath) err = server.InitRepo("../testdata/git/repo", git.DefaultBranch, repoPath)
g.Expect(err).ToNot(HaveOccurred()) g.Expect(err).ToNot(HaveOccurred())
tmpDir, _ := os.MkdirTemp("", "test") tmpDir := t.TempDir()
defer os.RemoveAll(tmpDir)
// Test HTTP transport // Test HTTP transport
@ -285,8 +284,7 @@ func TestManagedTransport_E2E(t *testing.T) {
g.Expect(err).ToNot(HaveOccurred()) g.Expect(err).ToNot(HaveOccurred())
repo.Free() repo.Free()
tmpDir2, _ := os.MkdirTemp("", "test") tmpDir2 := t.TempDir()
defer os.RemoveAll(tmpDir2)
kp, err := ssh.NewEd25519Generator().Generate() kp, err := ssh.NewEd25519Generator().Generate()
g.Expect(err).ToNot(HaveOccurred()) g.Expect(err).ToNot(HaveOccurred())
@ -313,8 +311,7 @@ func TestManagedTransport_E2E(t *testing.T) {
func TestManagedTransport_HandleRedirect(t *testing.T) { func TestManagedTransport_HandleRedirect(t *testing.T) {
g := NewWithT(t) g := NewWithT(t)
tmpDir, _ := os.MkdirTemp("", "test") tmpDir := t.TempDir()
defer os.RemoveAll(tmpDir)
// Force managed transport to be enabled // Force managed transport to be enabled
InitManagedTransport(logr.Discard()) InitManagedTransport(logr.Discard())

View File

@ -264,9 +264,7 @@ func TestCheckoutStrategyForImplementation_Proxied(t *testing.T) {
}) })
g.Expect(err).ToNot(HaveOccurred()) g.Expect(err).ToNot(HaveOccurred())
tmpDir, err := os.MkdirTemp("", "test-checkout") tmpDir := t.TempDir()
g.Expect(err).ToNot(HaveOccurred())
defer os.RemoveAll(tmpDir)
// for the NO_PROXY test we dont want to wait the 30s for it to timeout/fail, so shorten the timeout // for the NO_PROXY test we dont want to wait the 30s for it to timeout/fail, so shorten the timeout
checkoutCtx := context.TODO() checkoutCtx := context.TODO()

View File

@ -180,9 +180,7 @@ func TestCheckoutStrategyForImplementation_Auth(t *testing.T) {
checkoutStrategy, err := CheckoutStrategyForImplementation(context.TODO(), impl, checkoutOpts) checkoutStrategy, err := CheckoutStrategyForImplementation(context.TODO(), impl, checkoutOpts)
g.Expect(err).ToNot(HaveOccurred()) g.Expect(err).ToNot(HaveOccurred())
tmpDir, err := os.MkdirTemp("", "test-checkout") tmpDir := t.TempDir()
g.Expect(err).ToNot(HaveOccurred())
defer os.RemoveAll(tmpDir)
tt.wantFunc(g, checkoutStrategy, tmpDir, repoURL, authOpts) tt.wantFunc(g, checkoutStrategy, tmpDir, repoURL, authOpts)
} }
@ -271,9 +269,7 @@ func TestCheckoutStrategyForImplementation_SemVerCheckout(t *testing.T) {
} }
// Clone the repo locally. // Clone the repo locally.
cloneDir, err := os.MkdirTemp("", "test-clone") cloneDir := t.TempDir()
g.Expect(err).ToNot(HaveOccurred())
defer os.RemoveAll(cloneDir)
repo, err := extgogit.PlainClone(cloneDir, false, &extgogit.CloneOptions{ repo, err := extgogit.PlainClone(cloneDir, false, &extgogit.CloneOptions{
URL: repoURL, URL: repoURL,
}) })
@ -332,9 +328,7 @@ func TestCheckoutStrategyForImplementation_SemVerCheckout(t *testing.T) {
g.Expect(err).ToNot(HaveOccurred()) g.Expect(err).ToNot(HaveOccurred())
// Checkout and verify. // Checkout and verify.
tmpDir, err := os.MkdirTemp("", "test-checkout") tmpDir := t.TempDir()
g.Expect(err).ToNot(HaveOccurred())
defer os.RemoveAll(tmpDir)
cc, err := checkoutStrategy.Checkout(context.TODO(), tmpDir, repoURL, authOpts) cc, err := checkoutStrategy.Checkout(context.TODO(), tmpDir, repoURL, authOpts)
if tt.expectErr != nil { if tt.expectErr != nil {
@ -425,9 +419,7 @@ func TestCheckoutStrategyForImplementation_WithCtxTimeout(t *testing.T) {
checkoutStrategy, err := CheckoutStrategyForImplementation(context.TODO(), impl, checkoutOpts) checkoutStrategy, err := CheckoutStrategyForImplementation(context.TODO(), impl, checkoutOpts)
g.Expect(err).ToNot(HaveOccurred()) g.Expect(err).ToNot(HaveOccurred())
tmpDir, err := os.MkdirTemp("", "test-checkout") tmpDir := t.TempDir()
g.Expect(err).ToNot(HaveOccurred())
defer os.RemoveAll(tmpDir)
checkoutCtx, cancel := context.WithTimeout(context.TODO(), tt.timeout) checkoutCtx, cancel := context.WithTimeout(context.TODO(), tt.timeout)
defer cancel() defer cancel()

View File

@ -144,22 +144,18 @@ func TestBucketNotExists(t *testing.T) {
func TestFGetObject(t *testing.T) { func TestFGetObject(t *testing.T) {
ctx := context.Background() ctx := context.Background()
tempDir, err := os.MkdirTemp("", bucketName) tempDir := t.TempDir()
assert.NilError(t, err)
defer os.RemoveAll(tempDir)
path := filepath.Join(tempDir, sourceignore.IgnoreFile) path := filepath.Join(tempDir, sourceignore.IgnoreFile)
_, err = minioClient.FGetObject(ctx, bucketName, objectName, path) _, err := minioClient.FGetObject(ctx, bucketName, objectName, path)
assert.NilError(t, err) assert.NilError(t, err)
} }
func TestFGetObjectNotExists(t *testing.T) { func TestFGetObjectNotExists(t *testing.T) {
ctx := context.Background() ctx := context.Background()
tempDir, err := os.MkdirTemp("", bucketName) tempDir := t.TempDir()
assert.NilError(t, err)
defer os.RemoveAll(tempDir)
badKey := "invalid.txt" badKey := "invalid.txt"
path := filepath.Join(tempDir, badKey) 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.Error(t, err, "The specified key does not exist.")
assert.Check(t, minioClient.ObjectIsNotFound(err)) assert.Check(t, minioClient.ObjectIsNotFound(err))
} }

View File

@ -197,11 +197,7 @@ func TestDefaultPatterns(t *testing.T) {
} }
func TestLoadExcludePatterns(t *testing.T) { func TestLoadExcludePatterns(t *testing.T) {
tmpDir, err := os.MkdirTemp("", "sourceignore-load-") tmpDir := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpDir)
files := map[string]string{ files := map[string]string{
".sourceignore": "root.txt", ".sourceignore": "root.txt",
"d/.gitignore": "ignored", "d/.gitignore": "ignored",
@ -209,10 +205,10 @@ func TestLoadExcludePatterns(t *testing.T) {
"a/b/.sourceignore": "subdir.txt", "a/b/.sourceignore": "subdir.txt",
} }
for n, c := range files { 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) 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) t.Fatal(err)
} }
} }