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() // Test Get with loader callCount := 0 loader := func() (interface{}, time.Time, error) { callCount++ return "test-token", time.Now().Add(time.Hour), nil } // First call should invoke loader 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) } // Second call should hit cache 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() // Add token cache.Set("test", "key1", "token-value", time.Now().Add(time.Hour)) // Verify it's cached 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) } // Invalidate cache.Invalidate("test", "key1") // Verify it's gone _, 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 } // Generate some hits and misses cache.Get("test", "key1", loader) // miss cache.Get("test", "key1", loader) // hit cache.Get("test", "key1", loader) // hit cache.Get("test", "key2", loader) // miss 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) } }