Skip to content

Commit

Permalink
Add test and split func
Browse files Browse the repository at this point in the history
  • Loading branch information
jaimem88 committed Oct 13, 2020
1 parent a5ae76b commit 0293691
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 5 deletions.
20 changes: 15 additions & 5 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,11 @@ func (c *cache) Set(k string, x interface{}, d time.Duration) {
if d > 0 {
e = time.Now().Add(d).UnixNano()
}
c.mu.Lock()
if i, ok := c.items[k]; ok && i.Expired() {
// delete if expired so .onEvicted is called
c.delete(k)
}

// delete before setting and call onEvicted
c.deleteIfExpired(k)

c.mu.Lock()
c.items[k] = Item{
Object: x,
Expiration: e,
Expand Down Expand Up @@ -927,6 +926,17 @@ func (c *cache) delete(k string) (interface{}, bool) {
return nil, false
}

func (c *cache) deleteIfExpired(k string) {
c.mu.Lock()
i, ok := c.items[k]
c.mu.Unlock()

if ok && i.Expired() {
// delete if expired so .onEvicted is called
c.Delete(k)
}
}

type keyAndValue struct {
key string
value interface{}
Expand Down
33 changes: 33 additions & 0 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1247,6 +1247,39 @@ func TestOnEvicted(t *testing.T) {
}
}

func TestOnEvictedCalledBeforeSet(t *testing.T) {
tc := New(DefaultExpiration, 0)
expiry := 1 * time.Millisecond

works := false
tc.OnEvicted(func(k string, v interface{}) {
if k == "foo" && v.(int) == 3 {

works = true
}
tc.Set("bar", 4, DefaultExpiration)
})

tc.Set("foo", 3, expiry)
if tc.onEvicted == nil {
t.Fatal("tc.onEvicted is nil")
}

// ensure item expires
time.Sleep(expiry)

// calling Set again should evict expired item
tc.Set("foo", 3, DefaultExpiration)

x, _ := tc.Get("bar")
if !works {
t.Fatal("works bool not true")
}
if x.(int) != 4 {
t.Error("bar was not 4")
}
}

func TestCacheSerialization(t *testing.T) {
tc := New(DefaultExpiration, 0)
testFillAndSerialize(t, tc)
Expand Down

0 comments on commit 0293691

Please sign in to comment.