Skip to content

Commit f567a86

Browse files
authored
Merge pull request #65 from nii236/main
2 parents 2601bb0 + 6298b34 commit f567a86

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

cache.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,9 @@ type itemOptions struct {
7777
// WithExpiration is an option to set expiration time for any items.
7878
// If the expiration is zero or negative value, it treats as w/o expiration.
7979
func WithExpiration(exp time.Duration) ItemOption {
80+
if exp <= 0 {
81+
return func(o *itemOptions) {}
82+
}
8083
return func(o *itemOptions) {
8184
o.expiration = nowFunc().Add(exp)
8285
}

cache_internal_test.go

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,17 @@ import (
99
func TestDeletedCache(t *testing.T) {
1010
ctx, cancel := context.WithCancel(context.Background())
1111
defer cancel()
12+
restore := func() {
13+
nowFunc = time.Now
14+
}
15+
defer restore()
1216

1317
nc := NewContext[string, int](ctx)
1418
key := "key"
15-
nc.Set(key, 1, WithExpiration(-time.Second))
16-
19+
nc.Set(key, 1, WithExpiration(1*time.Second))
20+
nowFunc = func() time.Time {
21+
return time.Now().Add(2 * time.Second)
22+
}
1723
_, ok := nc.cache.Get(key)
1824
if !ok {
1925
t.Fatal("want true")
@@ -143,6 +149,30 @@ func TestDeleteExpired(t *testing.T) {
143149
t.Errorf("want %d items but got %d", want, got)
144150
}
145151
})
152+
153+
t.Run("issue #64", func(t *testing.T) {
154+
defer restore()
155+
c := New[string, int]()
156+
c.Set("1", 4, WithExpiration(0)) // These should not be expired
157+
c.Set("2", 5, WithExpiration(-1)) // These should not be expired
158+
c.Set("3", 6, WithExpiration(1*time.Hour))
159+
160+
want := true
161+
_, ok := c.Get("1")
162+
if ok != want {
163+
t.Errorf("want %t but got %t", want, ok)
164+
}
165+
166+
_, ok = c.Get("2")
167+
if ok != want {
168+
t.Errorf("want %t but got %t", want, ok)
169+
}
170+
_, ok = c.Get("3")
171+
if ok != want {
172+
t.Errorf("want %t but got %t", want, ok)
173+
}
174+
175+
})
146176
}
147177

148178
func max(x, y int) int {

0 commit comments

Comments
 (0)