distcache_test.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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"} // add redis, memcache, memory
  23. for _, v := range clients {
  24. client := createTestClient(t, v)
  25. CanPutGetAndDeleteCachedObjects(t, v, client)
  26. CanNotFetchExpiredItems(t, v, client)
  27. CanSetInfiniteCacheExpiration(t, v, client)
  28. }
  29. }
  30. func CanPutGetAndDeleteCachedObjects(t *testing.T, name string, 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, name string, client cacheStorage) {
  45. if name == "redis" {
  46. t.Skip() //this test does not work with redis since it uses its own getTime fn
  47. }
  48. cacheableStruct := CacheableStruct{String: "hej", Int64: 2000}
  49. // insert cache item one day back
  50. getTime = func() time.Time { return time.Now().AddDate(0, 0, -2) }
  51. err := client.Put("key", cacheableStruct, 10000*time.Second)
  52. assert.Equal(t, err, nil)
  53. // should not be able to read that value since its expired
  54. getTime = time.Now
  55. _, err = client.Get("key")
  56. assert.Equal(t, err, ErrCacheItemNotFound)
  57. }
  58. func CanSetInfiniteCacheExpiration(t *testing.T, name string, client cacheStorage) {
  59. cacheableStruct := CacheableStruct{String: "hej", Int64: 2000}
  60. // insert cache item one day back
  61. getTime = func() time.Time { return time.Now().AddDate(0, 0, -2) }
  62. err := client.Put("key", cacheableStruct, 0)
  63. assert.Equal(t, err, nil)
  64. // should not be able to read that value since its expired
  65. getTime = time.Now
  66. data, err := client.Get("key")
  67. s, ok := data.(CacheableStruct)
  68. assert.Equal(t, ok, true)
  69. assert.Equal(t, s.String, "hej")
  70. assert.Equal(t, s.Int64, int64(2000))
  71. }