From 0c6d8c7fa966ab548a1f25c1c85d45e22eb44770 Mon Sep 17 00:00:00 2001 From: siddharth ravikumar Date: Mon, 6 Jun 2022 19:03:08 -0400 Subject: add `cache` package A simple key-value store. --- cache/cache_test.go | 72 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 cache/cache_test.go (limited to 'cache/cache_test.go') diff --git a/cache/cache_test.go b/cache/cache_test.go new file mode 100644 index 0000000..41e0d25 --- /dev/null +++ b/cache/cache_test.go @@ -0,0 +1,72 @@ +// Copyright © 2022 siddharth ravikumar +// SPDX-License-Identifier: ISC + +package cache + +import ( + "testing" + "time" +) + +func TestNewCache(t *testing.T) { + c := NewCache() + if c == nil { + t.Errorf("cache is nil") + return + } + if c.store == nil { + t.Errorf("cache.store is nil") + return + } + // Try manually adding an item. + c.store["foo"] = item{ + value: "bar", + expires: time.Now().Add(time.Second * 10), + } + if c.store["foo"].value != "bar" { + t.Errorf("cache.store['foo'] is not bar") + return + } +} + +func TestCacheSet(t *testing.T) { + c := NewCache() + if c == nil { + t.Errorf("cache is nil") + return + } + exp := time.Now().Add(time.Second * 10) + c.Set("foo", "bar", exp) + if c.store["foo"].value != "bar" { + t.Errorf("cache.store['foo'] is not bar") + return + } + if c.store["foo"].expires.Unix() != exp.Unix() { + t.Errorf("cache.store['foo'].expires no set correctly") + return + } +} + +func TestCacheGet(t *testing.T) { + c := NewCache() + if c == nil { + t.Errorf("cache is nil") + return + } + + // Test 1 + exp := time.Now().Add(time.Second * 10) + c.Set("foo", "bar", exp) + if c.Get("foo") != "bar" { + t.Errorf("cache.Get(foo) is not bar") + return + } + + // Test 2 + exp = time.Now().Add(time.Second * -10) + c.Set("sna", "fu", exp) + if c.Get("sna") != "" { + t.Errorf("cache.Get(sna) is not empty: %s", c.Get("sna")) + return + } +} -- cgit v1.2.3