Skip to content

Commit

Permalink
client_iter: check for http status code
Browse files Browse the repository at this point in the history
  • Loading branch information
aviau committed Sep 15, 2024
1 parent 4d0cedb commit d143d8a
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
9 changes: 8 additions & 1 deletion api_client_iter.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,21 @@ func getIterResult(
if err != nil {
return nil, fmt.Errorf("failed to fetch next page: %w", err)
}

defer response.Body.Close()

body, err := io.ReadAll(response.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}

if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf(
"got http status code %d status while fetching next page: %s",
response.StatusCode,
body,
)
}

type ResponseWithNext struct {
Next string `json:"next"`
}
Expand Down
35 changes: 34 additions & 1 deletion api_client_iter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func TestIterGet(t *testing.T) {

}

func TestIterGetBadResponse(t *testing.T) {
func TestIterGetBadResponseJson(t *testing.T) {
ct := newClientTest(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "/leaksdb/sources", r.URL.Path)
Expand All @@ -82,6 +82,39 @@ func TestIterGetBadResponse(t *testing.T) {
assert.Equal(t, 1, lastPageIndex, "Didn't get the expected number of pages")
}

func TestIterGetBadResponseStatus(t *testing.T) {
ct := newClientTest(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Correct response structure but bad response status code.
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(`"some error"`))
}),
)
defer ct.Close()

lastPageIndex := 0

for result, err := range ct.apiClient.IterGet(
"/leaksdb/sources",
nil,
) {
lastPageIndex = lastPageIndex + 1
if lastPageIndex > 2 {
// We are going crazy here...
break
}
assert.ErrorContains(
t,
err,
`got http status code 400 status while fetching next page: "some error"`,
"Bad HTTP status should trigger an error",
)
assert.Nil(t, result, "result should be nil on errors")
}

assert.Equal(t, 1, lastPageIndex, "Didn't get the expected number of pages")
}

func TestIterPostJson(t *testing.T) {
ct := newClientTest(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Expand Down

0 comments on commit d143d8a

Please sign in to comment.