File tree Expand file tree Collapse file tree 2 files changed +30
-1
lines changed Expand file tree Collapse file tree 2 files changed +30
-1
lines changed Original file line number Diff line number Diff line change @@ -11,19 +11,31 @@ import (
11
11
"time"
12
12
)
13
13
14
+ const (
15
+ neverExpires = - 1
16
+ )
17
+
14
18
type CacheItem struct {
15
19
Value []byte `json:"value"`
16
20
ExpiresAt int64 `json:"expires_at"`
17
21
}
18
22
19
23
func NewCacheItem (value []byte , ttl time.Duration ) CacheItem {
24
+ expiresAt := time .Now ().Add (ttl ).Unix ()
25
+ if ttl < 0 {
26
+ expiresAt = neverExpires
27
+ }
28
+
20
29
return CacheItem {
21
30
Value : value ,
22
- ExpiresAt : time . Now (). Add ( ttl ). Unix () ,
31
+ ExpiresAt : expiresAt ,
23
32
}
24
33
}
25
34
26
35
func (item CacheItem ) IsExpired () bool {
36
+ if item .ExpiresAt < 0 {
37
+ return false
38
+ }
27
39
return time .Now ().Unix () > item .ExpiresAt
28
40
}
29
41
Original file line number Diff line number Diff line change 5
5
"github.com/stretchr/testify/suite"
6
6
"os"
7
7
"testing"
8
+ "time"
8
9
)
9
10
10
11
func TestLocalCacheTestSuite (t * testing.T ) {
@@ -53,3 +54,19 @@ func (suite *LocalCacheTestSuite) TestDelete() {
53
54
err = suite .cache .Get (ctx , key , new (string ))
54
55
suite .Error (err )
55
56
}
57
+
58
+ func (suite * LocalCacheTestSuite ) TestCacheItemExpiration () {
59
+ item := NewCacheItem ([]byte ("testValue" ), 1 * time .Second )
60
+ suite .False (item .IsExpired (), "CacheItem should not be expired right after creation" )
61
+ time .Sleep (2 * time .Second )
62
+
63
+ suite .True (item .IsExpired (), "CacheItem should be expired after its TTL" )
64
+ }
65
+
66
+ func (suite * LocalCacheTestSuite ) TestCacheItemNeverExpires () {
67
+ item := NewCacheItem ([]byte ("testValue" ), - 1 )
68
+ suite .False (item .IsExpired (), "CacheItem with negative TTL should never expire" )
69
+ time .Sleep (2 * time .Second )
70
+
71
+ suite .False (item .IsExpired (), "CacheItem with negative TTL should never expire, even after some time" )
72
+ }
You can’t perform that action at this time.
0 commit comments