gin/binding/binding_body_test.go

74 lines
1.6 KiB
Go
Raw Normal View History

package binding
import (
"bytes"
"io/ioutil"
"testing"
2019-04-17 17:10:21 +03:00
"github.com/gin-gonic/gin/binding/common"
"github.com/gin-gonic/gin/testdata/protoexample"
"github.com/golang/protobuf/proto"
"github.com/stretchr/testify/assert"
"github.com/ugorji/go/codec"
)
func TestBindingBody(t *testing.T) {
for _, tt := range []struct {
name string
2019-04-17 17:10:21 +03:00
binding common.BindingBody
body string
want string
}{
{
name: "JSON binding",
2019-04-17 17:10:21 +03:00
binding: JSON(),
body: `{"foo":"FOO"}`,
},
{
name: "XML binding",
2019-04-17 17:10:21 +03:00
binding: XML(),
body: `<?xml version="1.0" encoding="UTF-8"?>
<root>
<foo>FOO</foo>
</root>`,
},
{
name: "MsgPack binding",
2019-04-17 17:10:21 +03:00
binding: MsgPack(),
body: msgPackBody(t),
},
{
name: "YAML binding",
2019-04-17 17:10:21 +03:00
binding: YAML(),
body: `foo: FOO`,
},
} {
t.Logf("testing: %s", tt.name)
req := requestWithBody("POST", "/", tt.body)
form := FooStruct{}
body, _ := ioutil.ReadAll(req.Body)
assert.NoError(t, tt.binding.BindBody(body, &form))
assert.Equal(t, FooStruct{"FOO"}, form)
}
}
func msgPackBody(t *testing.T) string {
test := FooStruct{"FOO"}
h := new(codec.MsgpackHandle)
buf := bytes.NewBuffer(nil)
assert.NoError(t, codec.NewEncoder(buf, h).Encode(test))
return buf.String()
}
func TestBindingBodyProto(t *testing.T) {
test := protoexample.Test{
Label: proto.String("FOO"),
}
data, _ := proto.Marshal(&test)
req := requestWithBody("POST", "/", string(data))
form := protoexample.Test{}
body, _ := ioutil.ReadAll(req.Body)
2019-04-17 17:10:21 +03:00
assert.NoError(t, ProtoBuf().BindBody(body, &form))
assert.Equal(t, test, form)
}