test: use `T.TempDir` to create temporary test directory (#1918)

The directory created by `T.TempDir` is automatically removed when the
test and all its subtests complete.

Reference: https://pkg.go.dev/testing#T.TempDir
Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
This commit is contained in:
Eng Zer Jun 2022-02-08 02:27:34 +08:00 committed by GitHub
parent 268ee26f4e
commit 0adbbee21d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 81 additions and 265 deletions

View File

@ -52,11 +52,8 @@ var copyTests = []struct {
}, },
} }
func setupTestTemp() string { func setupTestTemp(t *testing.T) string {
tempDir, err := ioutil.TempDir("", "") tempDir := t.TempDir()
if err != nil {
logrus.Fatalf("error creating temp dir %s", err)
}
logrus.Debugf("Tempdir: %s", tempDir) logrus.Debugf("Tempdir: %s", tempDir)
srcPath, err := filepath.Abs("../../integration/context") srcPath, err := filepath.Abs("../../integration/context")
@ -108,9 +105,9 @@ func setupTestTemp() string {
} }
func Test_CachingCopyCommand_ExecuteCommand(t *testing.T) { func Test_CachingCopyCommand_ExecuteCommand(t *testing.T) {
tempDir := setupTestTemp() tempDir := setupTestTemp(t)
tarContent, err := prepareTarFixture([]string{"foo.txt"}) tarContent, err := prepareTarFixture(t, []string{"foo.txt"})
if err != nil { if err != nil {
t.Errorf("couldn't prepare tar fixture %v", err) t.Errorf("couldn't prepare tar fixture %v", err)
} }
@ -261,8 +258,7 @@ func Test_CachingCopyCommand_ExecuteCommand(t *testing.T) {
} }
func TestCopyExecuteCmd(t *testing.T) { func TestCopyExecuteCmd(t *testing.T) {
tempDir := setupTestTemp() tempDir := setupTestTemp(t)
defer os.RemoveAll(tempDir)
cfg := &v1.Config{ cfg := &v1.Config{
Cmd: nil, Cmd: nil,
@ -336,10 +332,7 @@ func Test_resolveIfSymlink(t *testing.T) {
err error err error
} }
tmpDir, err := ioutil.TempDir("", "copy-test") tmpDir := t.TempDir()
if err != nil {
t.Error(err)
}
baseDir, err := ioutil.TempDir(tmpDir, "not-linked") baseDir, err := ioutil.TempDir(tmpDir, "not-linked")
if err != nil { if err != nil {
@ -394,10 +387,7 @@ func Test_resolveIfSymlink(t *testing.T) {
func TestCopyCommand_ExecuteCommand_Extended(t *testing.T) { func TestCopyCommand_ExecuteCommand_Extended(t *testing.T) {
setupDirs := func(t *testing.T) (string, string) { setupDirs := func(t *testing.T) (string, string) {
testDir, err := ioutil.TempDir("", "") testDir := t.TempDir()
if err != nil {
t.Fatal(err)
}
dir := filepath.Join(testDir, "bar") dir := filepath.Join(testDir, "bar")

View File

@ -125,11 +125,8 @@ func Test_addDefaultHOME(t *testing.T) {
} }
} }
func prepareTarFixture(fileNames []string) ([]byte, error) { func prepareTarFixture(t *testing.T, fileNames []string) ([]byte, error) {
dir, err := ioutil.TempDir("/tmp", "tar-fixture") dir := t.TempDir()
if err != nil {
return nil, err
}
content := ` content := `
Meow meow meow meow Meow meow meow meow
@ -174,7 +171,7 @@ meow meow meow meow
} }
func Test_CachingRunCommand_ExecuteCommand(t *testing.T) { func Test_CachingRunCommand_ExecuteCommand(t *testing.T) {
tarContent, err := prepareTarFixture([]string{"foo.txt"}) tarContent, err := prepareTarFixture(t, []string{"foo.txt"})
if err != nil { if err != nil {
t.Errorf("couldn't prepare tar fixture %v", err) t.Errorf("couldn't prepare tar fixture %v", err)
} }
@ -318,10 +315,7 @@ func Test_CachingRunCommand_ExecuteCommand(t *testing.T) {
} }
func TestSetWorkDirIfExists(t *testing.T) { func TestSetWorkDirIfExists(t *testing.T) {
testDir, err := ioutil.TempDir("", "workdir") testDir := t.TempDir()
if err != nil {
t.Error(err)
}
testutil.CheckDeepEqual(t, testDir, setWorkDirIfExists(testDir)) testutil.CheckDeepEqual(t, testDir, setWorkDirIfExists(testDir))
testutil.CheckDeepEqual(t, "", setWorkDirIfExists("doesnot-exists")) testutil.CheckDeepEqual(t, "", setWorkDirIfExists("doesnot-exists"))
} }

View File

@ -430,15 +430,11 @@ func Test_filesToSave(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) {
tmpDir, err := ioutil.TempDir("", "") tmpDir := t.TempDir()
original := config.RootDir original := config.RootDir
config.RootDir = tmpDir config.RootDir = tmpDir
if err != nil {
t.Errorf("error creating tmpdir: %s", err)
}
defer func() { defer func() {
config.RootDir = original config.RootDir = original
os.RemoveAll(tmpDir)
}() }()
for _, f := range tt.files { for _, f := range tt.files {
@ -762,10 +758,7 @@ func Test_stageBuilder_build(t *testing.T) {
}, },
} }
destDir, err := ioutil.TempDir("", "baz") destDir := t.TempDir()
if err != nil {
t.Errorf("could not create temp dir %v", err)
}
return testcase{ return testcase{
description: "fake command cache enabled but key not in cache", description: "fake command cache enabled but key not in cache",
config: &v1.ConfigFile{Config: v1.Config{WorkingDir: destDir}}, config: &v1.ConfigFile{Config: v1.Config{WorkingDir: destDir}},
@ -795,10 +788,7 @@ func Test_stageBuilder_build(t *testing.T) {
}, },
} }
destDir, err := ioutil.TempDir("", "baz") destDir := t.TempDir()
if err != nil {
t.Errorf("could not create temp dir %v", err)
}
return testcase{ return testcase{
description: "fake command cache enabled and key in cache", description: "fake command cache enabled and key in cache",
opts: &config.KanikoOptions{Cache: true}, opts: &config.KanikoOptions{Cache: true},
@ -831,10 +821,7 @@ func Test_stageBuilder_build(t *testing.T) {
}, },
} }
destDir, err := ioutil.TempDir("", "baz") destDir := t.TempDir()
if err != nil {
t.Errorf("could not create temp dir %v", err)
}
return testcase{ return testcase{
description: "fake command cache enabled with tar compression disabled and key in cache", description: "fake command cache enabled with tar compression disabled and key in cache",
opts: &config.KanikoOptions{Cache: true, CompressedCaching: false}, opts: &config.KanikoOptions{Cache: true, CompressedCaching: false},
@ -932,10 +919,7 @@ COPY %s foo.txt
dir, filenames := tempDirAndFile(t) dir, filenames := tempDirAndFile(t)
filename := filenames[0] filename := filenames[0]
tarContent := []byte{} tarContent := []byte{}
destDir, err := ioutil.TempDir("", "baz") destDir := t.TempDir()
if err != nil {
t.Errorf("could not create temp dir %v", err)
}
filePath := filepath.Join(dir, filename) filePath := filepath.Join(dir, filename)
ch := NewCompositeCache("", fmt.Sprintf("COPY %s foo.txt", filename)) ch := NewCompositeCache("", fmt.Sprintf("COPY %s foo.txt", filename))
ch.AddPath(filePath, util.FileContext{}) ch.AddPath(filePath, util.FileContext{})
@ -993,10 +977,7 @@ COPY %s foo.txt
filename := filenames[0] filename := filenames[0]
tarContent := generateTar(t, filename) tarContent := generateTar(t, filename)
destDir, err := ioutil.TempDir("", "baz") destDir := t.TempDir()
if err != nil {
t.Errorf("could not create temp dir %v", err)
}
filePath := filepath.Join(dir, filename) filePath := filepath.Join(dir, filename)
ch := NewCompositeCache("", "RUN foobar") ch := NewCompositeCache("", "RUN foobar")
@ -1070,10 +1051,7 @@ COPY %s bar.txt
filename := filenames[0] filename := filenames[0]
tarContent := generateTar(t, filename) tarContent := generateTar(t, filename)
destDir, err := ioutil.TempDir("", "baz") destDir := t.TempDir()
if err != nil {
t.Errorf("could not create temp dir %v", err)
}
filePath := filepath.Join(dir, filename) filePath := filepath.Join(dir, filename)
@ -1081,7 +1059,7 @@ COPY %s bar.txt
ch.AddPath(filePath, util.FileContext{}) ch.AddPath(filePath, util.FileContext{})
// copy hash // copy hash
_, err = ch.Hash() _, err := ch.Hash()
if err != nil { if err != nil {
t.Errorf("couldn't create hash %v", err) t.Errorf("couldn't create hash %v", err)
} }
@ -1372,13 +1350,10 @@ func getCommands(fileContext util.FileContext, cmds []instructions.Command, cach
func tempDirAndFile(t *testing.T) (string, []string) { func tempDirAndFile(t *testing.T) (string, []string) {
filenames := []string{"bar.txt"} filenames := []string{"bar.txt"}
dir, err := ioutil.TempDir("", "foo") dir := t.TempDir()
if err != nil {
t.Errorf("could not create temp dir %v", err)
}
for _, filename := range filenames { for _, filename := range filenames {
filepath := filepath.Join(dir, filename) filepath := filepath.Join(dir, filename)
err = ioutil.WriteFile(filepath, []byte(`meow`), 0777) err := ioutil.WriteFile(filepath, []byte(`meow`), 0777)
if err != nil { if err != nil {
t.Errorf("could not create temp file %v", err) t.Errorf("could not create temp file %v", err)
} }

View File

@ -68,10 +68,7 @@ func Test_CompositeCache_Hash(t *testing.T) {
} }
func Test_CompositeCache_AddPath_dir(t *testing.T) { func Test_CompositeCache_AddPath_dir(t *testing.T) {
tmpDir, err := ioutil.TempDir("/tmp", "foo") tmpDir := t.TempDir()
if err != nil {
t.Errorf("got error setting up test %v", err)
}
content := `meow meow meow` content := `meow meow meow`
if err := ioutil.WriteFile(filepath.Join(tmpDir, "foo.txt"), []byte(content), 0777); err != nil { if err := ioutil.WriteFile(filepath.Join(tmpDir, "foo.txt"), []byte(content), 0777); err != nil {
@ -158,14 +155,10 @@ func createFilesystemStructure(root string, directories, files []string) error {
return nil return nil
} }
func setIgnoreContext(content string) (util.FileContext, error) { func setIgnoreContext(t *testing.T, content string) (util.FileContext, error) {
var fileContext util.FileContext var fileContext util.FileContext
dockerIgnoreDir, err := ioutil.TempDir("", "") dockerIgnoreDir := t.TempDir()
if err != nil { err := ioutil.WriteFile(dockerIgnoreDir+".dockerignore", []byte(content), 0644)
return fileContext, err
}
defer os.RemoveAll(dockerIgnoreDir)
err = ioutil.WriteFile(dockerIgnoreDir+".dockerignore", []byte(content), 0644)
if err != nil { if err != nil {
return fileContext, err return fileContext, err
} }
@ -218,21 +211,13 @@ func Test_CompositeKey_AddPath_Works(t *testing.T) {
for _, test := range tests { for _, test := range tests {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
testDir1, err := ioutil.TempDir("", "") testDir1 := t.TempDir()
if err != nil { err := createFilesystemStructure(testDir1, test.directories, test.files)
t.Fatalf("Error creating tempdir: %s", err)
}
defer os.RemoveAll(testDir1)
err = createFilesystemStructure(testDir1, test.directories, test.files)
if err != nil { if err != nil {
t.Fatalf("Error creating filesytem structure: %s", err) t.Fatalf("Error creating filesytem structure: %s", err)
} }
testDir2, err := ioutil.TempDir("", "") testDir2 := t.TempDir()
if err != nil {
t.Fatalf("Error creating tempdir: %s", err)
}
defer os.RemoveAll(testDir2)
err = createFilesystemStructure(testDir2, test.directories, test.files) err = createFilesystemStructure(testDir2, test.directories, test.files)
if err != nil { if err != nil {
t.Fatalf("Error creating filesytem structure: %s", err) t.Fatalf("Error creating filesytem structure: %s", err)
@ -291,21 +276,13 @@ func Test_CompositeKey_AddPath_WithExtraFile_Works(t *testing.T) {
for _, test := range tests { for _, test := range tests {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
testDir1, err := ioutil.TempDir("", "") testDir1 := t.TempDir()
if err != nil { err := createFilesystemStructure(testDir1, test.directories, test.files)
t.Fatalf("Error creating tempdir: %s", err)
}
defer os.RemoveAll(testDir1)
err = createFilesystemStructure(testDir1, test.directories, test.files)
if err != nil { if err != nil {
t.Fatalf("Error creating filesytem structure: %s", err) t.Fatalf("Error creating filesytem structure: %s", err)
} }
testDir2, err := ioutil.TempDir("", "") testDir2 := t.TempDir()
if err != nil {
t.Fatalf("Error creating tempdir: %s", err)
}
defer os.RemoveAll(testDir2)
err = createFilesystemStructure(testDir2, test.directories, test.files) err = createFilesystemStructure(testDir2, test.directories, test.files)
if err != nil { if err != nil {
t.Fatalf("Error creating filesytem structure: %s", err) t.Fatalf("Error creating filesytem structure: %s", err)
@ -369,21 +346,13 @@ func Test_CompositeKey_AddPath_WithExtraDir_Works(t *testing.T) {
for _, test := range tests { for _, test := range tests {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
testDir1, err := ioutil.TempDir("", "") testDir1 := t.TempDir()
if err != nil { err := createFilesystemStructure(testDir1, test.directories, test.files)
t.Fatalf("Error creating tempdir: %s", err)
}
defer os.RemoveAll(testDir1)
err = createFilesystemStructure(testDir1, test.directories, test.files)
if err != nil { if err != nil {
t.Fatalf("Error creating filesytem structure: %s", err) t.Fatalf("Error creating filesytem structure: %s", err)
} }
testDir2, err := ioutil.TempDir("", "") testDir2 := t.TempDir()
if err != nil {
t.Fatalf("Error creating tempdir: %s", err)
}
defer os.RemoveAll(testDir2)
err = createFilesystemStructure(testDir2, test.directories, test.files) err = createFilesystemStructure(testDir2, test.directories, test.files)
if err != nil { if err != nil {
t.Fatalf("Error creating filesytem structure: %s", err) t.Fatalf("Error creating filesytem structure: %s", err)
@ -443,28 +412,20 @@ func Test_CompositeKey_AddPath_WithExtraFilIgnored_Works(t *testing.T) {
}, },
} }
fileContext, err := setIgnoreContext("**/extra") fileContext, err := setIgnoreContext(t, "**/extra")
if err != nil { if err != nil {
t.Fatalf("Error setting exlusion context: %s", err) t.Fatalf("Error setting exlusion context: %s", err)
} }
for _, test := range tests { for _, test := range tests {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
testDir1, err := ioutil.TempDir("", "") testDir1 := t.TempDir()
if err != nil {
t.Fatalf("Error creating tempdir: %s", err)
}
defer os.RemoveAll(testDir1)
err = createFilesystemStructure(testDir1, test.directories, test.files) err = createFilesystemStructure(testDir1, test.directories, test.files)
if err != nil { if err != nil {
t.Fatalf("Error creating filesytem structure: %s", err) t.Fatalf("Error creating filesytem structure: %s", err)
} }
testDir2, err := ioutil.TempDir("", "") testDir2 := t.TempDir()
if err != nil {
t.Fatalf("Error creating tempdir: %s", err)
}
defer os.RemoveAll(testDir2)
err = createFilesystemStructure(testDir2, test.directories, test.files) err = createFilesystemStructure(testDir2, test.directories, test.files)
if err != nil { if err != nil {
t.Fatalf("Error creating filesytem structure: %s", err) t.Fatalf("Error creating filesytem structure: %s", err)
@ -524,28 +485,20 @@ func Test_CompositeKey_AddPath_WithExtraDirIgnored_Works(t *testing.T) {
}, },
} }
fileContext, err := setIgnoreContext("**/extra") fileContext, err := setIgnoreContext(t, "**/extra")
if err != nil { if err != nil {
t.Fatalf("Error setting exlusion context: %s", err) t.Fatalf("Error setting exlusion context: %s", err)
} }
for _, test := range tests { for _, test := range tests {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
testDir1, err := ioutil.TempDir("", "") testDir1 := t.TempDir()
if err != nil { err := createFilesystemStructure(testDir1, test.directories, test.files)
t.Fatalf("Error creating tempdir: %s", err)
}
defer os.RemoveAll(testDir1)
err = createFilesystemStructure(testDir1, test.directories, test.files)
if err != nil { if err != nil {
t.Fatalf("Error creating filesytem structure: %s", err) t.Fatalf("Error creating filesytem structure: %s", err)
} }
testDir2, err := ioutil.TempDir("", "") testDir2 := t.TempDir()
if err != nil {
t.Fatalf("Error creating tempdir: %s", err)
}
defer os.RemoveAll(testDir2)
err = createFilesystemStructure(testDir2, test.directories, test.files) err = createFilesystemStructure(testDir2, test.directories, test.files)
if err != nil { if err != nil {
t.Fatalf("Error creating filesytem structure: %s", err) t.Fatalf("Error creating filesytem structure: %s", err)

View File

@ -119,10 +119,7 @@ COPY --from=first copied another`)
} }
func setupMultistageTests(t *testing.T) (string, func()) { func setupMultistageTests(t *testing.T) (string, func()) {
testDir, err := ioutil.TempDir("", "") testDir := t.TempDir()
if err != nil {
t.Fatal(err)
}
// Create workspace with files, dirs, and symlinks // Create workspace with files, dirs, and symlinks
// workspace tree: // workspace tree:

View File

@ -150,11 +150,7 @@ func (m *mockRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) {
} }
func TestOCILayoutPath(t *testing.T) { func TestOCILayoutPath(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "") tmpDir := t.TempDir()
if err != nil {
t.Fatalf("could not create temp dir: %s", err)
}
defer os.RemoveAll(tmpDir)
image, err := random.Image(1024, 4) image, err := random.Image(1024, 4)
if err != nil { if err != nil {
@ -338,11 +334,7 @@ func TestHelperProcess(t *testing.T) {
} }
func TestWriteDigestFile(t *testing.T) { func TestWriteDigestFile(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "*") tmpDir := t.TempDir()
if err != nil {
t.Fatalf("could not create temp dir: %s", err)
}
defer os.RemoveAll(tmpDir)
t.Run("parent directory does not exist", func(t *testing.T) { t.Run("parent directory does not exist", func(t *testing.T) {
err := writeDigestFile(tmpDir+"/test/df", []byte("test")) err := writeDigestFile(tmpDir+"/test/df", []byte("test"))

View File

@ -51,12 +51,7 @@ func Test_ResolvePaths(t *testing.T) {
} }
t.Run("list of files", func(t *testing.T) { t.Run("list of files", func(t *testing.T) {
dir, err := ioutil.TempDir("", "snapshot-test") dir := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)
files := []string{ files := []string{
"/foo/bar.txt", "/foo/bar.txt",
@ -187,10 +182,7 @@ func Test_ResolvePaths(t *testing.T) {
func Test_resolveSymlinkAncestor(t *testing.T) { func Test_resolveSymlinkAncestor(t *testing.T) {
setupDirs := func(t *testing.T) (string, string) { setupDirs := func(t *testing.T) (string, string) {
testDir, err := ioutil.TempDir("", "") testDir := t.TempDir()
if err != nil {
t.Fatal(err)
}
targetDir := filepath.Join(testDir, "bar", "baz") targetDir := filepath.Join(testDir, "bar", "baz")

View File

@ -32,7 +32,7 @@ import (
) )
func TestSnapshotFSFileChange(t *testing.T) { func TestSnapshotFSFileChange(t *testing.T) {
testDir, snapshotter, cleanup, err := setUpTest() testDir, snapshotter, cleanup, err := setUpTest(t)
testDirWithoutLeadingSlash := strings.TrimLeft(testDir, "/") testDirWithoutLeadingSlash := strings.TrimLeft(testDir, "/")
defer cleanup() defer cleanup()
if err != nil { if err != nil {
@ -98,7 +98,7 @@ func TestSnapshotFSFileChange(t *testing.T) {
} }
func TestSnapshotFSIsReproducible(t *testing.T) { func TestSnapshotFSIsReproducible(t *testing.T) {
testDir, snapshotter, cleanup, err := setUpTest() testDir, snapshotter, cleanup, err := setUpTest(t)
defer cleanup() defer cleanup()
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@ -137,7 +137,7 @@ func TestSnapshotFSIsReproducible(t *testing.T) {
} }
func TestSnapshotFSChangePermissions(t *testing.T) { func TestSnapshotFSChangePermissions(t *testing.T) {
testDir, snapshotter, cleanup, err := setUpTest() testDir, snapshotter, cleanup, err := setUpTest(t)
testDirWithoutLeadingSlash := strings.TrimLeft(testDir, "/") testDirWithoutLeadingSlash := strings.TrimLeft(testDir, "/")
defer cleanup() defer cleanup()
if err != nil { if err != nil {
@ -198,7 +198,7 @@ func TestSnapshotFSChangePermissions(t *testing.T) {
} }
func TestSnapshotFiles(t *testing.T) { func TestSnapshotFiles(t *testing.T) {
testDir, snapshotter, cleanup, err := setUpTest() testDir, snapshotter, cleanup, err := setUpTest(t)
testDirWithoutLeadingSlash := strings.TrimLeft(testDir, "/") testDirWithoutLeadingSlash := strings.TrimLeft(testDir, "/")
defer cleanup() defer cleanup()
if err != nil { if err != nil {
@ -250,7 +250,7 @@ func TestSnapshotFiles(t *testing.T) {
} }
func TestEmptySnapshotFS(t *testing.T) { func TestEmptySnapshotFS(t *testing.T) {
_, snapshotter, cleanup, err := setUpTest() _, snapshotter, cleanup, err := setUpTest(t)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -305,11 +305,10 @@ func TestFileWithLinks(t *testing.T) {
for _, tt := range tcs { for _, tt := range tcs {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
testDir, cleanup, err := setUpTestDir() testDir, err := setUpTestDir(t)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
defer cleanup()
if err := setupSymlink(testDir, link, tt.linkFileTarget); err != nil { if err := setupSymlink(testDir, link, tt.linkFileTarget); err != nil {
t.Fatalf("could not set up symlink due to %s", err) t.Fatalf("could not set up symlink due to %s", err)
} }
@ -343,7 +342,7 @@ func TestSnasphotPreservesFileOrder(t *testing.T) {
filesInTars := [][]string{} filesInTars := [][]string{}
for i := 0; i <= 2; i++ { for i := 0; i <= 2; i++ {
testDir, snapshotter, cleanup, err := setUpTest() testDir, snapshotter, cleanup, err := setUpTest(t)
testDirWithoutLeadingSlash := strings.TrimLeft(testDir, "/") testDirWithoutLeadingSlash := strings.TrimLeft(testDir, "/")
defer cleanup() defer cleanup()
@ -392,7 +391,7 @@ func TestSnasphotPreservesFileOrder(t *testing.T) {
} }
func TestSnapshotWithForceBuildMetadataSet(t *testing.T) { func TestSnapshotWithForceBuildMetadataSet(t *testing.T) {
_, snapshotter, cleanup, err := setUpTest() _, snapshotter, cleanup, err := setUpTest(t)
defer cleanup() defer cleanup()
if err != nil { if err != nil {
@ -412,7 +411,7 @@ func TestSnapshotWithForceBuildMetadataSet(t *testing.T) {
} }
func TestSnapshotWithForceBuildMetadataIsNotSet(t *testing.T) { func TestSnapshotWithForceBuildMetadataIsNotSet(t *testing.T) {
_, snapshotter, cleanup, err := setUpTest() _, snapshotter, cleanup, err := setUpTest(t)
defer cleanup() defer cleanup()
if err != nil { if err != nil {
@ -452,7 +451,7 @@ func TestSnasphotPreservesWhiteoutOrder(t *testing.T) {
filesInTars := [][]string{} filesInTars := [][]string{}
for i := 0; i <= 2; i++ { for i := 0; i <= 2; i++ {
testDir, snapshotter, cleanup, err := setUpTest() testDir, snapshotter, cleanup, err := setUpTest(t)
testDirWithoutLeadingSlash := strings.TrimLeft(testDir, "/") testDirWithoutLeadingSlash := strings.TrimLeft(testDir, "/")
defer cleanup() defer cleanup()
@ -514,7 +513,7 @@ func TestSnasphotPreservesWhiteoutOrder(t *testing.T) {
} }
func TestSnapshotOmitsUnameGname(t *testing.T) { func TestSnapshotOmitsUnameGname(t *testing.T) {
_, snapshotter, cleanup, err := setUpTest() _, snapshotter, cleanup, err := setUpTest(t)
defer cleanup() defer cleanup()
if err != nil { if err != nil {
@ -560,11 +559,8 @@ func sortAndCompareFilepaths(t *testing.T, testDir string, expected []string, ac
testutil.CheckDeepEqual(t, expectedFullPaths, actual) testutil.CheckDeepEqual(t, expectedFullPaths, actual)
} }
func setUpTestDir() (string, func(), error) { func setUpTestDir(t *testing.T) (string, error) {
testDir, err := ioutil.TempDir("", "") testDir := t.TempDir()
if err != nil {
return "", nil, errors.Wrap(err, "setting up temp dir")
}
files := map[string]string{ files := map[string]string{
"foo": "baz1", "foo": "baz1",
"bar/bat": "baz2", "bar/bat": "baz2",
@ -573,26 +569,19 @@ func setUpTestDir() (string, func(), error) {
} }
// Set up initial files // Set up initial files
if err := testutil.SetupFiles(testDir, files); err != nil { if err := testutil.SetupFiles(testDir, files); err != nil {
return "", nil, errors.Wrap(err, "setting up file system") return "", errors.Wrap(err, "setting up file system")
} }
cleanup := func() { return testDir, nil
os.RemoveAll(testDir)
}
return testDir, cleanup, nil
} }
func setUpTest() (string, *Snapshotter, func(), error) { func setUpTest(t *testing.T) (string, *Snapshotter, func(), error) {
testDir, dirCleanUp, err := setUpTestDir() testDir, err := setUpTestDir(t)
if err != nil { if err != nil {
return "", nil, nil, err return "", nil, nil, err
} }
snapshotPath, err := ioutil.TempDir("", "")
if err != nil {
return "", nil, nil, errors.Wrap(err, "setting up temp dir")
}
snapshotPath := t.TempDir()
snapshotPathPrefix = snapshotPath snapshotPathPrefix = snapshotPath
// Take the initial snapshot // Take the initial snapshot
@ -605,9 +594,7 @@ func setUpTest() (string, *Snapshotter, func(), error) {
original := config.KanikoDir original := config.KanikoDir
config.KanikoDir = testDir config.KanikoDir = testDir
cleanup := func() { cleanup := func() {
os.RemoveAll(snapshotPath)
config.KanikoDir = original config.KanikoDir = original
dirCleanUp()
} }
return testDir, snapshotter, cleanup, nil return testDir, snapshotter, cleanup, nil

View File

@ -40,10 +40,7 @@ import (
) )
func Test_DetectFilesystemSkiplist(t *testing.T) { func Test_DetectFilesystemSkiplist(t *testing.T) {
testDir, err := ioutil.TempDir("", "") testDir := t.TempDir()
if err != nil {
t.Fatalf("Error creating tempdir: %s", err)
}
fileContents := ` fileContents := `
228 122 0:90 / / rw,relatime - aufs none rw,si=f8e2406af90782bc,dio,dirperm1 228 122 0:90 / / rw,relatime - aufs none rw,si=f8e2406af90782bc,dio,dirperm1
229 228 0:98 / /proc rw,nosuid,nodev,noexec,relatime - proc proc rw 229 228 0:98 / /proc rw,nosuid,nodev,noexec,relatime - proc proc rw
@ -59,7 +56,7 @@ func Test_DetectFilesystemSkiplist(t *testing.T) {
t.Fatalf("Error writing file contents to %s: %s", path, err) t.Fatalf("Error writing file contents to %s: %s", path, err)
} }
err = DetectFilesystemIgnoreList(path) err := DetectFilesystemIgnoreList(path)
expectedSkiplist := []IgnoreListEntry{ expectedSkiplist := []IgnoreListEntry{
{"/kaniko", false}, {"/kaniko", false},
{"/proc", false}, {"/proc", false},
@ -155,11 +152,7 @@ var tests = []struct {
func Test_RelativeFiles(t *testing.T) { func Test_RelativeFiles(t *testing.T) {
for _, test := range tests { for _, test := range tests {
testDir, err := ioutil.TempDir("", "") testDir := t.TempDir()
if err != nil {
t.Fatalf("err setting up temp dir: %v", err)
}
defer os.RemoveAll(testDir)
if err := testutil.SetupFiles(testDir, test.files); err != nil { if err := testutil.SetupFiles(testDir, test.files); err != nil {
t.Fatalf("err setting up files: %v", err) t.Fatalf("err setting up files: %v", err)
} }
@ -659,11 +652,7 @@ func Test_UnTar(t *testing.T) {
} }
for _, tc := range tcs { for _, tc := range tcs {
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
testDir, err := ioutil.TempDir("", "") testDir := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(testDir)
if err := createUncompressedTar(tc.setupTarContents, tc.tarFileName, testDir); err != nil { if err := createUncompressedTar(tc.setupTarContents, tc.tarFileName, testDir); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -812,15 +801,11 @@ func TestExtractFile(t *testing.T) {
tc := tc tc := tc
t.Parallel() t.Parallel()
r := "" r := ""
var err error
if tc.tmpdir != "" { if tc.tmpdir != "" {
r = tc.tmpdir r = tc.tmpdir
} else { } else {
r, err = ioutil.TempDir("", "") r = t.TempDir()
if err != nil {
t.Fatal(err)
}
} }
defer os.RemoveAll(r) defer os.RemoveAll(r)
@ -863,14 +848,10 @@ func TestCopySymlink(t *testing.T) {
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
tc := tc tc := tc
t.Parallel() t.Parallel()
r, err := ioutil.TempDir("", "") r := t.TempDir()
os.MkdirAll(filepath.Join(r, filepath.Dir(tc.linkTarget)), 0777) os.MkdirAll(filepath.Join(r, filepath.Dir(tc.linkTarget)), 0777)
tc.linkTarget = filepath.Join(r, tc.linkTarget) tc.linkTarget = filepath.Join(r, tc.linkTarget)
ioutil.WriteFile(tc.linkTarget, nil, 0644) ioutil.WriteFile(tc.linkTarget, nil, 0644)
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(r)
if tc.beforeLink != nil { if tc.beforeLink != nil {
if err := tc.beforeLink(r); err != nil { if err := tc.beforeLink(r); err != nil {
@ -994,10 +975,7 @@ func Test_correctDockerignoreFileIsUsed(t *testing.T) {
func Test_CopyFile_skips_self(t *testing.T) { func Test_CopyFile_skips_self(t *testing.T) {
t.Parallel() t.Parallel()
tempDir, err := ioutil.TempDir("", "kaniko_test") tempDir := t.TempDir()
if err != nil {
t.Fatal(err)
}
tempFile := filepath.Join(tempDir, "foo") tempFile := filepath.Join(tempDir, "foo")
expected := "bar" expected := "bar"
@ -1037,18 +1015,13 @@ func fakeExtract(dest string, hdr *tar.Header, tr io.Reader) error {
func Test_GetFSFromLayers_with_whiteouts_include_whiteout_enabled(t *testing.T) { func Test_GetFSFromLayers_with_whiteouts_include_whiteout_enabled(t *testing.T) {
ctrl := gomock.NewController(t) ctrl := gomock.NewController(t)
root, err := ioutil.TempDir("", "layers-test") root := t.TempDir()
if err != nil {
t.Fatal(err)
}
// Write a whiteout path // Write a whiteout path
d1 := []byte("Hello World\n") d1 := []byte("Hello World\n")
if err := ioutil.WriteFile(filepath.Join(root, "foobar"), d1, 0644); err != nil { if err := ioutil.WriteFile(filepath.Join(root, "foobar"), d1, 0644); err != nil {
t.Fatal(err) t.Fatal(err)
} }
defer os.Remove(root)
opts := []FSOpt{ opts := []FSOpt{
// I'd rather use the real func (util.ExtractFile) // I'd rather use the real func (util.ExtractFile)
// but you have to be root to chown // but you have to be root to chown
@ -1138,16 +1111,12 @@ func Test_GetFSFromLayers_with_whiteouts_include_whiteout_enabled(t *testing.T)
func Test_GetFSFromLayers_with_whiteouts_include_whiteout_disabled(t *testing.T) { func Test_GetFSFromLayers_with_whiteouts_include_whiteout_disabled(t *testing.T) {
ctrl := gomock.NewController(t) ctrl := gomock.NewController(t)
root, err := ioutil.TempDir("", "layers-test") root := t.TempDir()
if err != nil {
t.Fatal(err)
}
// Write a whiteout path // Write a whiteout path
d1 := []byte("Hello World\n") d1 := []byte("Hello World\n")
if err := ioutil.WriteFile(filepath.Join(root, "foobar"), d1, 0644); err != nil { if err := ioutil.WriteFile(filepath.Join(root, "foobar"), d1, 0644); err != nil {
t.Fatal(err) t.Fatal(err)
} }
defer os.Remove(root)
opts := []FSOpt{ opts := []FSOpt{
// I'd rather use the real func (util.ExtractFile) // I'd rather use the real func (util.ExtractFile)
@ -1242,11 +1211,7 @@ func Test_GetFSFromLayers_with_whiteouts_include_whiteout_disabled(t *testing.T)
func Test_GetFSFromLayers_ignorelist(t *testing.T) { func Test_GetFSFromLayers_ignorelist(t *testing.T) {
ctrl := gomock.NewController(t) ctrl := gomock.NewController(t)
root, err := ioutil.TempDir("", "layers-test") root := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer os.Remove(root)
// Write a whiteout path // Write a whiteout path
fileContents := []byte("Hello World\n") fileContents := []byte("Hello World\n")
if err := os.Mkdir(filepath.Join(root, "testdir"), 0775); err != nil { if err := os.Mkdir(filepath.Join(root, "testdir"), 0775); err != nil {
@ -1388,11 +1353,7 @@ func Test_GetFSFromLayers_ignorelist(t *testing.T) {
func Test_GetFSFromLayers(t *testing.T) { func Test_GetFSFromLayers(t *testing.T) {
ctrl := gomock.NewController(t) ctrl := gomock.NewController(t)
root, err := ioutil.TempDir("", "layers-test") root := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer os.Remove(root)
opts := []FSOpt{ opts := []FSOpt{
// I'd rather use the real func (util.ExtractFile) // I'd rather use the real func (util.ExtractFile)
@ -1536,12 +1497,7 @@ func TestInitIgnoreList(t *testing.T) {
} }
func Test_setFileTimes(t *testing.T) { func Test_setFileTimes(t *testing.T) {
testDir, err := ioutil.TempDir("", "") testDir := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(testDir)
p := filepath.Join(testDir, "foo.txt") p := filepath.Join(testDir, "foo.txt")

View File

@ -33,11 +33,7 @@ func TestDockerConfLocationWithInvalidFileLocation(t *testing.T) {
if err := os.Unsetenv(DockerConfigEnvKey); err != nil { if err := os.Unsetenv(DockerConfigEnvKey); err != nil {
t.Fatalf("Failed to unset DOCKER_CONFIG: %v", err) t.Fatalf("Failed to unset DOCKER_CONFIG: %v", err)
} }
tmpDir, err := ioutil.TempDir("", "*") tmpDir := t.TempDir()
if err != nil {
t.Fatalf("could not create temp dir: %s", err)
}
defer os.RemoveAll(tmpDir)
random := "fdgdsfrdfgdf-fdfsf-24dsgfd" //replace with a really random string random := "fdgdsfrdfgdf-fdfsf-24dsgfd" //replace with a really random string
file := filepath.Join(tmpDir, random) // an random file name, shouldn't exist file := filepath.Join(tmpDir, random) // an random file name, shouldn't exist
if err := os.Setenv(DockerConfigEnvKey, file); err != nil { if err := os.Setenv(DockerConfigEnvKey, file); err != nil {
@ -63,11 +59,7 @@ func TestDockerConfLocation(t *testing.T) {
if unset != unsetExpected { if unset != unsetExpected {
t.Errorf("Unexpected default Docker configuration file location: expected:'%s' got:'%s'", unsetExpected, unset) t.Errorf("Unexpected default Docker configuration file location: expected:'%s' got:'%s'", unsetExpected, unset)
} }
tmpDir, err := ioutil.TempDir("", "*") tmpDir := t.TempDir()
if err != nil {
t.Fatalf("could not create temp dir: %s", err)
}
defer os.RemoveAll(tmpDir)
dir := filepath.Join(tmpDir, "/kaniko/.docker") dir := filepath.Join(tmpDir, "/kaniko/.docker")
os.MkdirAll(dir, os.ModePerm) os.MkdirAll(dir, os.ModePerm)
@ -80,11 +72,7 @@ func TestDockerConfLocation(t *testing.T) {
t.Errorf("Unexpected kaniko default Docker conf file location: expected:'%s' got:'%s'", kanikoDefaultExpected, kanikoDefault) t.Errorf("Unexpected kaniko default Docker conf file location: expected:'%s' got:'%s'", kanikoDefaultExpected, kanikoDefault)
} }
differentPath, err := ioutil.TempDir("", "differentPath") differentPath := t.TempDir()
if err != nil {
t.Fatalf("could not create temp dir: %s", err)
}
defer os.RemoveAll(differentPath)
if err := os.Setenv(DockerConfigEnvKey, differentPath); err != nil { if err := os.Setenv(DockerConfigEnvKey, differentPath); err != nil {
t.Fatalf("Failed to set DOCKER_CONFIG: %v", err) t.Fatalf("Failed to set DOCKER_CONFIG: %v", err)
} }

View File

@ -35,11 +35,7 @@ var uncompressedTars = []string{"uncompressed", "uncompressed.tar"}
var compressedTars = []string{"compressed", "compressed.tar.gz"} var compressedTars = []string{"compressed", "compressed.tar.gz"}
func Test_IsLocalTarArchive(t *testing.T) { func Test_IsLocalTarArchive(t *testing.T) {
testDir, err := ioutil.TempDir("", "") testDir := t.TempDir()
if err != nil {
t.Fatalf("err setting up temp dir: %v", err)
}
defer os.RemoveAll(testDir)
if err := setUpFilesAndTars(testDir); err != nil { if err := setUpFilesAndTars(testDir); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -61,11 +57,7 @@ func Test_IsLocalTarArchive(t *testing.T) {
} }
func Test_AddFileToTar(t *testing.T) { func Test_AddFileToTar(t *testing.T) {
testDir, err := ioutil.TempDir("", "") testDir := t.TempDir()
if err != nil {
t.Fatalf("err setting up temp dir: %v", err)
}
defer os.RemoveAll(testDir)
path := filepath.Join(testDir, regularFiles[0]) path := filepath.Join(testDir, regularFiles[0])
if err := ioutil.WriteFile(path, []byte("hello"), os.ModePerm); err != nil { if err := ioutil.WriteFile(path, []byte("hello"), os.ModePerm); err != nil {