cache_test.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package hashcache
  15. import (
  16. "testing"
  17. "time"
  18. )
  19. func TestCache(t *testing.T) {
  20. c := NewCache(1024, time.Second)
  21. c.Set("123", 123)
  22. c.Set("456", 456)
  23. v := c.Get("123")
  24. if v == nil || v.(int) != 123 {
  25. t.Error("Key 123 not found")
  26. }
  27. v = c.Get("456")
  28. if v == nil || v.(int) != 456 {
  29. t.Error("Key 456 not found")
  30. }
  31. c.Set("456", 789)
  32. v = c.Get("456")
  33. if v == nil || v.(int) != 789 {
  34. t.Error("Key 456 not changed")
  35. }
  36. time.Sleep(time.Second)
  37. v = c.Get("123")
  38. if v != nil {
  39. t.Errorf("key 123 shoud expire")
  40. }
  41. c.Set("123", 1234)
  42. c.Set("456", 4567)
  43. v = c.Get("123")
  44. if v == nil || v.(int) != 1234 {
  45. t.Error("Key 123 not found")
  46. }
  47. v = c.Get("456")
  48. if v == nil || v.(int) != 4567 {
  49. t.Error("Key 456 not found")
  50. }
  51. time.Sleep(time.Second)
  52. v = c.Get("123")
  53. if v != nil {
  54. t.Errorf("key 123 shoud expire")
  55. }
  56. c.Set("123", 1234)
  57. v = c.Get("123")
  58. if v == nil || v.(int) != 1234 {
  59. t.Error("Key 123 not found")
  60. }
  61. c.Invalidate()
  62. v = c.Get("123")
  63. if v != nil {
  64. t.Error("Key 123 should not found")
  65. }
  66. }