cache_test.go 1.9 KB

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