package utils import ( "encoding/json" "net/http" "net/http/httptest" "testing" "github.com/gin-gonic/gin" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func init() { gin.SetMode(gin.TestMode) } func newTestContext() (*gin.Context, *httptest.ResponseRecorder) { w := httptest.NewRecorder() c, _ := gin.CreateTestContext(w) c.Request = httptest.NewRequest(http.MethodGet, "/", nil) return c, w } func TestHttpResponseNoData(t *testing.T) { c, w := newTestContext() HttpResponse(c, http.StatusOK, "2ep_svc100000") assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type")) var resp RespStatus require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp)) assert.Equal(t, http.StatusOK, resp.Code) assert.Equal(t, "OK", resp.Status) assert.Equal(t, "2ep_svc100000", resp.ErrorId) assert.Nil(t, resp.Data) } func TestHttpResponseWithData(t *testing.T) { c, w := newTestContext() payload := map[string]string{"key": "value"} HttpResponse(c, http.StatusOK, "2ep_svc100000", payload) var resp RespStatus require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp)) data, ok := resp.Data.(map[string]any) require.True(t, ok) assert.Equal(t, "value", data["key"]) } func TestHttpResponseWithMultipleData(t *testing.T) { c, w := newTestContext() HttpResponse(c, http.StatusOK, "code", "a", "b") var resp RespStatus require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp)) // Multiple data items are returned as a slice slice, ok := resp.Data.([]any) require.True(t, ok) assert.Len(t, slice, 2) } func TestHttpResponse4xx(t *testing.T) { c, w := newTestContext() HttpResponse(c, http.StatusBadRequest, "errcode") assert.Equal(t, http.StatusBadRequest, w.Code) } func TestHttpAbortSetsAbortedFlag(t *testing.T) { c, w := newTestContext() HttpAbort(c, http.StatusUnauthorized, "errcode") assert.Equal(t, http.StatusUnauthorized, w.Code) // gin marks the context as aborted assert.True(t, c.IsAborted()) }