Skip to content

Commit

Permalink
Updated TestCache to use do(); added ClearCache function
Browse files Browse the repository at this point in the history
  • Loading branch information
mtslzr committed Jun 24, 2019
1 parent b460e5b commit 228fae8
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 17 deletions.
5 changes: 5 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ func init() {
c = cache.New(cachemin*time.Minute, cachemax*time.Minute)
}

// ClearCache clears all cached data.
func ClearCache() {
c.Flush()
}

func do(endpoint string, obj interface{}) error {
cached, found := c.Get(endpoint)
if found {
Expand Down
44 changes: 27 additions & 17 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,39 +3,49 @@ package pokeapi
import (
"encoding/json"
"testing"
"time"

"github.com/mtslzr/pokeapi-go/structs"
"github.com/stretchr/testify/assert"
)

type CachedData struct {
Data interface{}
Expires time.Time
Found bool
}

func TestCache(t *testing.T) {
endpoint := "machine"
fullEndpoint := endpoint + "?offset=0&limit=0"
var endpoint = "machine/1"
var mockMachine structs.Machine

func TestSetCache(t *testing.T) {
_, found1 := c.Get(endpoint)
assert.Equal(t, false, found1,
"Expect to not have cached data before first call.")

result, _ := Resource(endpoint)
cached2, expires2, found2 := c.GetWithExpiration(fullEndpoint)
var cachedData structs.Resource
json.Unmarshal(cached2.([]byte), &cachedData)
_ = do(endpoint, &mockMachine)
cached2, expires2, found2 := c.GetWithExpiration(endpoint)
assert.Equal(t, true, found2,
"Expect to have cached data after first call.")

result, _ = Resource(endpoint)
cached3, expires3, _ := c.GetWithExpiration(fullEndpoint)
assert.Equal(t, cachedData, result,
_ = do(endpoint, &mockMachine)
var cachedData structs.Machine
json.Unmarshal(cached2.([]byte), &cachedData)
cached3, expires3, _ := c.GetWithExpiration(endpoint)
assert.Equal(t, cachedData, mockMachine,
"Expect data to match cached data.")
assert.Equal(t, cached2, cached3,
"Expect cached data to match previously-cached data.")
assert.Equal(t, expires2, expires3,
"Expect expiration times to match.")
}

func TestClearCache(t *testing.T) {
_, found := c.Get(endpoint)
if !found {
_ = do(endpoint, &mockMachine)
_, found = c.Get(endpoint)
}
assert.NotEqual(t, false, found,
"Expect to start with cached data.")

ClearCache()
nocache, nofound := c.Get(endpoint)
assert.Equal(t, false, nofound,
"Expect no data found after flushing cache.")
assert.Equal(t, nil, nocache,
"Expect no data after flushing cache.")
}

0 comments on commit 228fae8

Please sign in to comment.