From 68917c270c7f64b97fd76044b54594872904d2b8 Mon Sep 17 00:00:00 2001 From: Yevhenii Voevodin Date: Mon, 5 Dec 2016 18:27:55 +0200 Subject: [PATCH] add cache test --- exec-agent/src/auth/auth.go | 17 +++++++----- exec-agent/src/auth/cache_test.go | 45 +++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 7 deletions(-) create mode 100644 exec-agent/src/auth/cache_test.go diff --git a/exec-agent/src/auth/auth.go b/exec-agent/src/auth/auth.go index c1ea67d5764..bf83bc9df3f 100644 --- a/exec-agent/src/auth/auth.go +++ b/exec-agent/src/auth/auth.go @@ -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() } } diff --git a/exec-agent/src/auth/cache_test.go b/exec-agent/src/auth/cache_test.go new file mode 100644 index 00000000000..9854b0f3a0a --- /dev/null +++ b/exec-agent/src/auth/cache_test.go @@ -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") + } +} \ No newline at end of file