Skip to content

Commit

Permalink
add cache test
Browse files Browse the repository at this point in the history
  • Loading branch information
Yevhenii Voevodin committed Dec 5, 2016
1 parent b88605c commit 68917c2
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 7 deletions.
17 changes: 10 additions & 7 deletions exec-agent/src/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,14 +94,17 @@ func (cache *TokenCache) Contains(token string) bool {
func (cache *TokenCache) expirePeriodically(period time.Duration) {
cache.ticker = time.NewTicker(period)
for range cache.ticker.C {
now := time.Now()
cache.Lock()
for token, expTime := range cache.tokens {
if expTime.Before(now) {
delete(cache.tokens, token)
}
cache.expireAllBefore(time.Now())
}
}

func (cache *TokenCache) expireAllBefore(expirationPoint time.Time) {
cache.Lock()
defer cache.Unlock()
for token, expTime := range cache.tokens {
if expTime.Before(expirationPoint) {
delete(cache.tokens, token)
}
cache.Unlock()
}
}

Expand Down
45 changes: 45 additions & 0 deletions exec-agent/src/auth/cache_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package auth

import (
"testing"
"time"
)

func TestTokenCache(t *testing.T) {
cache := &TokenCache{
tokens : make(map[string]time.Time),
expireTimeout: 0,
}

token := "my-token"

cache.Put(token)
if !cache.Contains(token) {
t.Fatalf("Cache must contain token %s", token)
}

cache.Expire(token)
if cache.Contains(token) {
t.Fatalf("Cache must not contain token %s", token)
}
}

func TestExpiresTokensCreatedBeforeGivenPointOfTime(t *testing.T) {
cache := &TokenCache{
tokens : make(map[string]time.Time),
expireTimeout: 0,
}

cache.Put("token1")
afterToken1Put := time.Now()
cache.Put("token2")

cache.expireAllBefore(afterToken1Put)

if cache.Contains("token1") {
t.Fatal("Cache must not contain token1")
}
if !cache.Contains("token2") {
t.Fatal("Cache must contain token2")
}
}

0 comments on commit 68917c2

Please sign in to comment.