cache_test.go 2.1 KB

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