Files
Maxence MaireauxandGitHub edca639475 fix: roll up remaining backlog fixes (EN-1180-EN-1196) (#655)
* fix: roll up remaining backlog fixes (EN-1180-EN-1196)

* fix: preserve nil json marshal behavior

* docs: clarify implicit http status capture

* fix: align httpserver timeout and tracing paths

* fix: preserve debug request body read errors
2026-06-22 12:43:54 +00:00

130 lines
2.5 KiB
Go

package http
import (
stdhttp "net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
)
func TestMarshalJSONWithStatusWritesStatusWithoutBodyForNilJSONValues(t *testing.T) {
t.Parallel()
testCases := []struct {
name string
body any
status int
}{
{
name: "nil interface",
body: nil,
status: stdhttp.StatusNoContent,
},
{
name: "nil pointer",
body: (*struct {
ID string `json:"id"`
})(nil),
status: stdhttp.StatusAccepted,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
recorder := httptest.NewRecorder()
MarshalJSONWithStatus(recorder, tc.body, tc.status)
require.Equal(t, tc.status, recorder.Code)
require.Empty(t, recorder.Body.String())
require.Equal(t, "application/json", recorder.Header().Get("content-type"))
})
}
}
func TestMarshalJSONWithStatusWritesBodyForNonNilJSONValues(t *testing.T) {
t.Parallel()
testCases := []struct {
name string
body any
expected string
}{
{
name: "struct pointer",
body: &struct {
ID string `json:"id"`
}{ID: "test"},
expected: `{"id":"test"}`,
},
{
name: "empty map",
body: map[string]string{},
expected: `{}`,
},
{
name: "empty slice",
body: []string{},
expected: `[]`,
},
{
name: "nil map",
body: map[string]string(nil),
expected: `null`,
},
{
name: "nil slice",
body: []string(nil),
expected: `null`,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
recorder := httptest.NewRecorder()
MarshalJSONWithStatus(recorder, tc.body, stdhttp.StatusAccepted)
require.Equal(t, stdhttp.StatusAccepted, recorder.Code)
require.JSONEq(t, tc.expected, recorder.Body.String())
require.Equal(t, "application/json", recorder.Header().Get("content-type"))
})
}
}
func TestMarshalJSONWithStatusReturnsMarshalErrorsForUnsupportedNilValues(t *testing.T) {
t.Parallel()
testCases := []struct {
name string
body any
}{
{
name: "nil channel",
body: (chan string)(nil),
},
{
name: "nil function",
body: (func())(nil),
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
recorder := httptest.NewRecorder()
MarshalJSONWithStatus(recorder, tc.body, stdhttp.StatusAccepted)
require.Equal(t, stdhttp.StatusInternalServerError, recorder.Code)
require.Contains(t, recorder.Body.String(), "json: unsupported type")
})
}
}