github.com/Prakhar-Agarwal-byte/moby@v0.0.0-20231027092010-a14e3e8ab87e/builder/remotecontext/utils_test.go (about) 1 package remotecontext // import "github.com/Prakhar-Agarwal-byte/moby/builder/remotecontext" 2 3 import ( 4 "os" 5 "path/filepath" 6 "testing" 7 ) 8 9 // createTestTempDir creates a temporary directory for testing. 10 // It returns the created path and a cleanup function which is meant to be used as deferred call. 11 // When an error occurs, it terminates the test. 12 func createTestTempDir(t *testing.T, dir, prefix string) (string, func()) { 13 path, err := os.MkdirTemp(dir, prefix) 14 if err != nil { 15 t.Fatalf("Error when creating directory %s with prefix %s: %s", dir, prefix, err) 16 } 17 18 return path, func() { 19 err = os.RemoveAll(path) 20 21 if err != nil { 22 t.Fatalf("Error when removing directory %s: %s", path, err) 23 } 24 } 25 } 26 27 // createTestTempSubdir creates a temporary directory for testing. 28 // It returns the created path but doesn't provide a cleanup function, 29 // so createTestTempSubdir should be used only for creating temporary subdirectories 30 // whose parent directories are properly cleaned up. 31 // When an error occurs, it terminates the test. 32 func createTestTempSubdir(t *testing.T, dir, prefix string) string { 33 path, err := os.MkdirTemp(dir, prefix) 34 if err != nil { 35 t.Fatalf("Error when creating directory %s with prefix %s: %s", dir, prefix, err) 36 } 37 38 return path 39 } 40 41 // createTestTempFile creates a temporary file within dir with specific contents and permissions. 42 // When an error occurs, it terminates the test 43 func createTestTempFile(t *testing.T, dir, filename, contents string, perm os.FileMode) string { 44 filePath := filepath.Join(dir, filename) 45 err := os.WriteFile(filePath, []byte(contents), perm) 46 if err != nil { 47 t.Fatalf("Error when creating %s file: %s", filename, err) 48 } 49 50 return filePath 51 }