utils_test.go 1.7 KB

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