Files
geo/server/internal/shared/cache/readthrough_test.go
T

64 lines
1.7 KiB
Go
Raw Normal View History

package cache
import (
"context"
"testing"
"time"
"golang.org/x/sync/singleflight"
)
func TestLoadJSONWithEmptyCachesEmptyAndRecordsMetrics(t *testing.T) {
ResetMetricsForTest()
ctx := context.Background()
c := NewWithOptions("memory", nil, Options{
Namespace: "test",
JitterRatio: 0,
MetricsEnabled: true,
})
var group singleflight.Group
loads := 0
value, found, err := LoadJSONWithEmpty(ctx, c, &group, "empty", time.Minute, time.Minute, func(context.Context) (string, bool, error) {
loads++
return "", false, nil
})
if err != nil {
t.Fatalf("LoadJSONWithEmpty() error = %v", err)
}
if found || value != "" {
t.Fatalf("first load value=%q found=%v, want empty not found", value, found)
}
value, found, err = LoadJSONWithEmpty(ctx, c, &group, "empty", time.Minute, time.Minute, func(context.Context) (string, bool, error) {
loads++
return "unexpected", true, nil
})
if err != nil {
t.Fatalf("LoadJSONWithEmpty() cached error = %v", err)
}
if found || value != "" {
t.Fatalf("cached value=%q found=%v, want empty not found", value, found)
}
if loads != 1 {
t.Fatalf("loader calls = %d, want 1", loads)
}
snapshot := MetricsSnapshotValue()
if metricCount(snapshot, "readthrough_empty", "hit") != 1 {
t.Fatalf("readthrough_empty hit metric missing in %#v", snapshot.Operations)
}
if metricCount(snapshot, "readthrough_load", "ok") != 1 {
t.Fatalf("readthrough_load ok metric missing in %#v", snapshot.Operations)
}
}
func metricCount(snapshot MetricsSnapshot, operation, result string) int64 {
for _, item := range snapshot.Operations {
if item.Operation == operation && item.Result == result {
return item.Count
}
}
return 0
}