2020-01-07 06:31:10 +03:00
|
|
|
// Copyright 2020 Gin Core Team. All rights reserved.
|
|
|
|
// Use of this source code is governed by a MIT style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
2021-03-27 04:09:44 +03:00
|
|
|
//go:build !nomsgpack
|
2020-01-07 06:31:10 +03:00
|
|
|
|
|
|
|
package binding
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/stretchr/testify/assert"
|
2024-07-14 15:33:08 +03:00
|
|
|
"github.com/stretchr/testify/require"
|
2020-01-07 06:31:10 +03:00
|
|
|
"github.com/ugorji/go/codec"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestBindingMsgPack(t *testing.T) {
|
|
|
|
test := FooStruct{
|
|
|
|
Foo: "bar",
|
|
|
|
}
|
|
|
|
|
|
|
|
h := new(codec.MsgpackHandle)
|
|
|
|
assert.NotNil(t, h)
|
|
|
|
buf := bytes.NewBuffer([]byte{})
|
|
|
|
assert.NotNil(t, buf)
|
|
|
|
err := codec.NewEncoder(buf, h).Encode(test)
|
2024-07-14 15:33:08 +03:00
|
|
|
require.NoError(t, err)
|
2020-01-07 06:31:10 +03:00
|
|
|
|
|
|
|
data := buf.Bytes()
|
|
|
|
|
|
|
|
testMsgPackBodyBinding(t,
|
|
|
|
MsgPack, "msgpack",
|
|
|
|
"/", "/",
|
|
|
|
string(data), string(data[1:]))
|
|
|
|
}
|
|
|
|
|
|
|
|
func testMsgPackBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
|
|
|
|
assert.Equal(t, name, b.Name())
|
|
|
|
|
|
|
|
obj := FooStruct{}
|
|
|
|
req := requestWithBody("POST", path, body)
|
|
|
|
req.Header.Add("Content-Type", MIMEMSGPACK)
|
|
|
|
err := b.Bind(req, &obj)
|
2024-07-14 15:33:08 +03:00
|
|
|
require.NoError(t, err)
|
2020-01-07 06:31:10 +03:00
|
|
|
assert.Equal(t, "bar", obj.Foo)
|
|
|
|
|
|
|
|
obj = FooStruct{}
|
|
|
|
req = requestWithBody("POST", badPath, badBody)
|
|
|
|
req.Header.Add("Content-Type", MIMEMSGPACK)
|
|
|
|
err = MsgPack.Bind(req, &obj)
|
2024-07-14 15:33:08 +03:00
|
|
|
require.Error(t, err)
|
2020-01-07 06:31:10 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func TestBindingDefaultMsgPack(t *testing.T) {
|
|
|
|
assert.Equal(t, MsgPack, Default("POST", MIMEMSGPACK))
|
|
|
|
assert.Equal(t, MsgPack, Default("PUT", MIMEMSGPACK2))
|
|
|
|
}
|