Skip to content

Commit d95b1ca

Browse files
kilianpaquiermaxatome
authored andcommitted
feat: add NewJsonResponseOrPanic function
1 parent ebea747 commit d95b1ca

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

response.go

+26
Original file line numberDiff line numberDiff line change
@@ -586,6 +586,32 @@ func NewJsonResponse(status int, body any) (*http.Response, error) { //nolint: r
586586
return response, nil
587587
}
588588

589+
// NewJsonResponseOrPanic is like [NewJsonResponse] but panics in case of error.
590+
//
591+
// It simplifies the call of [ResponderFromMultipleResponses], avoiding the
592+
// use of a temporary variable and an error check, and so can be used in such
593+
// context:
594+
//
595+
// httpmock.RegisterResponder(
596+
// "GET",
597+
// "/test/path",
598+
// httpmock.ResponderFromMultipleResponses([]*http.Response{
599+
// httpmock.NewJsonResponseOrPanic(200, &MyFirstResponseBody),
600+
// httpmock.NewJsonResponseOrPanic(200, &MySecondResponseBody),
601+
// }),
602+
// )
603+
//
604+
// To pass the content of an existing file as body use [File] as in:
605+
//
606+
// httpmock.NewJsonResponseOrPanic(200, httpmock.File("body.json"))
607+
func NewJsonResponseOrPanic(status int, body any) *http.Response { //nolint: revive
608+
response, err := NewJsonResponse(status, body)
609+
if err != nil {
610+
panic(err)
611+
}
612+
return response
613+
}
614+
589615
// NewJsonResponder creates a [Responder] from a given body (as an
590616
// any that is encoded to JSON) and status code.
591617
//

response_test.go

+35
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,41 @@ func TestNewJsonResponse(t *testing.T) {
196196
assert.Nil(response)
197197
}
198198

199+
func TestNewJsonResponseOrPanic(t *testing.T) {
200+
assert := td.Assert(t)
201+
202+
type schema struct {
203+
Hello string `json:"hello"`
204+
}
205+
206+
dir, cleanup := tmpDir(assert)
207+
defer cleanup()
208+
fileName := filepath.Join(dir, "ok.json")
209+
writeFile(assert, fileName, []byte(`{ "test": true }`))
210+
211+
for i, test := range []struct {
212+
body interface{}
213+
expected string
214+
}{
215+
{body: &schema{"world"}, expected: `{"hello":"world"}`},
216+
{body: httpmock.File(fileName), expected: `{"test":true}`},
217+
} {
218+
assert.Run(fmt.Sprintf("#%d", i), func(assert *td.T) {
219+
assert.CmpNotPanic(func() {
220+
response := httpmock.NewJsonResponseOrPanic(200, test.body)
221+
assert.Cmp(response.StatusCode, 200)
222+
assert.Cmp(response.Header.Get("Content-Type"), "application/json")
223+
assertBody(assert, response, test.expected)
224+
})
225+
})
226+
}
227+
228+
// Error case
229+
assert.CmpPanic(
230+
func() { httpmock.NewJsonResponseOrPanic(200, func() {}) },
231+
td.Contains("json: unsupported type"))
232+
}
233+
199234
func checkResponder(assert *td.T, r httpmock.Responder, expectedStatus int, expectedBody string) {
200235
assert.Helper()
201236

0 commit comments

Comments
 (0)