cache_test.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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 ibm
  13. import (
  14. "testing"
  15. "time"
  16. "github.com/stretchr/testify/assert"
  17. )
  18. const maxEntries = 10
  19. func dataCache(t *testing.T, ttl time.Duration, maxEntries int) cacheIntf {
  20. t.Helper()
  21. return NewCache(maxEntries, ttl)
  22. }
  23. func TestGetData(t *testing.T) {
  24. tests := []struct {
  25. name string
  26. ttl time.Duration
  27. key string
  28. value []byte
  29. wantValue []byte
  30. wantFound bool
  31. }{
  32. {
  33. name: "object exists in cache and has not expired",
  34. ttl: 30 * time.Second,
  35. key: "testObject",
  36. value: []byte("testValue"),
  37. wantValue: []byte("testValue"),
  38. wantFound: true,
  39. },
  40. {
  41. name: "object exists in cache and will never expire",
  42. ttl: 0 * time.Second,
  43. key: "testObject",
  44. value: []byte("testValue"),
  45. wantValue: []byte("testValue"),
  46. wantFound: true,
  47. },
  48. {
  49. name: "object exists in cache but has expired",
  50. ttl: 1 * time.Nanosecond,
  51. key: "testObject",
  52. value: []byte("testValue"),
  53. wantFound: false,
  54. },
  55. {
  56. name: "object not in cache",
  57. ttl: 30 * time.Second,
  58. key: "testObject",
  59. wantFound: false,
  60. },
  61. }
  62. for _, tt := range tests {
  63. t.Run(tt.name, func(t *testing.T) {
  64. c := NewCache(10, tt.ttl)
  65. if tt.value != nil {
  66. c.PutData(tt.key, tt.value)
  67. }
  68. gotFound, gotValue := c.GetData(tt.key)
  69. assert.Equal(t, tt.wantFound, gotFound)
  70. assert.Equal(t, string(gotValue), string(tt.wantValue))
  71. })
  72. }
  73. }
  74. func TestPutData(t *testing.T) {
  75. t.Parallel()
  76. d := dataCache(t, time.Minute, maxEntries)
  77. d.PutData("test-key", []byte("test-value"))
  78. }
  79. func TestDeleteData(t *testing.T) {
  80. t.Parallel()
  81. d := dataCache(t, time.Minute, maxEntries)
  82. d.DeleteData("test-key")
  83. }