run.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. /*
  2. This provides Run for use in creating test suites
  3. To use this declare a TestMain
  4. // TestMain drives the tests
  5. func TestMain(m *testing.M) {
  6. fstest.TestMain(m)
  7. }
  8. And then make and destroy a Run in each test
  9. func TestMkdir(t *testing.T) {
  10. r := fstest.NewRun(t)
  11. defer r.Finalise()
  12. // test stuff
  13. }
  14. This will make r.Fremote and r.Flocal for a remote and a local
  15. remote. The remote is determined by the -remote flag passed in.
  16. */
  17. package fstest
  18. import (
  19. "bytes"
  20. "context"
  21. "flag"
  22. "fmt"
  23. "log"
  24. "os"
  25. "path"
  26. "path/filepath"
  27. "sort"
  28. "testing"
  29. "time"
  30. "github.com/rclone/rclone/fs"
  31. "github.com/rclone/rclone/fs/cache"
  32. "github.com/rclone/rclone/fs/fserrors"
  33. "github.com/rclone/rclone/fs/hash"
  34. "github.com/rclone/rclone/fs/object"
  35. "github.com/rclone/rclone/fs/walk"
  36. "github.com/rclone/rclone/lib/file"
  37. "github.com/stretchr/testify/assert"
  38. "github.com/stretchr/testify/require"
  39. )
  40. // Run holds the remotes for a test run
  41. type Run struct {
  42. LocalName string
  43. Flocal fs.Fs
  44. Fremote fs.Fs
  45. FremoteName string
  46. Precision time.Duration
  47. cleanRemote func()
  48. mkdir map[string]bool // whether the remote has been made yet for the fs name
  49. Logf, Fatalf func(text string, args ...interface{})
  50. }
  51. // TestMain drives the tests
  52. func TestMain(m *testing.M) {
  53. flag.Parse()
  54. if !*Individual {
  55. oneRun = newRun()
  56. }
  57. rc := m.Run()
  58. if !*Individual {
  59. oneRun.Finalise()
  60. }
  61. os.Exit(rc)
  62. }
  63. // oneRun holds the master run data if individual is not set
  64. var oneRun *Run
  65. // newRun initialise the remote and local for testing and returns a
  66. // run object.
  67. //
  68. // r.Flocal is an empty local Fs
  69. // r.Fremote is an empty remote Fs
  70. //
  71. // Finalise() will tidy them away when done.
  72. func newRun() *Run {
  73. r := &Run{
  74. Logf: log.Printf,
  75. Fatalf: log.Fatalf,
  76. mkdir: make(map[string]bool),
  77. }
  78. Initialise()
  79. var err error
  80. r.Fremote, r.FremoteName, r.cleanRemote, err = RandomRemote()
  81. if err != nil {
  82. r.Fatalf("Failed to open remote %q: %v", *RemoteName, err)
  83. }
  84. r.LocalName, err = os.MkdirTemp("", "rclone")
  85. if err != nil {
  86. r.Fatalf("Failed to create temp dir: %v", err)
  87. }
  88. r.LocalName = filepath.ToSlash(r.LocalName)
  89. r.Flocal, err = fs.NewFs(context.Background(), r.LocalName)
  90. if err != nil {
  91. r.Fatalf("Failed to make %q: %v", r.LocalName, err)
  92. }
  93. r.Precision = fs.GetModifyWindow(context.Background(), r.Fremote, r.Flocal)
  94. return r
  95. }
  96. // run f(), retrying it until it returns with no error or the limit
  97. // expires and it calls t.Fatalf
  98. func retry(t *testing.T, what string, f func() error) {
  99. var err error
  100. for try := 1; try <= *ListRetries; try++ {
  101. err = f()
  102. if err == nil {
  103. return
  104. }
  105. t.Logf("%s failed - try %d/%d: %v", what, try, *ListRetries, err)
  106. time.Sleep(time.Second)
  107. }
  108. t.Logf("%s failed: %v", what, err)
  109. }
  110. // newRunIndividual initialise the remote and local for testing and
  111. // returns a run object. Pass in true to make individual tests or
  112. // false to use the global one.
  113. //
  114. // r.Flocal is an empty local Fs
  115. // r.Fremote is an empty remote Fs
  116. //
  117. // Finalise() will tidy them away when done.
  118. func newRunIndividual(t *testing.T, individual bool) *Run {
  119. ctx := context.Background()
  120. var r *Run
  121. if individual {
  122. r = newRun()
  123. } else {
  124. // If not individual, use the global one with the clean method overridden
  125. r = new(Run)
  126. *r = *oneRun
  127. r.cleanRemote = func() {
  128. var toDelete []string
  129. err := walk.ListR(ctx, r.Fremote, "", true, -1, walk.ListAll, func(entries fs.DirEntries) error {
  130. for _, entry := range entries {
  131. switch x := entry.(type) {
  132. case fs.Object:
  133. retry(t, fmt.Sprintf("removing file %q", x.Remote()), func() error { return x.Remove(ctx) })
  134. case fs.Directory:
  135. toDelete = append(toDelete, x.Remote())
  136. }
  137. }
  138. return nil
  139. })
  140. if err == fs.ErrorDirNotFound {
  141. return
  142. }
  143. require.NoError(t, err)
  144. sort.Strings(toDelete)
  145. for i := len(toDelete) - 1; i >= 0; i-- {
  146. dir := toDelete[i]
  147. retry(t, fmt.Sprintf("removing dir %q", dir), func() error {
  148. return r.Fremote.Rmdir(ctx, dir)
  149. })
  150. }
  151. // Check remote is empty
  152. CheckListingWithPrecision(t, r.Fremote, []Item{}, []string{}, r.Fremote.Precision())
  153. // Clear the remote cache
  154. cache.Clear()
  155. }
  156. }
  157. r.Logf = t.Logf
  158. r.Fatalf = t.Fatalf
  159. r.Logf("Remote %q, Local %q, Modify Window %q", r.Fremote, r.Flocal, fs.GetModifyWindow(ctx, r.Fremote))
  160. t.Cleanup(r.Finalise)
  161. return r
  162. }
  163. // NewRun initialise the remote and local for testing and returns a
  164. // run object. Call this from the tests.
  165. //
  166. // r.Flocal is an empty local Fs
  167. // r.Fremote is an empty remote Fs
  168. func NewRun(t *testing.T) *Run {
  169. return newRunIndividual(t, *Individual)
  170. }
  171. // NewRunIndividual as per NewRun but makes an individual remote for this test
  172. func NewRunIndividual(t *testing.T) *Run {
  173. return newRunIndividual(t, true)
  174. }
  175. // RenameFile renames a file in local
  176. func (r *Run) RenameFile(item Item, newpath string) Item {
  177. oldFilepath := path.Join(r.LocalName, item.Path)
  178. newFilepath := path.Join(r.LocalName, newpath)
  179. if err := os.Rename(oldFilepath, newFilepath); err != nil {
  180. r.Fatalf("Failed to rename file from %q to %q: %v", item.Path, newpath, err)
  181. }
  182. item.Path = newpath
  183. return item
  184. }
  185. // WriteFile writes a file to local
  186. func (r *Run) WriteFile(filePath, content string, t time.Time) Item {
  187. item := NewItem(filePath, content, t)
  188. // FIXME make directories?
  189. filePath = path.Join(r.LocalName, filePath)
  190. dirPath := path.Dir(filePath)
  191. err := file.MkdirAll(dirPath, 0770)
  192. if err != nil {
  193. r.Fatalf("Failed to make directories %q: %v", dirPath, err)
  194. }
  195. err = os.WriteFile(filePath, []byte(content), 0600)
  196. if err != nil {
  197. r.Fatalf("Failed to write file %q: %v", filePath, err)
  198. }
  199. err = os.Chtimes(filePath, t, t)
  200. if err != nil {
  201. r.Fatalf("Failed to chtimes file %q: %v", filePath, err)
  202. }
  203. return item
  204. }
  205. // ForceMkdir creates the remote
  206. func (r *Run) ForceMkdir(ctx context.Context, f fs.Fs) {
  207. err := f.Mkdir(ctx, "")
  208. if err != nil {
  209. r.Fatalf("Failed to mkdir %q: %v", f, err)
  210. }
  211. r.mkdir[f.String()] = true
  212. }
  213. // Mkdir creates the remote if it hasn't been created already
  214. func (r *Run) Mkdir(ctx context.Context, f fs.Fs) {
  215. if !r.mkdir[f.String()] {
  216. r.ForceMkdir(ctx, f)
  217. }
  218. }
  219. // WriteObjectTo writes an object to the fs, remote passed in
  220. func (r *Run) WriteObjectTo(ctx context.Context, f fs.Fs, remote, content string, modTime time.Time, useUnchecked bool) Item {
  221. put := f.Put
  222. if useUnchecked {
  223. put = f.Features().PutUnchecked
  224. if put == nil {
  225. r.Fatalf("Fs doesn't support PutUnchecked")
  226. }
  227. }
  228. r.Mkdir(ctx, f)
  229. // calculate all hashes f supports for content
  230. hash, err := hash.NewMultiHasherTypes(f.Hashes())
  231. if err != nil {
  232. r.Fatalf("Failed to make new multi hasher: %v", err)
  233. }
  234. _, err = hash.Write([]byte(content))
  235. if err != nil {
  236. r.Fatalf("Failed to make write to hash: %v", err)
  237. }
  238. hashSums := hash.Sums()
  239. const maxTries = 10
  240. for tries := 1; ; tries++ {
  241. in := bytes.NewBufferString(content)
  242. objinfo := object.NewStaticObjectInfo(remote, modTime, int64(len(content)), true, hashSums, nil)
  243. _, err := put(ctx, in, objinfo)
  244. if err == nil {
  245. break
  246. }
  247. // Retry if err returned a retry error
  248. if fserrors.IsRetryError(err) && tries < maxTries {
  249. r.Logf("Retry Put of %q to %v: %d/%d (%v)", remote, f, tries, maxTries, err)
  250. time.Sleep(2 * time.Second)
  251. continue
  252. }
  253. r.Fatalf("Failed to put %q to %q: %v", remote, f, err)
  254. }
  255. return NewItem(remote, content, modTime)
  256. }
  257. // WriteObject writes an object to the remote
  258. func (r *Run) WriteObject(ctx context.Context, remote, content string, modTime time.Time) Item {
  259. return r.WriteObjectTo(ctx, r.Fremote, remote, content, modTime, false)
  260. }
  261. // WriteUncheckedObject writes an object to the remote not checking for duplicates
  262. func (r *Run) WriteUncheckedObject(ctx context.Context, remote, content string, modTime time.Time) Item {
  263. return r.WriteObjectTo(ctx, r.Fremote, remote, content, modTime, true)
  264. }
  265. // WriteBoth calls WriteObject and WriteFile with the same arguments
  266. func (r *Run) WriteBoth(ctx context.Context, remote, content string, modTime time.Time) Item {
  267. r.WriteFile(remote, content, modTime)
  268. return r.WriteObject(ctx, remote, content, modTime)
  269. }
  270. // CheckWithDuplicates does a test but allows duplicates
  271. func (r *Run) CheckWithDuplicates(t *testing.T, items ...Item) {
  272. var want, got []string
  273. // construct a []string of desired items
  274. for _, item := range items {
  275. want = append(want, fmt.Sprintf("%q %d", item.Path, item.Size))
  276. }
  277. sort.Strings(want)
  278. // do the listing
  279. objs, _, err := walk.GetAll(context.Background(), r.Fremote, "", true, -1)
  280. if err != nil && err != fs.ErrorDirNotFound {
  281. t.Fatalf("Error listing: %v", err)
  282. }
  283. // construct a []string of actual items
  284. for _, o := range objs {
  285. got = append(got, fmt.Sprintf("%q %d", o.Remote(), o.Size()))
  286. }
  287. sort.Strings(got)
  288. assert.Equal(t, want, got)
  289. }
  290. // CheckLocalItems checks the local fs with proper precision
  291. // to see if it has the expected items.
  292. func (r *Run) CheckLocalItems(t *testing.T, items ...Item) {
  293. CheckItemsWithPrecision(t, r.Flocal, r.Precision, items...)
  294. }
  295. // CheckRemoteItems checks the remote fs with proper precision
  296. // to see if it has the expected items.
  297. func (r *Run) CheckRemoteItems(t *testing.T, items ...Item) {
  298. CheckItemsWithPrecision(t, r.Fremote, r.Precision, items...)
  299. }
  300. // CheckLocalListing checks the local fs with proper precision
  301. // to see if it has the expected contents.
  302. //
  303. // If expectedDirs is non nil then we check those too. Note that no
  304. // directories returned is also OK as some remotes don't return
  305. // directories.
  306. func (r *Run) CheckLocalListing(t *testing.T, items []Item, expectedDirs []string) {
  307. CheckListingWithPrecision(t, r.Flocal, items, expectedDirs, r.Precision)
  308. }
  309. // CheckRemoteListing checks the remote fs with proper precision
  310. // to see if it has the expected contents.
  311. //
  312. // If expectedDirs is non nil then we check those too. Note that no
  313. // directories returned is also OK as some remotes don't return
  314. // directories.
  315. func (r *Run) CheckRemoteListing(t *testing.T, items []Item, expectedDirs []string) {
  316. CheckListingWithPrecision(t, r.Fremote, items, expectedDirs, r.Precision)
  317. }
  318. // CheckDirectoryModTimes checks that the directory names in r.Flocal has the correct modtime compared to r.Fremote
  319. func (r *Run) CheckDirectoryModTimes(t *testing.T, names ...string) {
  320. if r.Fremote.Features().DirSetModTime == nil && r.Fremote.Features().MkdirMetadata == nil {
  321. fs.Debugf(r.Fremote, "Skipping modtime test as remote does not support DirSetModTime or MkdirMetadata")
  322. return
  323. }
  324. ctx := context.Background()
  325. for _, name := range names {
  326. wantT := NewDirectory(ctx, t, r.Flocal, name).ModTime(ctx)
  327. got := NewDirectory(ctx, t, r.Fremote, name)
  328. CheckDirModTime(ctx, t, r.Fremote, got, wantT)
  329. }
  330. }
  331. // Clean the temporary directory
  332. func (r *Run) cleanTempDir() {
  333. err := os.RemoveAll(r.LocalName)
  334. if err != nil {
  335. r.Logf("Failed to clean temporary directory %q: %v", r.LocalName, err)
  336. }
  337. }
  338. // Finalise cleans the remote and local
  339. func (r *Run) Finalise() {
  340. // r.Logf("Cleaning remote %q", r.Fremote)
  341. r.cleanRemote()
  342. // r.Logf("Cleaning local %q", r.LocalName)
  343. r.cleanTempDir()
  344. // Clear the remote cache
  345. cache.Clear()
  346. }