binding_body_test.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package binding
  2. import (
  3. "bytes"
  4. "io/ioutil"
  5. "testing"
  6. "github.com/gin-gonic/gin/testdata/protoexample"
  7. "github.com/golang/protobuf/proto"
  8. "github.com/stretchr/testify/assert"
  9. "github.com/ugorji/go/codec"
  10. )
  11. func TestBindingBody(t *testing.T) {
  12. for _, tt := range []struct {
  13. name string
  14. binding BindingBody
  15. body string
  16. want string
  17. }{
  18. {
  19. name: "JSON binding",
  20. binding: JSON,
  21. body: `{"foo":"FOO"}`,
  22. },
  23. {
  24. name: "XML binding",
  25. binding: XML,
  26. body: `<?xml version="1.0" encoding="UTF-8"?>
  27. <root>
  28. <foo>FOO</foo>
  29. </root>`,
  30. },
  31. {
  32. name: "MsgPack binding",
  33. binding: MsgPack,
  34. body: msgPackBody(t),
  35. },
  36. {
  37. name: "YAML binding",
  38. binding: YAML,
  39. body: `foo: FOO`,
  40. },
  41. } {
  42. t.Logf("testing: %s", tt.name)
  43. req := requestWithBody("POST", "/", tt.body)
  44. form := FooStruct{}
  45. body, _ := ioutil.ReadAll(req.Body)
  46. assert.NoError(t, tt.binding.BindBody(body, &form))
  47. assert.Equal(t, FooStruct{"FOO"}, form)
  48. }
  49. }
  50. func msgPackBody(t *testing.T) string {
  51. test := FooStruct{"FOO"}
  52. h := new(codec.MsgpackHandle)
  53. buf := bytes.NewBuffer(nil)
  54. assert.NoError(t, codec.NewEncoder(buf, h).Encode(test))
  55. return buf.String()
  56. }
  57. func TestBindingBodyProto(t *testing.T) {
  58. test := protoexample.Test{
  59. Label: proto.String("FOO"),
  60. }
  61. data, _ := proto.Marshal(&test)
  62. req := requestWithBody("POST", "/", string(data))
  63. form := protoexample.Test{}
  64. body, _ := ioutil.ReadAll(req.Body)
  65. assert.NoError(t, ProtoBuf.BindBody(body, &form))
  66. assert.Equal(t, test, form)
  67. }