distcache_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package distcache
  2. import (
  3. "encoding/gob"
  4. "testing"
  5. "time"
  6. "github.com/bmizerany/assert"
  7. "github.com/grafana/grafana/pkg/log"
  8. "github.com/grafana/grafana/pkg/services/sqlstore"
  9. )
  10. type CacheableStruct struct {
  11. String string
  12. Int64 int64
  13. }
  14. func init() {
  15. gob.Register(CacheableStruct{})
  16. }
  17. func createClient(t *testing.T) cacheStorage {
  18. t.Helper()
  19. sqlstore := sqlstore.InitTestDB(t)
  20. dc := DistributedCache{log: log.New("test.logger"), SQLStore: sqlstore}
  21. dc.Init()
  22. return dc.Client
  23. }
  24. func TestCanPutIntoDatabaseStorage(t *testing.T) {
  25. client := createClient(t)
  26. cacheableStruct := CacheableStruct{String: "hej", Int64: 2000}
  27. err := client.Put("key", cacheableStruct, 1000)
  28. assert.Equal(t, err, nil)
  29. data, err := client.Get("key")
  30. s, ok := data.(CacheableStruct)
  31. assert.Equal(t, ok, true)
  32. assert.Equal(t, s.String, "hej")
  33. assert.Equal(t, s.Int64, int64(2000))
  34. err = client.Delete("key")
  35. assert.Equal(t, err, nil)
  36. _, err = client.Get("key")
  37. assert.Equal(t, err, ErrCacheItemNotFound)
  38. }
  39. func TestCanNotFetchExpiredItems(t *testing.T) {
  40. client := createClient(t)
  41. cacheableStruct := CacheableStruct{String: "hej", Int64: 2000}
  42. // insert cache item one day back
  43. getTime = func() time.Time { return time.Now().AddDate(0, 0, -2) }
  44. err := client.Put("key", cacheableStruct, 10000)
  45. assert.Equal(t, err, nil)
  46. // should not be able to read that value since its expired
  47. getTime = time.Now
  48. _, err = client.Get("key")
  49. assert.Equal(t, err, ErrCacheItemNotFound)
  50. }
  51. func TestCanSetInfiniteCacheExpiration(t *testing.T) {
  52. client := createClient(t)
  53. cacheableStruct := CacheableStruct{String: "hej", Int64: 2000}
  54. // insert cache item one day back
  55. getTime = func() time.Time { return time.Now().AddDate(0, 0, -2) }
  56. err := client.Put("key", cacheableStruct, 0)
  57. assert.Equal(t, err, nil)
  58. // should not be able to read that value since its expired
  59. getTime = time.Now
  60. data, err := client.Get("key")
  61. s, ok := data.(CacheableStruct)
  62. assert.Equal(t, ok, true)
  63. assert.Equal(t, s.String, "hej")
  64. assert.Equal(t, s.Int64, int64(2000))
  65. }