From 6eb274631f2d7f6e8af1bd0592129b63d1c2f0e4 Mon Sep 17 00:00:00 2001 From: kilianpaquier <107955904+kilianpaquier@users.noreply.github.com> Date: Wed, 17 Apr 2024 17:31:58 +0000 Subject: [PATCH] feat: add NewJsonResponseOrPanic function --- response.go | 26 ++++++++++++++++++++++++++ response_test.go | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) diff --git a/response.go b/response.go index fd9ecd4..4c4d8d3 100644 --- a/response.go +++ b/response.go @@ -586,6 +586,32 @@ func NewJsonResponse(status int, body any) (*http.Response, error) { // nolint: return response, nil } +// NewJsonResponseOrPanic is like [NewJsonResponse] but panics in case of error. +// +// It simplifies the call of [ResponderFromMultipleResponses], avoiding the +// use of a temporary variable and an error check, and so can be used in such +// context: +// +// httpmock.RegisterResponder( +// "GET", +// "/test/path", +// httpmock.ResponderFromMultipleResponses([]*http.Response{ +// httpmock.NewJsonResponseOrPanic(200, &MyFirstResponseBody), +// httpmock.NewJsonResponseOrPanic(200, &MySecondResponseBody), +// }), +// ) +// +// To pass the content of an existing file as body use [File] as in: +// +// httpmock.NewJsonResponseOrPanic(200, httpmock.File("body.json")) +func NewJsonResponseOrPanic(status int, body any) *http.Response { //nolint: revive + response, err := NewJsonResponse(status, body) + if err != nil { + panic(err) + } + return response +} + // NewJsonResponder creates a [Responder] from a given body (as an // any that is encoded to JSON) and status code. // diff --git a/response_test.go b/response_test.go index 83a03cf..a34915b 100644 --- a/response_test.go +++ b/response_test.go @@ -196,6 +196,41 @@ func TestNewJsonResponse(t *testing.T) { assert.Nil(response) } +func TestNewJsonResponseOrPanic(t *testing.T) { + assert := td.Assert(t) + + type schema struct { + Hello string `json:"hello"` + } + + dir, cleanup := tmpDir(assert) + defer cleanup() + fileName := filepath.Join(dir, "ok.json") + writeFile(assert, fileName, []byte(`{ "test": true }`)) + + for i, test := range []struct { + body interface{} + expected string + }{ + {body: &schema{"world"}, expected: `{"hello":"world"}`}, + {body: httpmock.File(fileName), expected: `{"test":true}`}, + } { + assert.Run(fmt.Sprintf("#%d", i), func(assert *td.T) { + assert.CmpNotPanic(func() { + response := httpmock.NewJsonResponseOrPanic(200, test.body) + assert.Cmp(response.StatusCode, 200) + assert.Cmp(response.Header.Get("Content-Type"), "application/json") + assertBody(assert, response, test.expected) + }) + }) + } + + // Error case + assert.CmpPanic( + func() { httpmock.NewJsonResponseOrPanic(200, func() {}) }, + td.Contains("json: unsupported type")) +} + func checkResponder(assert *td.T, r httpmock.Responder, expectedStatus int, expectedBody string) { assert.Helper()