distcache_test.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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{"database", "redis", "memcache"} // add redis, memcache, memory
  23. clients := []string{} // add redis, memcache, memory
  24. for _, v := range clients {
  25. client := createTestClient(t, v)
  26. CanPutGetAndDeleteCachedObjects(t, client)
  27. CanNotFetchExpiredItems(t, client)
  28. CanSetInfiniteCacheExpiration(t, client)
  29. }
  30. }
  31. func CanPutGetAndDeleteCachedObjects(t *testing.T, client cacheStorage) {
  32. cacheableStruct := CacheableStruct{String: "hej", Int64: 2000}
  33. err := client.Put("key", cacheableStruct, 0)
  34. assert.Equal(t, err, nil)
  35. data, err := client.Get("key")
  36. s, ok := data.(CacheableStruct)
  37. assert.Equal(t, ok, true)
  38. assert.Equal(t, s.String, "hej")
  39. assert.Equal(t, s.Int64, int64(2000))
  40. err = client.Delete("key")
  41. assert.Equal(t, err, nil)
  42. _, err = client.Get("key")
  43. assert.Equal(t, err, ErrCacheItemNotFound)
  44. }
  45. func CanNotFetchExpiredItems(t *testing.T, client cacheStorage) {
  46. cacheableStruct := CacheableStruct{String: "hej", Int64: 2000}
  47. err := client.Put("key", cacheableStruct, time.Second)
  48. assert.Equal(t, err, nil)
  49. //not sure how this can be avoided when testing redis/memcached :/
  50. <-time.After(time.Second + time.Millisecond)
  51. // should not be able to read that value since its expired
  52. _, err = client.Get("key")
  53. assert.Equal(t, err, ErrCacheItemNotFound)
  54. }
  55. func CanSetInfiniteCacheExpiration(t *testing.T, client cacheStorage) {
  56. cacheableStruct := CacheableStruct{String: "hej", Int64: 2000}
  57. // insert cache item one day back
  58. getTime = func() time.Time { return time.Now().AddDate(0, 0, -2) }
  59. err := client.Put("key", cacheableStruct, 0)
  60. assert.Equal(t, err, nil)
  61. // should not be able to read that value since its expired
  62. getTime = time.Now
  63. data, err := client.Get("key")
  64. s, ok := data.(CacheableStruct)
  65. assert.Equal(t, ok, true)
  66. assert.Equal(t, s.String, "hej")
  67. assert.Equal(t, s.Int64, int64(2000))
  68. }