binding_body_test.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package binding
  2. import (
  3. "bytes"
  4. "io/ioutil"
  5. "testing"
  6. "github.com/gin-gonic/gin/binding/example"
  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 bidning",
  20. binding: JSON,
  21. body: `{"foo":"FOO"}`,
  22. },
  23. {
  24. name: "XML bidning",
  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. t.Logf("testing: %s", tt.name)
  38. req := requestWithBody("POST", "/", tt.body)
  39. form := FooStruct{}
  40. body, _ := ioutil.ReadAll(req.Body)
  41. assert.NoError(t, tt.binding.BindBody(body, &form))
  42. assert.Equal(t, FooStruct{"FOO"}, form)
  43. }
  44. }
  45. func msgPackBody(t *testing.T) string {
  46. test := FooStruct{"FOO"}
  47. h := new(codec.MsgpackHandle)
  48. buf := bytes.NewBuffer(nil)
  49. assert.NoError(t, codec.NewEncoder(buf, h).Encode(test))
  50. return buf.String()
  51. }
  52. func TestBindingBodyProto(t *testing.T) {
  53. test := example.Test{
  54. Label: proto.String("FOO"),
  55. }
  56. data, _ := proto.Marshal(&test)
  57. req := requestWithBody("POST", "/", string(data))
  58. form := example.Test{}
  59. body, _ := ioutil.ReadAll(req.Body)
  60. assert.NoError(t, ProtoBuf.BindBody(body, &form))
  61. assert.Equal(t, test, form)
  62. }