utils_test.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. }
  50. // chdir changes current working directory to dir.
  51. // It returns a function which changes working directory back to the previous one.
  52. // This function is meant to be executed as a deferred call.
  53. // When an error occurs, it terminates the test.
  54. func chdir(t *testing.T, dir string) func() {
  55. workingDirectory, err := os.Getwd()
  56. if err != nil {
  57. t.Fatalf("Error when retrieving working directory: %s", err)
  58. }
  59. err = os.Chdir(dir)
  60. if err != nil {
  61. t.Fatalf("Error when changing directory to %s: %s", dir, err)
  62. }
  63. return func() {
  64. err = os.Chdir(workingDirectory)
  65. if err != nil {
  66. t.Fatalf("Error when changing back to working directory (%s): %s", workingDirectory, err)
  67. }
  68. }
  69. }