Skip to content

Commit

Permalink
Charmhub: Retry tests
Browse files Browse the repository at this point in the history
Ensure that the code does what we expect. The tests proves that with
using the httptest package.
  • Loading branch information
SimonRichardson committed Jun 24, 2021
1 parent 1301b41 commit 818d2c9
Showing 1 changed file with 71 additions and 0 deletions.
71 changes: 71 additions & 0 deletions charmhub/http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,13 @@ package charmhub
import (
"bytes"
"context"
"fmt"
"net/http"
"net/http/httptest"

"github.com/golang/mock/gomock"
"github.com/juju/errors"
jujuhttp "github.com/juju/http/v2"
"github.com/juju/testing"
jc "github.com/juju/testing/checkers"
gc "gopkg.in/check.v1"
Expand Down Expand Up @@ -136,6 +139,74 @@ func (s *RESTSuite) TestGetWithFailure(c *gc.C) {
c.Assert(err, gc.Not(jc.ErrorIsNil))
}

func (s *RESTSuite) TestGetWithFailureRetry(c *gc.C) {
var called int
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
called++
w.WriteHeader(http.StatusTooManyRequests)
}))

transport := RequestHTTPTransport(nil, jujuhttp.RetryPolicy{
Attempts: 3,
Delay: testing.ShortWait,
MaxDelay: testing.LongWait,
})(&FakeLogger{})
client := NewHTTPRESTClient(transport, nil)

base := MustMakePath(c, server.URL)

var result interface{}
_, err := client.Get(context.TODO(), base, &result)
c.Assert(err, gc.Not(jc.ErrorIsNil))
c.Assert(called, gc.Equals, 3)
}

func (s *RESTSuite) TestGetWithFailureWithoutRetry(c *gc.C) {
var called int
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
called++
w.WriteHeader(http.StatusInternalServerError)
}))

transport := RequestHTTPTransport(nil, jujuhttp.RetryPolicy{
Attempts: 3,
Delay: testing.ShortWait,
MaxDelay: testing.LongWait,
})(&FakeLogger{})
client := NewHTTPRESTClient(transport, nil)

base := MustMakePath(c, server.URL)

var result interface{}
_, err := client.Get(context.TODO(), base, &result)
c.Assert(err, gc.Not(jc.ErrorIsNil))
c.Assert(called, gc.Equals, 1)
}

func (s *RESTSuite) TestGetWithNoRetry(c *gc.C) {
var called int
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
called++
w.Header().Set("content-type", "application/json")
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, "{}")
}))

transport := RequestHTTPTransport(nil, jujuhttp.RetryPolicy{
Attempts: 3,
Delay: testing.ShortWait,
MaxDelay: testing.LongWait,
})(&FakeLogger{})
client := NewHTTPRESTClient(transport, nil)

base := MustMakePath(c, server.URL)

var result interface{}
_, err := client.Get(context.TODO(), base, &result)
c.Assert(err, jc.ErrorIsNil)
c.Assert(called, gc.Equals, 1)
}

func (s *RESTSuite) TestGetWithUnmarshalFailure(c *gc.C) {
ctrl := gomock.NewController(c)
defer ctrl.Finish()
Expand Down

0 comments on commit 818d2c9

Please sign in to comment.