Skip to content

Commit

Permalink
add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
JulienTant committed Oct 11, 2019
1 parent 1333bc4 commit a1663bd
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 1 deletion.
57 changes: 56 additions & 1 deletion client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,58 @@ func TestClient(t *testing.T) {
}
}

func TestClientWithError(t *testing.T) {
h := testHandler{}
ts := httptest.NewServer(&h)
defer ts.Close()

client := ts.Client()
u, _ := url.Parse(ts.URL)
e := NewClientWithError("GET", u, kithttp.EncodeJSONRequest, decodeTestResponse, kithttp.SetClient(client)).Endpoint()

h.statuses = []int{http.StatusServiceUnavailable}
resp, err := e(context.TODO(), nil)
if err != nil {
t.Error("When calling a failed server, the client with error should NOT return an error")
}
v, ok := resp.(testStruct)
if ok == false {
t.Errorf("The returned response must be decoded, got %#v", resp)
}
if v.err == nil {
t.Error("The response has not been correctly decoded")
}

if !IsRetryable(v.err) {
t.Error("The returned error for http.StatusServiceUnavailable should be retryable")
}

h.statuses = []int{http.StatusBadRequest}
resp, err = e(context.TODO(), nil)
if err != nil {
t.Error("When calling a failed server, the client with error should NOT return an error")
}
v, ok = resp.(testStruct)
if ok == false {
t.Errorf("The returned response must be decoded, got %#v", resp)
}
if v.err == nil {
t.Error("The response has not been correctly decoded")
}
if IsRetryable(v.err) {
t.Error("The returned error for http.StatusBadRequest should not be retryable")
}


h.statuses = []int{}
res, err := e(context.TODO(), nil)
if err != nil {
t.Errorf("When calling a working server, the client should not return an error, got %s", err)
} else if !reflect.DeepEqual(res, testData) {
t.Errorf("The endpoint returned invalid data : %+v", res)
}
}

var testData = testStruct{Foo: "bar"}

type testHandler struct {
Expand All @@ -57,14 +109,17 @@ func (h *testHandler) ServeHTTP(w http.ResponseWriter, _ *http.Request) {
h.statuses = h.statuses[1:]
} else {
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(testData)
}
json.NewEncoder(w).Encode(testData)
}

func decodeTestResponse(ctx context.Context, resp *http.Response) (interface{}, error) {
response := testStruct{}
if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
return nil, err
}

response.err = HTTPError(resp)

return response, nil
}
2 changes: 2 additions & 0 deletions server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,8 @@ func TestServer(t *testing.T) {
type testStruct struct {
Foo string `json:"foo"`
Status int `json:"status"`

err error
}

func testEP(_ context.Context, req interface{}) (interface{}, error) {
Expand Down

0 comments on commit a1663bd

Please sign in to comment.