github.com/skf/moby@v1.13.1/builder/utils_test.go (about) 1 package builder 2 3 import ( 4 "io/ioutil" 5 "os" 6 "path/filepath" 7 "testing" 8 ) 9 10 const ( 11 dockerfileContents = "FROM busybox" 12 dockerignoreFilename = ".dockerignore" 13 testfileContents = "test" 14 ) 15 16 // createTestTempDir creates a temporary directory for testing. 17 // It returns the created path and a cleanup function which is meant to be used as deferred call. 18 // When an error occurs, it terminates the test. 19 func createTestTempDir(t *testing.T, dir, prefix string) (string, func()) { 20 path, err := ioutil.TempDir(dir, prefix) 21 22 if err != nil { 23 t.Fatalf("Error when creating directory %s with prefix %s: %s", dir, prefix, err) 24 } 25 26 return path, func() { 27 err = os.RemoveAll(path) 28 29 if err != nil { 30 t.Fatalf("Error when removing directory %s: %s", path, err) 31 } 32 } 33 } 34 35 // createTestTempSubdir creates a temporary directory for testing. 36 // It returns the created path but doesn't provide a cleanup function, 37 // so createTestTempSubdir should be used only for creating temporary subdirectories 38 // whose parent directories are properly cleaned up. 39 // When an error occurs, it terminates the test. 40 func createTestTempSubdir(t *testing.T, dir, prefix string) string { 41 path, err := ioutil.TempDir(dir, prefix) 42 43 if err != nil { 44 t.Fatalf("Error when creating directory %s with prefix %s: %s", dir, prefix, err) 45 } 46 47 return path 48 } 49 50 // createTestTempFile creates a temporary file within dir with specific contents and permissions. 51 // When an error occurs, it terminates the test 52 func createTestTempFile(t *testing.T, dir, filename, contents string, perm os.FileMode) string { 53 filePath := filepath.Join(dir, filename) 54 err := ioutil.WriteFile(filePath, []byte(contents), perm) 55 56 if err != nil { 57 t.Fatalf("Error when creating %s file: %s", filename, err) 58 } 59 60 return filePath 61 } 62 63 // chdir changes current working directory to dir. 64 // It returns a function which changes working directory back to the previous one. 65 // This function is meant to be executed as a deferred call. 66 // When an error occurs, it terminates the test. 67 func chdir(t *testing.T, dir string) func() { 68 workingDirectory, err := os.Getwd() 69 70 if err != nil { 71 t.Fatalf("Error when retrieving working directory: %s", err) 72 } 73 74 err = os.Chdir(dir) 75 76 if err != nil { 77 t.Fatalf("Error when changing directory to %s: %s", dir, err) 78 } 79 80 return func() { 81 err = os.Chdir(workingDirectory) 82 83 if err != nil { 84 t.Fatalf("Error when changing back to working directory (%s): %s", workingDirectory, err) 85 } 86 } 87 }