utils_test.go 1.7 KB

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