Permalink
Browse files

add tests and more expressive error handling

  • Loading branch information...
rybit committed Nov 17, 2017
1 parent 2812133 commit e9a5623e4687cff491f187aef4c65c64bc397617
Showing with 37 additions and 14 deletions.
  1. +2 −2 coupons/coupons.go
  2. +35 −12 coupons/coupons_test.go
@@ -83,7 +83,7 @@ func (c *couponCacheFromURL) load() error {
}
resp, err := c.client.Do(req)
if err != nil {
return err
return errors.Wrap(err, "Failed to make request for coupon information")
}

if resp.StatusCode != http.StatusOK {
@@ -95,7 +95,7 @@ func (c *couponCacheFromURL) load() error {
defer resp.Body.Close()
decoder := json.NewDecoder(resp.Body)
if err := decoder.Decode(couponsResponse); err != nil {
return err
return errors.Wrap(err, "Failed to parse response.")
}

for key, coupon := range couponsResponse.Coupons {
@@ -89,12 +89,7 @@ func TestExplicitLookup(t *testing.T) {
SiteURL: svr.URL,
}
c.Coupons.URL = "this/is/where/the/coupons/are"

cacheFace, err := NewCouponCacheFromURL(c)
require.NoError(t, err)
require.NotNil(t, cacheFace)
cache, ok := cacheFace.(*couponCacheFromURL)
require.True(t, ok)
cache := newCache(t, c)
assert.Equal(t, svr.URL+"/this/is/where/the/coupons/are", cache.url)

coupon, err := cache.Lookup("meow")
@@ -107,6 +102,7 @@ func TestExplicitLookup(t *testing.T) {
assert.Error(t, err)
assert.IsType(t, new(CouponNotFound), err)
assert.Nil(t, coupon)
assert.Equal(t, 1, callCount)
}

func TestCacheExpiration(t *testing.T) {
@@ -121,13 +117,9 @@ func TestCacheExpiration(t *testing.T) {
c := &conf.Configuration{
SiteURL: "this is garbage",
}
// note that this is an absolute path, it is what is used
c.Coupons.URL = svr.URL + "/this/is/where/the/coupons/are"

cacheFace, err := NewCouponCacheFromURL(c)
require.NoError(t, err)
require.NotNil(t, cacheFace)
cache, ok := cacheFace.(*couponCacheFromURL)
require.True(t, ok)
cache := newCache(t, c)
assert.Equal(t, svr.URL+"/this/is/where/the/coupons/are", cache.url)

coupon, err := cache.Lookup("meow")
@@ -145,3 +137,34 @@ func TestCacheExpiration(t *testing.T) {
assert.Nil(t, coupon)
assert.Equal(t, 2, callCount)
}

func TestMalformedResponse(t *testing.T) {
var callCount int
svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
callCount++
w.WriteHeader(http.StatusOK)
w.Write([]byte("this is not json"))
}))
defer svr.Close()

c := &conf.Configuration{
SiteURL: svr.URL,
}
c.Coupons.URL = "/this/is/where/the/coupons/are"
cache := newCache(t, c)
assert.Equal(t, svr.URL+"/this/is/where/the/coupons/are", cache.url)

coupon, err := cache.Lookup("meow")
assert.Error(t, err)
assert.Nil(t, coupon)
assert.Equal(t, 1, callCount)
}

func newCache(t *testing.T, c *conf.Configuration) *couponCacheFromURL {
cacheFace, err := NewCouponCacheFromURL(c)
require.NoError(t, err)
require.NotNil(t, cacheFace)
cache, ok := cacheFace.(*couponCacheFromURL)
require.True(t, ok)
return cache
}

0 comments on commit e9a5623

Please sign in to comment.