Skip to content

Commit

Permalink
feat: add NewJsonResponseOrPanic function
Browse files Browse the repository at this point in the history
  • Loading branch information
kilianpaquier committed Apr 17, 2024
1 parent c72d04a commit 6eb2746
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
26 changes: 26 additions & 0 deletions response.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
//
Expand Down
35 changes: 35 additions & 0 deletions response_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down

0 comments on commit 6eb2746

Please sign in to comment.