//go:build test package mw import ( "encoding/json" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" ) func TestRespondJSON_Status(t *testing.T) { t.Parallel() w := httptest.NewRecorder() RespondJSON(w, http.StatusCreated, "created") assert.Equal(t, http.StatusCreated, w.Code) } func TestRespondJSON_ContentType(t *testing.T) { t.Parallel() w := httptest.NewRecorder() RespondJSON(w, http.StatusOK, "ok") assert.Equal(t, "application/json", w.Header().Get("Content-Type")) } func TestRespondJSON_EncodesData(t *testing.T) { t.Parallel() type payload struct { Name string `json:"name"` Count int `json:"count"` } data := payload{Name: "test", Count: 42} w := httptest.NewRecorder() RespondJSON(w, http.StatusOK, data) var decoded payload err := json.Unmarshal(w.Body.Bytes(), &decoded) assert.NoError(t, err) assert.Equal(t, "test", decoded.Name) assert.Equal(t, 42, decoded.Count) } func TestRespondJSON_NilData(t *testing.T) { t.Parallel() w := httptest.NewRecorder() RespondJSON(w, http.StatusOK, nil) assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "application/json", w.Header().Get("Content-Type")) assert.Equal(t, "null\n", w.Body.String()) } func TestRespondJSON_MapData(t *testing.T) { t.Parallel() data := map[string]any{ "key": "value", "count": 3.0, } w := httptest.NewRecorder() RespondJSON(w, http.StatusOK, data) var decoded map[string]any err := json.Unmarshal(w.Body.Bytes(), &decoded) assert.NoError(t, err) assert.Equal(t, "value", decoded["key"]) assert.Equal(t, 3.0, decoded["count"]) } func TestRespondJSON_SliceData(t *testing.T) { t.Parallel() data := []string{"a", "b", "c"} w := httptest.NewRecorder() RespondJSON(w, http.StatusOK, data) var decoded []string err := json.Unmarshal(w.Body.Bytes(), &decoded) assert.NoError(t, err) assert.Equal(t, []string{"a", "b", "c"}, decoded) } func TestRespondJSON_EmptySlice(t *testing.T) { t.Parallel() data := []int{} w := httptest.NewRecorder() RespondJSON(w, http.StatusOK, data) assert.Equal(t, "[]\n", w.Body.String()) } func TestRespondJSON_VariousStatusCodes(t *testing.T) { t.Parallel() tests := []struct { name string status int }{ {name: "ok", status: http.StatusOK}, {name: "created", status: http.StatusCreated}, {name: "no_content", status: http.StatusNoContent}, {name: "bad_request", status: http.StatusBadRequest}, {name: "unauthorized", status: http.StatusUnauthorized}, {name: "forbidden", status: http.StatusForbidden}, {name: "not_found", status: http.StatusNotFound}, {name: "internal_error", status: http.StatusInternalServerError}, } for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() w := httptest.NewRecorder() RespondJSON(w, tt.status, map[string]string{"status": tt.name}) assert.Equal(t, tt.status, w.Code) assert.Equal(t, "application/json", w.Header().Get("Content-Type")) }) } }