utils_test.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package dockerfile // import "github.com/docker/docker/builder/dockerfile"
  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. // createTestTempFile creates a temporary file within dir with specific contents and permissions.
  23. // When an error occurs, it terminates the test
  24. func createTestTempFile(t *testing.T, dir, filename, contents string, perm os.FileMode) string {
  25. filePath := filepath.Join(dir, filename)
  26. err := os.WriteFile(filePath, []byte(contents), perm)
  27. if err != nil {
  28. t.Fatalf("Error when creating %s file: %s", filename, err)
  29. }
  30. return filePath
  31. }
  32. // createTestSymlink creates a symlink file within dir which points to oldname
  33. func createTestSymlink(t *testing.T, dir, filename, oldname string) string {
  34. filePath := filepath.Join(dir, filename)
  35. if err := os.Symlink(oldname, filePath); err != nil {
  36. t.Fatalf("Error when creating %s symlink to %s: %s", filename, oldname, err)
  37. }
  38. return filePath
  39. }