You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
76 lines
2.1 KiB
Go
76 lines
2.1 KiB
Go
package server
|
|
|
|
import (
|
|
"encoding/json"
|
|
"reflect"
|
|
"testing"
|
|
|
|
"github.com/noahlann/nnet/internal/codec"
|
|
internalrequest "github.com/noahlann/nnet/internal/request"
|
|
protocolpkg "github.com/noahlann/nnet/pkg/protocol"
|
|
routerpkg "github.com/noahlann/nnet/pkg/router"
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
type fakeRoute struct {
|
|
reqType reflect.Type
|
|
codecName string
|
|
}
|
|
|
|
func (r *fakeRoute) Use(middleware ...routerpkg.Handler) routerpkg.Route { return r }
|
|
func (r *fakeRoute) Handler() routerpkg.Handler { return nil }
|
|
func (r *fakeRoute) RequestType() reflect.Type { return r.reqType }
|
|
func (r *fakeRoute) ResponseType() reflect.Type { return nil }
|
|
func (r *fakeRoute) CodecName() string { return r.codecName }
|
|
|
|
type userDTO struct {
|
|
Name string `json:"name"`
|
|
Age int `json:"age"`
|
|
}
|
|
|
|
func TestParseRequestBody_JSON_StructDecode(t *testing.T) {
|
|
// Prepare JSON body
|
|
bodyMap := map[string]interface{}{"name": "alice", "age": 30}
|
|
bodyBytes, _ := json.Marshal(bodyMap)
|
|
|
|
// Internal request with raw bytes
|
|
req := internalrequest.New(bodyBytes, nil)
|
|
|
|
// Route expects *userDTO and JSON codec
|
|
rt := &fakeRoute{
|
|
reqType: reflect.TypeOf(&userDTO{}),
|
|
codecName: "json",
|
|
}
|
|
|
|
reg := codec.NewRegistry()
|
|
_ = reg.Register("json", codec.NewJSONCodec())
|
|
jsonCodec, _ := reg.Get("json")
|
|
err := parseRequestBodyWithCodec(req, rt, protocolpkg.Protocol(nil), jsonCodec)
|
|
require.NoError(t, err)
|
|
|
|
// Data should be decoded into *userDTO
|
|
data := req.Data()
|
|
require.NotNil(t, data)
|
|
u, ok := data.(*userDTO)
|
|
require.True(t, ok)
|
|
assert.Equal(t, "alice", u.Name)
|
|
assert.Equal(t, 30, u.Age)
|
|
}
|
|
|
|
func TestParseRequestBody_InvalidRequestType(t *testing.T) {
|
|
// Use a request that does not support setter
|
|
fr := &fakeRequestNoSetterFull{}
|
|
rt := &fakeRoute{
|
|
reqType: reflect.TypeOf(&userDTO{}),
|
|
codecName: "json",
|
|
}
|
|
reg := codec.NewRegistry()
|
|
_ = reg.Register("json", codec.NewJSONCodec())
|
|
jsonCodec, _ := reg.Get("json")
|
|
err := parseRequestBodyWithCodec(fr, rt, nil, jsonCodec)
|
|
require.Error(t, err)
|
|
}
|
|
|
|
|