utils_test.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package remotecontext
  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. // createTestTempSubdir creates a temporary directory for testing.
  24. // It returns the created path but doesn't provide a cleanup function,
  25. // so createTestTempSubdir should be used only for creating temporary subdirectories
  26. // whose parent directories are properly cleaned up.
  27. // When an error occurs, it terminates the test.
  28. func createTestTempSubdir(t *testing.T, dir, prefix string) string {
  29. path, err := ioutil.TempDir(dir, prefix)
  30. if err != nil {
  31. t.Fatalf("Error when creating directory %s with prefix %s: %s", dir, prefix, err)
  32. }
  33. return path
  34. }
  35. // createTestTempFile creates a temporary file within dir with specific contents and permissions.
  36. // When an error occurs, it terminates the test
  37. func createTestTempFile(t *testing.T, dir, filename, contents string, perm os.FileMode) string {
  38. filePath := filepath.Join(dir, filename)
  39. err := ioutil.WriteFile(filePath, []byte(contents), perm)
  40. if err != nil {
  41. t.Fatalf("Error when creating %s file: %s", filename, err)
  42. }
  43. return filePath
  44. }