Skip to content

Commit e523822

Browse files
author
marcinromaszewicz
committed
Add a strict mode to test decoders
1 parent ccde40c commit e523822

File tree

2 files changed

+15
-3
lines changed

2 files changed

+15
-3
lines changed

request_helpers.go

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,14 @@ func (r *RequestBuilder) Go(t *testing.T, e *echo.Echo) *CompletedRequest {
162162
// ResponseRecorder with some nice helper functions.
163163
type CompletedRequest struct {
164164
Recorder *httptest.ResponseRecorder
165+
166+
// When set to true, decoders will be more strict. In the default JSON
167+
// recorder, unknown fields will cause errors.
168+
Strict bool
169+
}
170+
171+
func (c *CompletedRequest) DisallowUnknownFields() {
172+
c.Strict = true
165173
}
166174

167175
// This function takes a destination object as input, and unmarshals the object
@@ -177,7 +185,7 @@ func (c *CompletedRequest) UnmarshalBodyToObject(obj interface{}) error {
177185
return fmt.Errorf("unhandled content: %s", content)
178186
}
179187

180-
return handler(ctype, c.Recorder.Body, obj)
188+
return handler(ctype, c.Recorder.Body, obj, c.Strict)
181189
}
182190

183191
// This function assumes that the response contains JSON and unmarshals it

response_handlers.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ var (
1717
knownHandlers map[string]ResponseHandler
1818
)
1919

20-
type ResponseHandler func(contentType string, raw io.Reader, obj interface{}) error
20+
type ResponseHandler func(contentType string, raw io.Reader, obj interface{}, strict bool) error
2121

2222
func RegisterResponseHandler(mime string, handler ResponseHandler) {
2323
knownHandlersMu.Lock()
@@ -35,6 +35,10 @@ func getHandler(mime string) ResponseHandler {
3535

3636
// This function assumes that the response contains JSON and unmarshals it
3737
// into the specified object.
38-
func jsonHandler(_ string, r io.Reader, obj interface{}) error {
38+
func jsonHandler(_ string, r io.Reader, obj interface{}, strict bool) error {
39+
d := json.NewDecoder(r)
40+
if strict {
41+
d.DisallowUnknownFields()
42+
}
3943
return json.NewDecoder(r).Decode(obj)
4044
}

0 commit comments

Comments
 (0)