Skip to content

Commit

Permalink
test: ensure decoder does not allow trailing data
Browse files Browse the repository at this point in the history
  • Loading branch information
tdakkota committed Oct 5, 2022
1 parent af97df8 commit e564d1c
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
39 changes: 39 additions & 0 deletions internal/requests_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
Expand Down Expand Up @@ -217,6 +218,44 @@ func TestRequests(t *testing.T) {
})
}

func TestRequestJSONTrailingData(t *testing.T) {
a := require.New(t)
ctx := context.Background()

testData := "bababoi"
srv, err := api.NewServer(testHTTPRequests{},
api.WithErrorHandler(func(ctx context.Context, w http.ResponseWriter, r *http.Request, err error) {
w.WriteHeader(http.StatusBadRequest)
_, _ = io.WriteString(w, err.Error())
}),
)
a.NoError(err)

s := httptest.NewServer(srv)
defer s.Close()

reqBody := fmt.Sprintf(`{"name":%q}{"name":"trailing"}`, testData)
req, err := http.NewRequestWithContext(
ctx,
http.MethodPost,
s.URL+"/allRequestBodies",
strings.NewReader(reqBody),
)
a.NoError(err)
req.Header.Set("Content-Type", "application/json")

resp, err := s.Client().Do(req)
a.NoError(err)
defer func() {
_ = resp.Body.Close()
}()

a.Equal(http.StatusBadRequest, resp.StatusCode)
data, err := io.ReadAll(resp.Body)
a.NoError(err)
a.Contains(string(data), ": unexpected trailing data")
}

func TestServerURLOverride(t *testing.T) {
a := require.New(t)
ctx := context.Background()
Expand Down
19 changes: 19 additions & 0 deletions internal/responses_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -352,3 +352,22 @@ func TestResponsesPattern(t *testing.T) {
}
})
}

func TestResponseJSONTrailingData(t *testing.T) {
a := require.New(t)
ctx := context.Background()

s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = fmt.Fprint(w, `{"ok": "yes"}
{"ok": "trailing"}`)
}))
defer s.Close()

client, err := api.NewClient(s.URL, api.WithClient(s.Client()))
a.NoError(err)

_, err = client.Combined(ctx, api.CombinedParams{Type: api.CombinedType200})
a.ErrorContains(err, "unexpected trailing data")
}

0 comments on commit e564d1c

Please sign in to comment.