binding_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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", ""), GETForm)
  16. assert.Equal(t, Default("GET", MIMEJSON), GETForm)
  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), POSTForm)
  22. assert.Equal(t, Default("DELETE", MIMEPOSTForm), POSTForm)
  23. }
  24. func TestBindingJSON(t *testing.T) {
  25. testBinding(t,
  26. JSON, "json",
  27. "/", "/",
  28. `{"foo": "bar"}`, `{"bar": "foo"}`)
  29. }
  30. func TestBindingPOSTForm(t *testing.T) {
  31. testBinding(t,
  32. POSTForm, "post_form",
  33. "/", "/",
  34. "foo=bar", "bar=foo")
  35. }
  36. func TestBindingGETForm(t *testing.T) {
  37. testBinding(t,
  38. GETForm, "get_form",
  39. "/?foo=bar", "/?bar=foo",
  40. "", "")
  41. }
  42. func TestBindingXML(t *testing.T) {
  43. testBinding(t,
  44. XML, "xml",
  45. "/", "/",
  46. "<map><foo>bar</foo></map>", "<map><bar>foo</bar></map>")
  47. }
  48. func testBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
  49. assert.Equal(t, b.Name(), name)
  50. obj := FooStruct{}
  51. req := requestWithBody(path, body)
  52. err := b.Bind(req, &obj)
  53. assert.NoError(t, err)
  54. assert.Equal(t, obj.Foo, "bar")
  55. obj = FooStruct{}
  56. req = requestWithBody(badPath, badBody)
  57. err = JSON.Bind(req, &obj)
  58. assert.Error(t, err)
  59. }
  60. func requestWithBody(path, body string) (req *http.Request) {
  61. req, _ = http.NewRequest("POST", path, bytes.NewBufferString(body))
  62. return
  63. }