Skip to content

Commit 71ca070

Browse files
Add tests for TTLCache.GetOrCreate with maxSize <= 0
Cover the uncovered branch where maxSize is zero or negative causes GetOrCreate to bypass the cache entirely and call create() on every invocation. This brings syncutil package coverage from 97.7% to 100%. The passthrough-cache behaviour (maxSize <= 0) is a deliberate design choice that lets callers disable caching without changing call-sites. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent a5b5c18 commit 71ca070

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

internal/syncutil/ttl_cache_test.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,44 @@ func TestTTLCache_ConcurrentAccess(t *testing.T) {
207207
assert.LessOrEqual(t, createCount.Load(), int32(10), "at most 10 unique keys")
208208
}
209209

210+
// TestTTLCache_GetOrCreate_MaxSizeZeroOrNegativeBypassesCache verifies that
211+
// when maxSize is zero or negative every GetOrCreate call invokes create()
212+
// directly without caching the result, and Len() always reports zero entries.
213+
//
214+
// A maxSize <= 0 cache is intentionally a passthrough: useful for testing code
215+
// that accepts a *TTLCache or for runtime-disabling the cache without changing
216+
// call-sites.
217+
func TestTTLCache_GetOrCreate_MaxSizeZeroOrNegativeBypassesCache(t *testing.T) {
218+
tests := []struct {
219+
name string
220+
maxSize int
221+
}{
222+
{name: "zero disables cache", maxSize: 0},
223+
{name: "negative one disables cache", maxSize: -1},
224+
{name: "large negative disables cache", maxSize: -100},
225+
}
226+
227+
for _, tt := range tests {
228+
t.Run(tt.name, func(t *testing.T) {
229+
cache := NewTTLCache[string, int](time.Hour, tt.maxSize)
230+
231+
createCount := 0
232+
233+
// First call: create must be invoked.
234+
first := cache.GetOrCreate("key", func() int { createCount++; return 42 })
235+
assert.Equal(t, 42, first)
236+
assert.Equal(t, 1, createCount, "create should be called on first access")
237+
assert.Equal(t, 0, cache.Len(), "nothing should be stored when maxSize <= 0")
238+
239+
// Second call with the same key: create must be invoked again (no caching).
240+
second := cache.GetOrCreate("key", func() int { createCount++; return 99 })
241+
assert.Equal(t, 99, second, "second call should return the new value (not a cached result)")
242+
assert.Equal(t, 2, createCount, "create should be called on every access when maxSize <= 0")
243+
assert.Equal(t, 0, cache.Len(), "cache must remain empty after second access")
244+
})
245+
}
246+
}
247+
210248
// TestTTLCache_MaxSizeOne verifies edge behaviour when maxSize is 1.
211249
func TestTTLCache_MaxSizeOne(t *testing.T) {
212250
clk := newFakeClock()

0 commit comments

Comments
 (0)