Files
iotlcm/server/internal/logic/middleware/channel_test_response_test.go
T
2026-10-29 14:36:49 +08:00

69 lines
2.2 KiB
Go

package middleware
import (
"encoding/json"
"net/http"
"strconv"
"testing"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
"git.5iot.com/iotlcm-public/iotlcm-admin-svr/internal/model"
)
func TestChannelTestErrorResponsePreservesOriginalError(t *testing.T) {
const raw = `{"code":50,"message":"channel is not accessible","data":null}`
server := g.Server(t.Name())
server.SetAddr("127.0.0.1:0")
server.SetDumpRouterMap(false)
server.Group("/", func(group *ghttp.RouterGroup) {
group.Middleware(New().ResponseHandler)
group.GET("/plain", func(r *ghttp.Request) {
r.SetError(gerror.New("channel is not accessible"))
})
group.GET("/diagnostic", func(r *ghttp.Request) {
r.SetError(&model.TSimChannelsTestError{Err: gerror.New("channel is not accessible"), GatewayResponseRaw: raw})
})
group.GET("/coded", func(r *ghttp.Request) {
r.SetError(&model.TSimChannelsTestError{Err: gerror.NewCode(gcode.CodeInvalidParameter, "invalid input"), GatewayResponseRaw: raw})
})
})
if err := server.Start(); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = server.Shutdown() })
for _, tc := range []struct {
path string
code int
message string
raw string
}{
{"/plain", gcode.CodeInternalError.Code(), "channel is not accessible", ""},
{"/diagnostic", gcode.CodeInternalError.Code(), "channel is not accessible", raw},
{"/coded", gcode.CodeInvalidParameter.Code(), "invalid input", raw},
} {
t.Run(tc.path, func(t *testing.T) {
res, err := http.Get("http://127.0.0.1:" + strconv.Itoa(server.GetListenedPort()) + tc.path)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
var body struct {
Code int `json:"code"`
Message string `json:"message"`
Data struct {
GatewayResponseRaw string `json:"gatewayResponseRaw"`
} `json:"data"`
}
if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
t.Fatal(err)
}
if res.StatusCode != http.StatusOK || body.Code != tc.code || body.Message != tc.message || body.Data.GatewayResponseRaw != tc.raw {
t.Fatalf("unexpected response: status=%d body=%+v", res.StatusCode, body)
}
})
}
}