cache_test.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // Copyright (C) 2014 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 ignore
  7. import (
  8. "testing"
  9. "time"
  10. "github.com/syncthing/syncthing/lib/ignore/ignoreresult"
  11. )
  12. func TestCache(t *testing.T) {
  13. fc := new(fakeClock)
  14. oldClock := clock
  15. clock = fc
  16. defer func() {
  17. clock = oldClock
  18. }()
  19. c := newCache()
  20. res, ok := c.get("nonexistent")
  21. if res.IsIgnored() || res.IsDeletable() || ok {
  22. t.Errorf("res %v, ok %v for nonexistent item", res, ok)
  23. }
  24. // Set and check some items
  25. c.set("true", ignoreresult.IgnoredDeletable)
  26. c.set("false", 0)
  27. res, ok = c.get("true")
  28. if !res.IsIgnored() || !res.IsDeletable() || !ok {
  29. t.Errorf("res %v, ok %v for true item", res, ok)
  30. }
  31. res, ok = c.get("false")
  32. if res.IsIgnored() || res.IsDeletable() || !ok {
  33. t.Errorf("res %v, ok %v for false item", res, ok)
  34. }
  35. // Don't clean anything
  36. c.clean(time.Second)
  37. // Same values should exist
  38. res, ok = c.get("true")
  39. if !res.IsIgnored() || !res.IsDeletable() || !ok {
  40. t.Errorf("res %v, ok %v for true item", res, ok)
  41. }
  42. res, ok = c.get("false")
  43. if res.IsIgnored() || res.IsDeletable() || !ok {
  44. t.Errorf("res %v, ok %v for false item", res, ok)
  45. }
  46. // Sleep and access, to get some data for clean
  47. *fc += 500 // milliseconds
  48. c.get("true")
  49. *fc += 100 // milliseconds
  50. // "false" was accessed ~600 ms ago, "true" was accessed ~100 ms ago.
  51. // This should clean out "false" but not "true"
  52. c.clean(300 * time.Millisecond)
  53. // Same values should exist
  54. _, ok = c.get("true")
  55. if !ok {
  56. t.Error("item should still exist")
  57. }
  58. _, ok = c.get("false")
  59. if ok {
  60. t.Errorf("item should have been cleaned")
  61. }
  62. }
  63. type fakeClock int64 // milliseconds
  64. func (f *fakeClock) Now() time.Time {
  65. t := time.Unix(int64(*f)/1000, (int64(*f)%1000)*int64(time.Millisecond))
  66. *f++
  67. return t
  68. }