distcache_test.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package distcache
  2. import (
  3. "encoding/gob"
  4. "testing"
  5. "time"
  6. "github.com/bmizerany/assert"
  7. "github.com/grafana/grafana/pkg/services/sqlstore"
  8. )
  9. type CacheableStruct struct {
  10. String string
  11. Int64 int64
  12. }
  13. func init() {
  14. gob.Register(CacheableStruct{})
  15. }
  16. func createTestClient(t *testing.T, name string) cacheStorage {
  17. t.Helper()
  18. sqlstore := sqlstore.InitTestDB(t)
  19. return createClient(CacheOpts{name: name}, sqlstore)
  20. }
  21. func TestAllCacheClients(t *testing.T) {
  22. clients := []string{"memory"} // add redis, memcache, memory
  23. for _, v := range clients {
  24. client := createTestClient(t, v)
  25. CanPutGetAndDeleteCachedObjects(t, client)
  26. CanNotFetchExpiredItems(t, client)
  27. CanSetInfiniteCacheExpiration(t, client)
  28. }
  29. }
  30. func CanPutGetAndDeleteCachedObjects(t *testing.T, client cacheStorage) {
  31. cacheableStruct := CacheableStruct{String: "hej", Int64: 2000}
  32. err := client.Put("key", cacheableStruct, 0)
  33. assert.Equal(t, err, nil)
  34. data, err := client.Get("key")
  35. s, ok := data.(CacheableStruct)
  36. assert.Equal(t, ok, true)
  37. assert.Equal(t, s.String, "hej")
  38. assert.Equal(t, s.Int64, int64(2000))
  39. err = client.Delete("key")
  40. assert.Equal(t, err, nil)
  41. _, err = client.Get("key")
  42. assert.Equal(t, err, ErrCacheItemNotFound)
  43. }
  44. func CanNotFetchExpiredItems(t *testing.T, client cacheStorage) {
  45. cacheableStruct := CacheableStruct{String: "hej", Int64: 2000}
  46. err := client.Put("key", cacheableStruct, time.Second)
  47. assert.Equal(t, err, nil)
  48. //not sure how this can be avoided when testing redis/memcached :/
  49. <-time.After(time.Second + time.Millisecond)
  50. // should not be able to read that value since its expired
  51. _, err = client.Get("key")
  52. assert.Equal(t, err, ErrCacheItemNotFound)
  53. }
  54. func CanSetInfiniteCacheExpiration(t *testing.T, client cacheStorage) {
  55. cacheableStruct := CacheableStruct{String: "hej", Int64: 2000}
  56. // insert cache item one day back
  57. getTime = func() time.Time { return time.Now().AddDate(0, 0, -2) }
  58. err := client.Put("key", cacheableStruct, 0)
  59. assert.Equal(t, err, nil)
  60. // should not be able to read that value since its expired
  61. getTime = time.Now
  62. data, err := client.Get("key")
  63. s, ok := data.(CacheableStruct)
  64. assert.Equal(t, ok, true)
  65. assert.Equal(t, s.String, "hej")
  66. assert.Equal(t, s.Int64, int64(2000))
  67. }