You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
1.8 KiB

  1. package os
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io/ioutil"
  6. "os"
  7. "path/filepath"
  8. "testing"
  9. "github.com/stretchr/testify/require"
  10. )
  11. func TestCopyFile(t *testing.T) {
  12. tmpfile, err := ioutil.TempFile("", "example")
  13. if err != nil {
  14. t.Fatal(err)
  15. }
  16. defer os.Remove(tmpfile.Name())
  17. content := []byte("hello world")
  18. if _, err := tmpfile.Write(content); err != nil {
  19. t.Fatal(err)
  20. }
  21. copyfile := fmt.Sprintf("%s.copy", tmpfile.Name())
  22. if err := CopyFile(tmpfile.Name(), copyfile); err != nil {
  23. t.Fatal(err)
  24. }
  25. if _, err := os.Stat(copyfile); os.IsNotExist(err) {
  26. t.Fatal("copy should exist")
  27. }
  28. data, err := ioutil.ReadFile(copyfile)
  29. if err != nil {
  30. t.Fatal(err)
  31. }
  32. if !bytes.Equal(data, content) {
  33. t.Fatalf("copy file content differs: expected %v, got %v", content, data)
  34. }
  35. os.Remove(copyfile)
  36. }
  37. func TestEnsureDir(t *testing.T) {
  38. tmp, err := ioutil.TempDir("", "ensure-dir")
  39. require.NoError(t, err)
  40. defer os.RemoveAll(tmp)
  41. // Should be possible to create a new directory.
  42. err = EnsureDir(filepath.Join(tmp, "dir"), 0755)
  43. require.NoError(t, err)
  44. require.DirExists(t, filepath.Join(tmp, "dir"))
  45. // Should succeed on existing directory.
  46. err = EnsureDir(filepath.Join(tmp, "dir"), 0755)
  47. require.NoError(t, err)
  48. // Should fail on file.
  49. err = ioutil.WriteFile(filepath.Join(tmp, "file"), []byte{}, 0644)
  50. require.NoError(t, err)
  51. err = EnsureDir(filepath.Join(tmp, "file"), 0755)
  52. require.Error(t, err)
  53. // Should allow symlink to dir.
  54. err = os.Symlink(filepath.Join(tmp, "dir"), filepath.Join(tmp, "linkdir"))
  55. require.NoError(t, err)
  56. err = EnsureDir(filepath.Join(tmp, "linkdir"), 0755)
  57. require.NoError(t, err)
  58. // Should error on symlink to file.
  59. err = os.Symlink(filepath.Join(tmp, "file"), filepath.Join(tmp, "linkfile"))
  60. require.NoError(t, err)
  61. err = EnsureDir(filepath.Join(tmp, "linkfile"), 0755)
  62. require.Error(t, err)
  63. }