| package token |
|
|
| import ( |
| "testing" |
| "time" |
| ) |
|
|
| func TestCache_GetSet(t *testing.T) { |
| config := &Config{ |
| Enabled: true, |
| RefreshBeforeSeconds: 60, |
| CleanupIntervalSeconds: 10, |
| } |
|
|
| cache := NewCache(config) |
| if cache == nil { |
| t.Fatal("expected cache to be created") |
| } |
| defer cache.Close() |
|
|
| |
| callCount := 0 |
| loader := func() (interface{}, time.Time, error) { |
| callCount++ |
| return "test-token", time.Now().Add(time.Hour), nil |
| } |
|
|
| |
| token, err := cache.Get("test", "key1", loader) |
| if err != nil { |
| t.Fatalf("Get failed: %v", err) |
| } |
| if token != "test-token" { |
| t.Errorf("expected test-token, got %v", token) |
| } |
| if callCount != 1 { |
| t.Errorf("expected loader to be called once, called %d times", callCount) |
| } |
|
|
| |
| token, err = cache.Get("test", "key1", loader) |
| if err != nil { |
| t.Fatalf("Get failed: %v", err) |
| } |
| if callCount != 1 { |
| t.Errorf("expected loader to not be called again, called %d times", callCount) |
| } |
| } |
|
|
| func TestCache_Disabled(t *testing.T) { |
| config := &Config{ |
| Enabled: false, |
| } |
|
|
| cache := NewCache(config) |
| if cache != nil { |
| t.Error("expected nil cache when disabled") |
| } |
| } |
|
|
| func TestCache_Invalidate(t *testing.T) { |
| config := &Config{ |
| Enabled: true, |
| RefreshBeforeSeconds: 60, |
| CleanupIntervalSeconds: 10, |
| } |
|
|
| cache := NewCache(config) |
| defer cache.Close() |
|
|
| |
| cache.Set("test", "key1", "token-value", time.Now().Add(time.Hour)) |
|
|
| |
| token, found := cache.GetCached("test", "key1") |
| if !found { |
| t.Error("expected token to be found") |
| } |
| if token != "token-value" { |
| t.Errorf("expected token-value, got %v", token) |
| } |
|
|
| |
| cache.Invalidate("test", "key1") |
|
|
| |
| _, found = cache.GetCached("test", "key1") |
| if found { |
| t.Error("expected token to be invalidated") |
| } |
| } |
|
|
| func TestCache_Stats(t *testing.T) { |
| config := &Config{ |
| Enabled: true, |
| RefreshBeforeSeconds: 60, |
| CleanupIntervalSeconds: 10, |
| } |
|
|
| cache := NewCache(config) |
| defer cache.Close() |
|
|
| loader := func() (interface{}, time.Time, error) { |
| return "token", time.Now().Add(time.Hour), nil |
| } |
|
|
| |
| cache.Get("test", "key1", loader) |
| cache.Get("test", "key1", loader) |
| cache.Get("test", "key1", loader) |
| cache.Get("test", "key2", loader) |
|
|
| hits, misses, count := cache.Stats() |
| if hits != 2 { |
| t.Errorf("expected 2 hits, got %d", hits) |
| } |
| if misses != 2 { |
| t.Errorf("expected 2 misses, got %d", misses) |
| } |
| if count != 2 { |
| t.Errorf("expected 2 entries, got %d", count) |
| } |
| } |
|
|