From d9499dfec51f7a2d2ea02d73a4ce94a628bb24cb Mon Sep 17 00:00:00 2001 From: Ananya Kumar Mallik Date: Tue, 3 Dec 2024 13:58:49 +0000 Subject: [PATCH] Add collector cache test Signed-off-by: Ananya Kumar Mallik --- collectors/cache_test.go | 53 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/collectors/cache_test.go b/collectors/cache_test.go index 7164baff..3be2eecc 100644 --- a/collectors/cache_test.go +++ b/collectors/cache_test.go @@ -74,3 +74,56 @@ func TestDescriptorCache(t *testing.T) { t.Error("cache entries should have expired") } } + +func TestCollectorCache(t *testing.T) { + createCollector := func(id string) *MonitoringCollector { + return &MonitoringCollector{ + projectID: id, + } + } + + t.Run("basic cache Op", func(t *testing.T) { + ttl := 1 * time.Second + cache := NewCollectorCache(ttl) + collector := createCollector("test-project") + key := "test-key" + + cache.Store(key, collector) + + if _, found := cache.Get("test-key"); !found { + t.Error("Collector should be available in cache before TTL") + } + + time.Sleep(2 * ttl) + if _, found := cache.Get("test-key"); found { + t.Error("Collector should have expired") + } + }) + + t.Run("multiple collectors", func(t *testing.T) { + ttl := 1 * time.Second + cache := NewCollectorCache(ttl) + + collectors := map[string]*MonitoringCollector{ + "test-key-1": createCollector("test-project-1"), + "test-key-2": createCollector("test-project-2"), + "test-key-3": createCollector("test-project-3"), + } + + for k, v := range collectors { + cache.Store(k, v) + } + + for k, original := range collectors { + cached, found := cache.Get(k) + if !found { + t.Errorf("Collector %s not found in cache", k) + continue + } + + if cached.projectID != original.projectID { + t.Errorf("Wrong collector for key %s. Got projectId %s, want %s", k, cached.projectID, original.projectID) + } + } + }) +}