trashcan_test.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright (C) 2015 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package versioner
  7. import (
  8. "io/ioutil"
  9. "os"
  10. "path/filepath"
  11. "testing"
  12. "time"
  13. "github.com/syncthing/syncthing/lib/fs"
  14. )
  15. func TestTrashcanCleanout(t *testing.T) {
  16. // Verify that files older than the cutoff are removed, that files newer
  17. // than the cutoff are *not* removed, and that empty directories are
  18. // removed (best effort).
  19. var testcases = []struct {
  20. file string
  21. shouldRemove bool
  22. }{
  23. {"testdata/.stversions/file1", false},
  24. {"testdata/.stversions/file2", true},
  25. {"testdata/.stversions/keep1/file1", false},
  26. {"testdata/.stversions/keep1/file2", false},
  27. {"testdata/.stversions/keep2/file1", false},
  28. {"testdata/.stversions/keep2/file2", true},
  29. {"testdata/.stversions/keep3/keepsubdir/file1", false},
  30. {"testdata/.stversions/remove/file1", true},
  31. {"testdata/.stversions/remove/file2", true},
  32. {"testdata/.stversions/remove/removesubdir/file1", true},
  33. }
  34. os.RemoveAll("testdata")
  35. defer os.RemoveAll("testdata")
  36. oldTime := time.Now().Add(-8 * 24 * time.Hour)
  37. for _, tc := range testcases {
  38. os.MkdirAll(filepath.Dir(tc.file), 0777)
  39. if err := ioutil.WriteFile(tc.file, []byte("data"), 0644); err != nil {
  40. t.Fatal(err)
  41. }
  42. if tc.shouldRemove {
  43. if err := os.Chtimes(tc.file, oldTime, oldTime); err != nil {
  44. t.Fatal(err)
  45. }
  46. }
  47. }
  48. versioner := NewTrashcan("default", fs.NewFilesystem(fs.FilesystemTypeBasic, "testdata"), map[string]string{"cleanoutDays": "7"}).(*Trashcan)
  49. if err := versioner.cleanoutArchive(); err != nil {
  50. t.Fatal(err)
  51. }
  52. for _, tc := range testcases {
  53. _, err := os.Lstat(tc.file)
  54. if tc.shouldRemove && !os.IsNotExist(err) {
  55. t.Error(tc.file, "should have been removed")
  56. } else if !tc.shouldRemove && err != nil {
  57. t.Error(tc.file, "should not have been removed")
  58. }
  59. }
  60. if _, err := os.Lstat("testdata/.stversions/keep3"); os.IsNotExist(err) {
  61. t.Error("directory with non empty subdirs should not be removed")
  62. }
  63. if _, err := os.Lstat("testdata/.stversions/remove"); !os.IsNotExist(err) {
  64. t.Error("empty directory should have been removed")
  65. }
  66. }