Extend cache interface (#1318)

* Extend cache interface.

* update test.
This commit is contained in:
ahrav 2023-05-03 08:21:00 -07:00 committed by GitHub
parent 714c480931
commit 9cb91a6e4f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 43 additions and 3 deletions

4
pkg/cache/cache.go vendored
View file

@ -15,6 +15,10 @@ type Cache interface {
Clear()
// Count the number of key/value pairs in the cache.
Count() int
// Keys returns all keys in the cache.
Keys() []string
// Values returns all values in the cache.
Values() []string
// Contents returns all keys in the cache encoded as a string.
Contents() string
}

View file

@ -74,6 +74,26 @@ func (c *Cache) Count() int {
return c.c.ItemCount()
}
// Keys returns all keys in the cache.
func (c *Cache) Keys() []string {
items := c.c.Items()
res := make([]string, 0, len(items))
for k := range items {
res = append(res, k)
}
return res
}
// Values returns all values in the cache.
func (c *Cache) Values() []string {
items := c.c.Items()
res := make([]string, 0, len(items))
for _, v := range items {
res = append(res, v.Object.(string))
}
return res
}
// Contents returns all key-value pairs in the cache encodes as a string.
func (c *Cache) Contents() string {
items := c.c.Items()

View file

@ -46,12 +46,28 @@ func TestCache(t *testing.T) {
t.Fatalf("Unexpected value for key10 after clear: %v, %v", v, ok)
}
// Test contents.
// Test getting only the keys.
keys := []string{"key1", "key2", "key3"}
for _, k := range keys {
c.Set(k, k)
values := []string{"value1", "value2", "value3"}
for i, k := range keys {
c.Set(k, values[i])
}
k := c.Keys()
sort.Strings(keys)
sort.Strings(k)
if !cmp.Equal(keys, k) {
t.Fatalf("Unexpected keys: %v", k)
}
// Test getting only the values.
vals := c.Values()
sort.Strings(vals)
sort.Strings(values)
if !cmp.Equal(values, vals) {
t.Fatalf("Unexpected values: %v", vals)
}
// Test contents.
items := c.Contents()
sort.Strings(keys)
res := strings.Split(items, ",")