remotecache_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package remotecache
  2. import (
  3. "testing"
  4. "time"
  5. "github.com/grafana/grafana/pkg/services/sqlstore"
  6. "github.com/grafana/grafana/pkg/setting"
  7. "github.com/stretchr/testify/assert"
  8. )
  9. type CacheableStruct struct {
  10. String string
  11. Int64 int64
  12. }
  13. func init() {
  14. Register(CacheableStruct{})
  15. }
  16. func createTestClient(t *testing.T, opts *setting.RemoteCacheOptions, sqlstore *sqlstore.SqlStore) CacheStorage {
  17. t.Helper()
  18. dc := &RemoteCache{
  19. SQLStore: sqlstore,
  20. Cfg: &setting.Cfg{
  21. RemoteCacheOptions: opts,
  22. },
  23. }
  24. err := dc.Init()
  25. if err != nil {
  26. t.Fatalf("failed to init client for test. error: %v", err)
  27. }
  28. return dc
  29. }
  30. func TestCachedBasedOnConfig(t *testing.T) {
  31. cfg := setting.NewCfg()
  32. cfg.Load(&setting.CommandLineArgs{
  33. HomePath: "../../../",
  34. })
  35. client := createTestClient(t, cfg.RemoteCacheOptions, sqlstore.InitTestDB(t))
  36. runTestsForClient(t, client)
  37. }
  38. func TestInvalidCacheTypeReturnsError(t *testing.T) {
  39. _, err := createClient(&setting.RemoteCacheOptions{Name: "invalid"}, nil)
  40. assert.Equal(t, err, ErrInvalidCacheType)
  41. }
  42. func runTestsForClient(t *testing.T, client CacheStorage) {
  43. canPutGetAndDeleteCachedObjects(t, client)
  44. canNotFetchExpiredItems(t, client)
  45. }
  46. func canPutGetAndDeleteCachedObjects(t *testing.T, client CacheStorage) {
  47. cacheableStruct := CacheableStruct{String: "hej", Int64: 2000}
  48. err := client.Set("key1", cacheableStruct, 0)
  49. assert.Equal(t, err, nil, "expected nil. got: ", err)
  50. data, err := client.Get("key1")
  51. assert.Equal(t, err, nil)
  52. s, ok := data.(CacheableStruct)
  53. assert.Equal(t, ok, true)
  54. assert.Equal(t, s.String, "hej")
  55. assert.Equal(t, s.Int64, int64(2000))
  56. err = client.Delete("key1")
  57. assert.Equal(t, err, nil)
  58. _, err = client.Get("key1")
  59. assert.Equal(t, err, ErrCacheItemNotFound)
  60. }
  61. func canNotFetchExpiredItems(t *testing.T, client CacheStorage) {
  62. cacheableStruct := CacheableStruct{String: "hej", Int64: 2000}
  63. err := client.Set("key1", cacheableStruct, time.Second)
  64. assert.Equal(t, err, nil)
  65. //not sure how this can be avoided when testing redis/memcached :/
  66. <-time.After(time.Second + time.Millisecond)
  67. // should not be able to read that value since its expired
  68. _, err = client.Get("key1")
  69. assert.Equal(t, err, ErrCacheItemNotFound)
  70. }