Skip to content

Commit

Permalink
Merge 1b61c87 into 5eb7935
Browse files Browse the repository at this point in the history
  • Loading branch information
smallnest authored Jul 31, 2019
2 parents 5eb7935 + 1b61c87 commit 6e6ce13
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 0 deletions.
29 changes: 29 additions & 0 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,32 @@ func Cache(table string) *CacheTable {

return t
}

// RemoveCache removes the table if it exists.
func RemoveCache(table string) {
mutex.RLock()
delete(cache, table)
mutex.RUnlock()
}

// AllTables returns name list of all tables.
func AllTables() []string {
mutex.RLock()
defer mutex.RUnlock()

var tables []string

for k := range cache {
tables = append(tables, k)
}

return tables
}

// ResetCache clears all tables.
func ResetCache() {
mutex.RLock()
defer mutex.RUnlock()

cache = make(map[string]*CacheTable)
}
48 changes: 48 additions & 0 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ package cache2go
import (
"bytes"
"log"
"sort"
"strconv"
"sync"
"sync/atomic"
Expand Down Expand Up @@ -54,6 +55,53 @@ func TestCache(t *testing.T) {
}
}

func TestRemoveCache(t *testing.T) {
// add an expiring item after a non-expiring one to
// trigger expirationCheck iterating over non-expiring items
table := Cache("testCache")
table.Add(k+"_1", 0*time.Second, v)
table.Add(k+"_2", 1*time.Minute, v)

RemoveCache("testCache")

//re-get the cache
table = Cache("testCache")
// check if both items are still there
p, err := table.Value(k + "_1")
if err == nil || p != nil {
t.Error("Error retrieving non-existed data from cache", err)
}
p, err = table.Value(k + "_2")
if err == nil || p != nil {
t.Error("Error retrieving non-existed data from cache", err)
}
}

func TestAllTables(t *testing.T) {
ResetCache()

// create some tables.
Cache("testCache1")
Cache("testCache2")
Cache("testCache3")
Cache("testCache1")
Cache("testCache2")
Cache("testCache3")

RemoveCache("testCache1")

tables := AllTables()

if len(tables) != 2 {
t.Errorf("Expect 2 tables but got %d", len(tables))
}

sort.Strings(tables)
if tables[0] != "testCache2" || tables[1] != "testCache3" {
t.Errorf("Expect testCache2 and testCache3 but got %v", tables)
}
}

func TestCacheExpire(t *testing.T) {
table := Cache("testCache")

Expand Down

0 comments on commit 6e6ce13

Please sign in to comment.