github.com/hellobchain/third_party@v0.0.0-20230331131523-deb0478a2e52/gin/binding/binding_msgpack_test.go (about)

     1  // Copyright 2020 Gin Core Team. All rights reserved.
     2  // Use of this source code is governed by a MIT style
     3  // license that can be found in the LICENSE file.
     4  
     5  //go:build !nomsgpack
     6  // +build !nomsgpack
     7  
     8  package binding
     9  
    10  import (
    11  	"bytes"
    12  	"testing"
    13  
    14  	"github.com/stretchr/testify/assert"
    15  	"github.com/ugorji/go/codec"
    16  )
    17  
    18  func TestBindingMsgPack(t *testing.T) {
    19  	test := FooStruct{
    20  		Foo: "bar",
    21  	}
    22  
    23  	h := new(codec.MsgpackHandle)
    24  	assert.NotNil(t, h)
    25  	buf := bytes.NewBuffer([]byte{})
    26  	assert.NotNil(t, buf)
    27  	err := codec.NewEncoder(buf, h).Encode(test)
    28  	assert.NoError(t, err)
    29  
    30  	data := buf.Bytes()
    31  
    32  	testMsgPackBodyBinding(t,
    33  		MsgPack, "msgpack",
    34  		"/", "/",
    35  		string(data), string(data[1:]))
    36  }
    37  
    38  func testMsgPackBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
    39  	assert.Equal(t, name, b.Name())
    40  
    41  	obj := FooStruct{}
    42  	req := requestWithBody("POST", path, body)
    43  	req.Header.Add("Content-Type", MIMEMSGPACK)
    44  	err := b.Bind(req, &obj)
    45  	assert.NoError(t, err)
    46  	assert.Equal(t, "bar", obj.Foo)
    47  
    48  	obj = FooStruct{}
    49  	req = requestWithBody("POST", badPath, badBody)
    50  	req.Header.Add("Content-Type", MIMEMSGPACK)
    51  	err = MsgPack.Bind(req, &obj)
    52  	assert.Error(t, err)
    53  }
    54  
    55  func TestBindingDefaultMsgPack(t *testing.T) {
    56  	assert.Equal(t, MsgPack, Default("POST", MIMEMSGPACK))
    57  	assert.Equal(t, MsgPack, Default("PUT", MIMEMSGPACK2))
    58  }