package imgcache import ( "errors" "testing" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/testutil" ) // counterValues holds the values of a cache's counters. type counterValues struct { hitCount int64 missCount int64 upstreamFetchCount int64 upstreamFetchBytes int64 transformCount int64 } // readCounters reads cache's counters. func readCounters(cache *Cache) counterValues { return counterValues{ hitCount: int64(testutil.ToFloat64(cache.cacheHits)), missCount: int64(testutil.ToFloat64(cache.cacheMisses)), upstreamFetchCount: int64(testutil.ToFloat64(cache.upstreamFetches)), upstreamFetchBytes: int64(testutil.ToFloat64(cache.upstreamFetchBytes)), transformCount: int64(testutil.ToFloat64(cache.transforms)), } } // TestNewCache_RegistersItsCountersOnItsRegistry checks that NewCache // registers the cache's counters on the registry it is given, under the // names README.md gives them. func TestNewCache_RegistersItsCountersOnItsRegistry(t *testing.T) { t.Parallel() registry := prometheus.NewRegistry() _, err := NewCache(evictionTestDB(t), CacheConfig{StateDir: t.TempDir()}, registry) if err != nil { t.Fatalf("NewCache() error = %v", err) } names := []string{ "pixa_cache_hits_total", "pixa_cache_misses_total", "pixa_upstream_fetches_total", "pixa_upstream_fetch_bytes_total", "pixa_transforms_total", } count, err := testutil.GatherAndCount(registry, names...) if err != nil { t.Fatalf("testutil.GatherAndCount() error = %v", err) } if count != len(names) { t.Errorf("%d of the counters %v are on the registry, want %d", count, names, len(names)) } } // TestNewCache_FailsWhenItsCountersCannotBeRegistered makes a second cache // on the registry of a first. Its counters have the same names, so the // registry refuses them, and NewCache must return that error. func TestNewCache_FailsWhenItsCountersCannotBeRegistered(t *testing.T) { t.Parallel() registry := prometheus.NewRegistry() _, err := NewCache(evictionTestDB(t), CacheConfig{StateDir: t.TempDir()}, registry) if err != nil { t.Fatalf("NewCache() of the first cache error = %v", err) } _, err = NewCache(evictionTestDB(t), CacheConfig{StateDir: t.TempDir()}, registry) t.Logf("NewCache() of the second cache error = %v", err) var alreadyRegistered prometheus.AlreadyRegisteredError if !errors.As(err, &alreadyRegistered) { t.Errorf("NewCache() of the second cache error = %v, want %T", err, alreadyRegistered) } }