From 228fae8f36182294f571110e3d43498eec7aba83 Mon Sep 17 00:00:00 2001 From: Matthew Salazar Date: Mon, 24 Jun 2019 00:38:00 -0400 Subject: [PATCH] Updated TestCache to use do(); added ClearCache function --- client.go | 5 +++++ client_test.go | 44 +++++++++++++++++++++++++++----------------- 2 files changed, 32 insertions(+), 17 deletions(-) diff --git a/client.go b/client.go index 6f0377a..e675d75 100644 --- a/client.go +++ b/client.go @@ -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 { diff --git a/client_test.go b/client_test.go index 96ff054..3068ae1 100644 --- a/client_test.go +++ b/client_test.go @@ -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.") +}