mirror of
https://github.com/grafana/grafana.git
synced 2025-02-25 18:55:37 -06:00
Send empty http response when body is nil (#80196)
* build empty response if body is nil * fix test
This commit is contained in:
parent
67feb0bba1
commit
6b28669e1f
@ -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 {
|
||||
|
@ -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())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
@ -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 {
|
||||
|
Loading…
Reference in New Issue
Block a user