Send empty http response when body is nil (#80196)

* build empty response if body is nil

* fix test
This commit is contained in:
Mihai Doarna 2024-01-29 14:17:56 +02:00 committed by GitHub
parent 67feb0bba1
commit 6b28669e1f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 49 additions and 4 deletions

View File

@ -311,6 +311,8 @@ func Respond(status int, body any) *NormalResponse {
b = t
case string:
b = []byte(t)
case nil:
break
default:
var err error
if b, err = json.Marshal(body); err != nil {

View File

@ -125,3 +125,49 @@ func TestErrors(t *testing.T) {
)
}
}
func TestRespond(t *testing.T) {
testCases := []struct {
name string
status int
body any
expected []byte
}{
{
name: "with body of type []byte",
status: 200,
body: []byte("message body"),
expected: []byte("message body"),
},
{
name: "with body of type string",
status: 400,
body: "message body",
expected: []byte("message body"),
},
{
name: "with nil body",
status: 204,
body: nil,
expected: nil,
},
{
name: "with body of type struct",
status: 200,
body: struct {
Name string
Value int
}{"name", 1},
expected: []byte(`{"Name":"name","Value":1}`),
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
resp := Respond(tc.status, tc.body)
require.Equal(t, tc.status, resp.status)
require.Equal(t, tc.expected, resp.body.Bytes())
})
}
}

View File

@ -269,10 +269,7 @@ func TestAPIDeletePublicDashboard(t *testing.T) {
assert.Equal(t, test.ExpectedHttpResponse, response.Code)
if test.ExpectedHttpResponse == http.StatusOK {
var jsonResp any
err := json.Unmarshal(response.Body.Bytes(), &jsonResp)
require.NoError(t, err)
assert.Equal(t, jsonResp, nil)
assert.Equal(t, []byte(nil), response.Body.Bytes())
}
if !test.ShouldCallService {