trashcan_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. )
  14. func TestTrashcanCleanout(t *testing.T) {
  15. // Verify that files older than the cutoff are removed, that files newer
  16. // than the cutoff are *not* removed, and that empty directories are
  17. // removed (best effort).
  18. var testcases = []struct {
  19. file string
  20. shouldRemove bool
  21. }{
  22. {"testdata/.stversions/file1", false},
  23. {"testdata/.stversions/file2", true},
  24. {"testdata/.stversions/keep1/file1", false},
  25. {"testdata/.stversions/keep1/file2", false},
  26. {"testdata/.stversions/keep2/file1", false},
  27. {"testdata/.stversions/keep2/file2", true},
  28. {"testdata/.stversions/remove/file1", true},
  29. {"testdata/.stversions/remove/file2", true},
  30. }
  31. os.RemoveAll("testdata")
  32. defer os.RemoveAll("testdata")
  33. oldTime := time.Now().Add(-8 * 24 * time.Hour)
  34. for _, tc := range testcases {
  35. os.MkdirAll(filepath.Dir(tc.file), 0777)
  36. if err := ioutil.WriteFile(tc.file, []byte("data"), 0644); err != nil {
  37. t.Fatal(err)
  38. }
  39. if tc.shouldRemove {
  40. if err := os.Chtimes(tc.file, oldTime, oldTime); err != nil {
  41. t.Fatal(err)
  42. }
  43. }
  44. }
  45. versioner := NewTrashcan("default", "testdata", map[string]string{"cleanoutDays": "7"}).(*Trashcan)
  46. if err := versioner.cleanoutArchive(); err != nil {
  47. t.Fatal(err)
  48. }
  49. for _, tc := range testcases {
  50. _, err := os.Lstat(tc.file)
  51. if tc.shouldRemove && !os.IsNotExist(err) {
  52. t.Error(tc.file, "should have been removed")
  53. } else if !tc.shouldRemove && err != nil {
  54. t.Error(tc.file, "should not have been removed")
  55. }
  56. }
  57. if _, err := os.Lstat("testdata/.stversions/remove"); !os.IsNotExist(err) {
  58. t.Error("empty directory should have been removed")
  59. }
  60. }