Skip to content

Commit

Permalink
test: Make it possible to run revoke & refresh loops faster for quick…
Browse files Browse the repository at this point in the history
…er tests. Test case for revocation skipping bug when item is in updating state
  • Loading branch information
mahe-work committed Oct 26, 2021
1 parent 436902d commit aa648a3
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 2 deletions.
7 changes: 5 additions & 2 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ var cacheSize = 20
// default ttl
var ttl = 1 * time.Hour

// revoke & refresh loop interval
var loopInterval = 1 * time.Second

var jobs chan timedCacheItem

// StartWith background loading cache with specified parameters
Expand All @@ -40,8 +43,8 @@ func Start() {
for w := 1; w <= workerAmount; w++ {
go worker(w, jobs)
}
go doEvery(1*time.Second, refresh)
go doEvery(1*time.Second, revoke)
go doEvery(loopInterval, refresh)
go doEvery(loopInterval, revoke)
}

// check and update expiring items
Expand Down
61 changes: 61 additions & 0 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,10 +113,71 @@ func TestItemWithShortestTTLIsRevokedWhenCacheFillsUp(t *testing.T) {
}
}

func TestConcurrentRefreshAndGetBug(t *testing.T) {
// Run refresh & revoke loops quicker than usual
defaultLoopInterval := loopInterval
defer func() {
loopInterval = defaultLoopInterval
}()
loopInterval = 10 * time.Millisecond
StartWith(1, 11, 1, 5*time.Second)
// continuously spam GetValue until we want to stop
c := make(chan []byte, 1)
url := "https://httpbin.org/ip"
go busyGet(t, c, url)
value := randomGetFunc("")
i := CacheItem{
Key: url,
Value: value,
Expiration: 10 * time.Millisecond,
GetFunc: randomGetFunc,
}
AddItem(i)
time.Sleep(1 * time.Second)
c <- []byte("stop")
v, _ := cache.Get(url)
ci := v.(timedCacheItem)
assert.NotEqual(t, ci.Updating, true, "Item Should not be in updating state")
}

func TestRevocationDespiteUpdatingBug(t *testing.T) {
// Run refresh & revoke loops quicker than usual
defaultLoopInterval := loopInterval
defer func() {
loopInterval = defaultLoopInterval
}()
loopInterval = 10 * time.Millisecond
StartWith(1, 11, 1, 20*time.Millisecond)
// continuously spam GetValue until we want to stop
c := make(chan []byte, 1)
url := "https://httpbin.org/ip"
go busyGet(t, c, url)
value := randomGetFunc("")
i := CacheItem{
Key: url,
Value: value,
Expiration: 10 * time.Millisecond,
GetFunc: randomGetFunc,
}
AddItem(i)
time.Sleep(1 * time.Second)
c <- []byte("stop")
assert.True(t, nil == GetValue(url), "Item should have been revoked by now")
}

func noopGetFunc(s string) []byte {
return nil
}

func randomGetFunc(s string) []byte {
return []byte(uuid.New().String())
}

func busyGet(t *testing.T, c chan []byte, k string) {
defer func() {
_ = <-c
}()
for len(c) == 0 {
_ = GetValue(k)
}
}

0 comments on commit aa648a3

Please sign in to comment.