cache_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /*
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. */
  12. package cache
  13. import (
  14. "testing"
  15. "github.com/stretchr/testify/assert"
  16. )
  17. type client struct{}
  18. var cacheKey = Key{Name: "foo"}
  19. func TestCacheAdd(t *testing.T) {
  20. c, err := New[client](1, nil)
  21. if err != nil {
  22. t.Fail()
  23. }
  24. cl := client{}
  25. c.Add("", cacheKey, cl)
  26. cachedVal, _ := c.Get("", cacheKey)
  27. assert.EqualValues(t, cl, cachedVal)
  28. }
  29. func TestCacheContains(t *testing.T) {
  30. c, err := New[client](1, nil)
  31. if err != nil {
  32. t.Fail()
  33. }
  34. cl := client{}
  35. c.Add("", cacheKey, cl)
  36. exists := c.Contains(cacheKey)
  37. notExists := c.Contains(Key{Name: "does not exist"})
  38. assert.True(t, exists)
  39. assert.False(t, notExists)
  40. assert.Nil(t, err)
  41. }
  42. func TestCacheGet(t *testing.T) {
  43. c, err := New[*client](1, nil)
  44. if err != nil {
  45. t.Fail()
  46. }
  47. cachedVal, ok := c.Get("", cacheKey)
  48. assert.Nil(t, cachedVal)
  49. assert.False(t, ok)
  50. }
  51. func TestCacheGetInvalidVersion(t *testing.T) {
  52. var cleanupCalled bool
  53. c, err := New(1, func(client *client) {
  54. cleanupCalled = true
  55. })
  56. if err != nil {
  57. t.Fail()
  58. }
  59. cl := &client{}
  60. c.Add("", cacheKey, cl)
  61. cachedVal, ok := c.Get("invalid", cacheKey)
  62. assert.Nil(t, cachedVal)
  63. assert.False(t, ok)
  64. assert.True(t, cleanupCalled)
  65. }
  66. func TestCacheEvict(t *testing.T) {
  67. var cleanupCalled bool
  68. c, err := New(1, func(client client) {
  69. cleanupCalled = true
  70. })
  71. if err != nil {
  72. t.Fail()
  73. }
  74. // add first version
  75. c.Add("", Key{Name: "foo"}, client{})
  76. assert.False(t, cleanupCalled)
  77. // adding a second version should evict old one
  78. c.Add("", Key{Name: "bar"}, client{})
  79. assert.True(t, cleanupCalled)
  80. }