2018-05-11 05:33:33 +03:00
|
|
|
package binding
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"io/ioutil"
|
|
|
|
"testing"
|
|
|
|
|
2018-08-12 18:38:31 +03:00
|
|
|
"github.com/gin-gonic/gin/testdata/protoexample"
|
2018-05-11 05:33:33 +03:00
|
|
|
"github.com/golang/protobuf/proto"
|
|
|
|
"github.com/stretchr/testify/assert"
|
2019-07-05 15:53:26 +03:00
|
|
|
"github.com/vmihailenco/msgpack"
|
2018-05-11 05:33:33 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestBindingBody(t *testing.T) {
|
|
|
|
for _, tt := range []struct {
|
|
|
|
name string
|
|
|
|
binding BindingBody
|
|
|
|
body string
|
|
|
|
want string
|
|
|
|
}{
|
|
|
|
{
|
2018-11-06 04:49:45 +03:00
|
|
|
name: "JSON binding",
|
2018-05-11 05:33:33 +03:00
|
|
|
binding: JSON,
|
|
|
|
body: `{"foo":"FOO"}`,
|
|
|
|
},
|
|
|
|
{
|
2018-11-06 04:49:45 +03:00
|
|
|
name: "XML binding",
|
2018-05-11 05:33:33 +03:00
|
|
|
binding: XML,
|
|
|
|
body: `<?xml version="1.0" encoding="UTF-8"?>
|
|
|
|
<root>
|
|
|
|
<foo>FOO</foo>
|
|
|
|
</root>`,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
name: "MsgPack binding",
|
|
|
|
binding: MsgPack,
|
|
|
|
body: msgPackBody(t),
|
|
|
|
},
|
2018-11-06 04:49:45 +03:00
|
|
|
{
|
|
|
|
name: "YAML binding",
|
|
|
|
binding: YAML,
|
|
|
|
body: `foo: FOO`,
|
|
|
|
},
|
2018-05-11 05:33:33 +03:00
|
|
|
} {
|
|
|
|
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"}
|
|
|
|
buf := bytes.NewBuffer(nil)
|
2019-07-05 15:53:26 +03:00
|
|
|
assert.NoError(t, msgpack.NewEncoder(buf).Encode(test))
|
2018-05-11 05:33:33 +03:00
|
|
|
return buf.String()
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestBindingBodyProto(t *testing.T) {
|
2018-08-12 18:38:31 +03:00
|
|
|
test := protoexample.Test{
|
2018-05-11 05:33:33 +03:00
|
|
|
Label: proto.String("FOO"),
|
|
|
|
}
|
|
|
|
data, _ := proto.Marshal(&test)
|
|
|
|
req := requestWithBody("POST", "/", string(data))
|
2018-08-12 18:38:31 +03:00
|
|
|
form := protoexample.Test{}
|
2018-05-11 05:33:33 +03:00
|
|
|
body, _ := ioutil.ReadAll(req.Body)
|
|
|
|
assert.NoError(t, ProtoBuf.BindBody(body, &form))
|
|
|
|
assert.Equal(t, test, form)
|
|
|
|
}
|