utils_test.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package dockerfile
  2. import (
  3. "io/ioutil"
  4. "os"
  5. "path/filepath"
  6. "testing"
  7. )
  8. // createTestTempDir creates a temporary directory for testing.
  9. // It returns the created path and a cleanup function which is meant to be used as deferred call.
  10. // When an error occurs, it terminates the test.
  11. func createTestTempDir(t *testing.T, dir, prefix string) (string, func()) {
  12. path, err := ioutil.TempDir(dir, prefix)
  13. if err != nil {
  14. t.Fatalf("Error when creating directory %s with prefix %s: %s", dir, prefix, err)
  15. }
  16. return path, func() {
  17. err = os.RemoveAll(path)
  18. if err != nil {
  19. t.Fatalf("Error when removing directory %s: %s", path, err)
  20. }
  21. }
  22. }
  23. // createTestTempFile creates a temporary file within dir with specific contents and permissions.
  24. // When an error occurs, it terminates the test
  25. func createTestTempFile(t *testing.T, dir, filename, contents string, perm os.FileMode) string {
  26. filePath := filepath.Join(dir, filename)
  27. err := ioutil.WriteFile(filePath, []byte(contents), perm)
  28. if err != nil {
  29. t.Fatalf("Error when creating %s file: %s", filename, err)
  30. }
  31. return filePath
  32. }
  33. // createTestSymlink creates a symlink file within dir which points to oldname
  34. func createTestSymlink(t *testing.T, dir, filename, oldname string) string {
  35. filePath := filepath.Join(dir, filename)
  36. if err := os.Symlink(oldname, filePath); err != nil {
  37. t.Fatalf("Error when creating %s symlink to %s: %s", filename, oldname, err)
  38. }
  39. return filePath
  40. }