Files
cms-server/utils/response_test.go
Asai Neko 210b8b08ce
All checks were successful
Server Check Build (NixCN CMS) TeamCity build finished
Add test for all components
Signed-off-by: Asai Neko <sugar@sne.moe>
2026-03-26 18:19:26 +08:00

79 lines
2.0 KiB
Go

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())
}