utils.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. package cstest
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "testing"
  7. "github.com/stretchr/testify/assert"
  8. "github.com/stretchr/testify/require"
  9. )
  10. func Copy(sourceFile string, destinationFile string) error {
  11. input, err := os.ReadFile(sourceFile)
  12. if err != nil {
  13. return err
  14. }
  15. err = os.WriteFile(destinationFile, input, 0644)
  16. if err != nil {
  17. return err
  18. }
  19. return nil
  20. }
  21. // checkPathNotContained returns an error if 'subpath' is inside 'path'
  22. func checkPathNotContained(path string, subpath string) error {
  23. absPath, err := filepath.Abs(path)
  24. if err != nil {
  25. return err
  26. }
  27. absSubPath, err := filepath.Abs(subpath)
  28. if err != nil {
  29. return err
  30. }
  31. current := absSubPath
  32. for {
  33. if current == absPath {
  34. return fmt.Errorf("cannot copy a folder onto itself")
  35. }
  36. up := filepath.Dir(current)
  37. if current == up {
  38. break
  39. }
  40. current = up
  41. }
  42. return nil
  43. }
  44. func CopyDir(src string, dest string) error {
  45. err := checkPathNotContained(src, dest)
  46. if err != nil {
  47. return err
  48. }
  49. f, err := os.Open(src)
  50. if err != nil {
  51. return err
  52. }
  53. file, err := f.Stat()
  54. if err != nil {
  55. return err
  56. }
  57. if !file.IsDir() {
  58. return fmt.Errorf("Source " + file.Name() + " is not a directory!")
  59. }
  60. err = os.MkdirAll(dest, 0755)
  61. if err != nil {
  62. return err
  63. }
  64. files, err := os.ReadDir(src)
  65. if err != nil {
  66. return err
  67. }
  68. for _, f := range files {
  69. if f.IsDir() {
  70. err = CopyDir(src+"/"+f.Name(), dest+"/"+f.Name())
  71. if err != nil {
  72. return err
  73. }
  74. }
  75. if !f.IsDir() {
  76. content, err := os.ReadFile(src + "/" + f.Name())
  77. if err != nil {
  78. return err
  79. }
  80. err = os.WriteFile(dest+"/"+f.Name(), content, 0755)
  81. if err != nil {
  82. return err
  83. }
  84. }
  85. }
  86. return nil
  87. }
  88. func AssertErrorContains(t *testing.T, err error, expectedErr string) {
  89. t.Helper()
  90. if expectedErr != "" {
  91. assert.ErrorContains(t, err, expectedErr)
  92. return
  93. }
  94. assert.NoError(t, err)
  95. }
  96. func RequireErrorContains(t *testing.T, err error, expectedErr string) {
  97. t.Helper()
  98. if expectedErr != "" {
  99. require.ErrorContains(t, err, expectedErr)
  100. return
  101. }
  102. require.NoError(t, err)
  103. }