binding_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // Copyright 2014 Manu Martinez-Almeida. 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. package binding
  5. import (
  6. "bytes"
  7. "net/http"
  8. "testing"
  9. "github.com/stretchr/testify/assert"
  10. )
  11. type FooStruct struct {
  12. Foo string `json:"foo" form:"foo" xml:"foo" binding:"required"`
  13. }
  14. func TestBindingDefault(t *testing.T) {
  15. assert.Equal(t, Default("GET", ""), Form)
  16. assert.Equal(t, Default("GET", MIMEJSON), Form)
  17. assert.Equal(t, Default("POST", MIMEJSON), JSON)
  18. assert.Equal(t, Default("PUT", MIMEJSON), JSON)
  19. assert.Equal(t, Default("POST", MIMEXML), XML)
  20. assert.Equal(t, Default("PUT", MIMEXML2), XML)
  21. assert.Equal(t, Default("POST", MIMEPOSTForm), Form)
  22. assert.Equal(t, Default("DELETE", MIMEPOSTForm), Form)
  23. }
  24. func TestBindingJSON(t *testing.T) {
  25. testBodyBinding(t,
  26. JSON, "json",
  27. "/", "/",
  28. `{"foo": "bar"}`, `{"bar": "foo"}`)
  29. }
  30. func TestBindingForm(t *testing.T) {
  31. testFormBinding(t, "POST",
  32. "/", "/",
  33. "foo=bar", "bar=foo")
  34. }
  35. func TestBindingForm2(t *testing.T) {
  36. testFormBinding(t, "GET",
  37. "/?foo=bar", "/?bar=foo",
  38. "", "")
  39. }
  40. func TestBindingXML(t *testing.T) {
  41. testBodyBinding(t,
  42. XML, "xml",
  43. "/", "/",
  44. "<map><foo>bar</foo></map>", "<map><bar>foo</bar></map>")
  45. }
  46. func testFormBinding(t *testing.T, method, path, badPath, body, badBody string) {
  47. b := Form
  48. assert.Equal(t, b.Name(), "query")
  49. obj := FooStruct{}
  50. req := requestWithBody(method, path, body)
  51. if method == "POST" {
  52. req.Header.Add("Content-Type", MIMEPOSTForm)
  53. }
  54. err := b.Bind(req, &obj)
  55. assert.NoError(t, err)
  56. assert.Equal(t, obj.Foo, "bar")
  57. obj = FooStruct{}
  58. req = requestWithBody(method, badPath, badBody)
  59. err = JSON.Bind(req, &obj)
  60. assert.Error(t, err)
  61. }
  62. func testBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
  63. assert.Equal(t, b.Name(), name)
  64. obj := FooStruct{}
  65. req := requestWithBody("POST", path, body)
  66. err := b.Bind(req, &obj)
  67. assert.NoError(t, err)
  68. assert.Equal(t, obj.Foo, "bar")
  69. obj = FooStruct{}
  70. req = requestWithBody("POST", badPath, badBody)
  71. err = JSON.Bind(req, &obj)
  72. assert.Error(t, err)
  73. }
  74. func requestWithBody(method, path, body string) (req *http.Request) {
  75. req, _ = http.NewRequest(method, path, bytes.NewBufferString(body))
  76. return
  77. }