|
| 1 | +package ristretto_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "testing" |
| 6 | + "time" |
| 7 | + |
| 8 | + rist "github.com/dgraph-io/ristretto" |
| 9 | + "github.com/rocketlaunchr/remember-go" |
| 10 | + "github.com/rocketlaunchr/remember-go/ristretto" |
| 11 | +) |
| 12 | + |
| 13 | +var cfg = &rist.Config{ |
| 14 | + NumCounters: 1e7, // number of keys to track frequency of (10M). |
| 15 | + MaxCost: 1 << 30, // maximum cost of cache (1GB). |
| 16 | + BufferItems: 64, // number of keys per Get buffer. |
| 17 | +} |
| 18 | + |
| 19 | +func TestKeyBasicOperation(t *testing.T) { |
| 20 | + ctx := context.Background() |
| 21 | + var ms = ristretto.NewRistrettoStore(cfg) |
| 22 | + |
| 23 | + key := "key" |
| 24 | + exp := 10 * time.Minute |
| 25 | + |
| 26 | + slowQuery := func(ctx context.Context) (interface{}, error) { |
| 27 | + return "val", nil |
| 28 | + } |
| 29 | + |
| 30 | + actual, _, _ := remember.Cache(ctx, ms, key, exp, slowQuery) |
| 31 | + |
| 32 | + expected := "val" |
| 33 | + |
| 34 | + if actual.(string) != expected { |
| 35 | + t.Errorf("wrong val: expected: %v actual: %v", expected, actual) |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +func TestFetchFromCacheAndDisableCache(t *testing.T) { |
| 40 | + ctx := context.Background() |
| 41 | + var ms = ristretto.NewRistrettoStore(cfg) |
| 42 | + |
| 43 | + key := "key" |
| 44 | + exp := 10 * time.Minute |
| 45 | + |
| 46 | + slowQuery := func(ctx context.Context) (interface{}, error) { |
| 47 | + return "val", nil |
| 48 | + } |
| 49 | + |
| 50 | + // warm up cache |
| 51 | + remember.Cache(ctx, ms, key, exp, slowQuery) |
| 52 | + |
| 53 | + // This time fetch from cache |
| 54 | + actual, _, _ := remember.Cache(ctx, ms, key, exp, slowQuery) |
| 55 | + |
| 56 | + expected := "val" |
| 57 | + |
| 58 | + if actual.(string) != expected { |
| 59 | + t.Errorf("wrong val: expected: %v actual: %v", expected, actual) |
| 60 | + } |
| 61 | + |
| 62 | + // Actual is now "val", Let's change it to "val2" and disable cache usage. |
| 63 | + |
| 64 | + slowQuery = func(ctx context.Context) (interface{}, error) { |
| 65 | + return "val2", nil |
| 66 | + } |
| 67 | + |
| 68 | + actual, _, _ = remember.Cache(ctx, ms, key, exp, slowQuery, remember.Options{DisableCacheUsage: true}) |
| 69 | + |
| 70 | + expected = "val2" |
| 71 | + |
| 72 | + if actual.(string) != expected { |
| 73 | + t.Errorf("wrong val: expected: %v actual: %v", expected, actual) |
| 74 | + } |
| 75 | +} |
0 commit comments