trashcan_test.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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/remove/file1", true},
  30. {"testdata/.stversions/remove/file2", true},
  31. }
  32. os.RemoveAll("testdata")
  33. defer os.RemoveAll("testdata")
  34. oldTime := time.Now().Add(-8 * 24 * time.Hour)
  35. for _, tc := range testcases {
  36. os.MkdirAll(filepath.Dir(tc.file), 0777)
  37. if err := ioutil.WriteFile(tc.file, []byte("data"), 0644); err != nil {
  38. t.Fatal(err)
  39. }
  40. if tc.shouldRemove {
  41. if err := os.Chtimes(tc.file, oldTime, oldTime); err != nil {
  42. t.Fatal(err)
  43. }
  44. }
  45. }
  46. versioner := NewTrashcan("default", fs.NewFilesystem(fs.FilesystemTypeBasic, "testdata"), map[string]string{"cleanoutDays": "7"}).(*Trashcan)
  47. if err := versioner.cleanoutArchive(); err != nil {
  48. t.Fatal(err)
  49. }
  50. for _, tc := range testcases {
  51. _, err := os.Lstat(tc.file)
  52. if tc.shouldRemove && !os.IsNotExist(err) {
  53. t.Error(tc.file, "should have been removed")
  54. } else if !tc.shouldRemove && err != nil {
  55. t.Error(tc.file, "should not have been removed")
  56. }
  57. }
  58. if _, err := os.Lstat("testdata/.stversions/remove"); !os.IsNotExist(err) {
  59. t.Error("empty directory should have been removed")
  60. }
  61. }