binding_test.go 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432
  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. "encoding/json"
  8. "errors"
  9. "io/ioutil"
  10. "mime/multipart"
  11. "net/http"
  12. "strconv"
  13. "strings"
  14. "testing"
  15. "time"
  16. "github.com/gin-gonic/gin/testdata/protoexample"
  17. "github.com/golang/protobuf/proto"
  18. "github.com/stretchr/testify/assert"
  19. "github.com/ugorji/go/codec"
  20. )
  21. type FooStruct struct {
  22. Foo string `msgpack:"foo" json:"foo" form:"foo" xml:"foo" binding:"required"`
  23. }
  24. type FooBarStruct struct {
  25. FooStruct
  26. Bar string `msgpack:"bar" json:"bar" form:"bar" xml:"bar" binding:"required"`
  27. }
  28. type FooDefaultBarStruct struct {
  29. FooStruct
  30. Bar string `msgpack:"bar" json:"bar" form:"bar,default=hello" xml:"bar" binding:"required"`
  31. }
  32. type FooStructUseNumber struct {
  33. Foo interface{} `json:"foo" binding:"required"`
  34. }
  35. type FooBarStructForTimeType struct {
  36. TimeFoo time.Time `form:"time_foo" time_format:"2006-01-02" time_utc:"1" time_location:"Asia/Chongqing"`
  37. TimeBar time.Time `form:"time_bar" time_format:"2006-01-02" time_utc:"1"`
  38. }
  39. type FooStructForTimeTypeNotFormat struct {
  40. TimeFoo time.Time `form:"time_foo"`
  41. }
  42. type FooStructForTimeTypeFailFormat struct {
  43. TimeFoo time.Time `form:"time_foo" time_format:"2017-11-15"`
  44. }
  45. type FooStructForTimeTypeFailLocation struct {
  46. TimeFoo time.Time `form:"time_foo" time_format:"2006-01-02" time_location:"/asia/chongqing"`
  47. }
  48. type FooStructForMapType struct {
  49. MapFoo map[string]interface{} `form:"map_foo"`
  50. }
  51. type FooStructForIgnoreFormTag struct {
  52. Foo *string `form:"-"`
  53. }
  54. type InvalidNameType struct {
  55. TestName string `invalid_name:"test_name"`
  56. }
  57. type InvalidNameMapType struct {
  58. TestName struct {
  59. MapFoo map[string]interface{} `form:"map_foo"`
  60. }
  61. }
  62. type FooStructForSliceType struct {
  63. SliceFoo []int `form:"slice_foo"`
  64. }
  65. type FooStructForStructType struct {
  66. StructFoo struct {
  67. Idx int `form:"idx"`
  68. }
  69. }
  70. type FooStructForStructPointerType struct {
  71. StructPointerFoo *struct {
  72. Name string `form:"name"`
  73. }
  74. }
  75. type FooStructForSliceMapType struct {
  76. // Unknown type: not support map
  77. SliceMapFoo []map[string]interface{} `form:"slice_map_foo"`
  78. }
  79. type FooStructForBoolType struct {
  80. BoolFoo bool `form:"bool_foo"`
  81. }
  82. type FooBarStructForIntType struct {
  83. IntFoo int `form:"int_foo"`
  84. IntBar int `form:"int_bar" binding:"required"`
  85. }
  86. type FooBarStructForInt8Type struct {
  87. Int8Foo int8 `form:"int8_foo"`
  88. Int8Bar int8 `form:"int8_bar" binding:"required"`
  89. }
  90. type FooBarStructForInt16Type struct {
  91. Int16Foo int16 `form:"int16_foo"`
  92. Int16Bar int16 `form:"int16_bar" binding:"required"`
  93. }
  94. type FooBarStructForInt32Type struct {
  95. Int32Foo int32 `form:"int32_foo"`
  96. Int32Bar int32 `form:"int32_bar" binding:"required"`
  97. }
  98. type FooBarStructForInt64Type struct {
  99. Int64Foo int64 `form:"int64_foo"`
  100. Int64Bar int64 `form:"int64_bar" binding:"required"`
  101. }
  102. type FooBarStructForUintType struct {
  103. UintFoo uint `form:"uint_foo"`
  104. UintBar uint `form:"uint_bar" binding:"required"`
  105. }
  106. type FooBarStructForUint8Type struct {
  107. Uint8Foo uint8 `form:"uint8_foo"`
  108. Uint8Bar uint8 `form:"uint8_bar" binding:"required"`
  109. }
  110. type FooBarStructForUint16Type struct {
  111. Uint16Foo uint16 `form:"uint16_foo"`
  112. Uint16Bar uint16 `form:"uint16_bar" binding:"required"`
  113. }
  114. type FooBarStructForUint32Type struct {
  115. Uint32Foo uint32 `form:"uint32_foo"`
  116. Uint32Bar uint32 `form:"uint32_bar" binding:"required"`
  117. }
  118. type FooBarStructForUint64Type struct {
  119. Uint64Foo uint64 `form:"uint64_foo"`
  120. Uint64Bar uint64 `form:"uint64_bar" binding:"required"`
  121. }
  122. type FooBarStructForBoolType struct {
  123. BoolFoo bool `form:"bool_foo"`
  124. BoolBar bool `form:"bool_bar" binding:"required"`
  125. }
  126. type FooBarStructForFloat32Type struct {
  127. Float32Foo float32 `form:"float32_foo"`
  128. Float32Bar float32 `form:"float32_bar" binding:"required"`
  129. }
  130. type FooBarStructForFloat64Type struct {
  131. Float64Foo float64 `form:"float64_foo"`
  132. Float64Bar float64 `form:"float64_bar" binding:"required"`
  133. }
  134. type FooStructForStringPtrType struct {
  135. PtrFoo *string `form:"ptr_foo"`
  136. PtrBar *string `form:"ptr_bar" binding:"required"`
  137. }
  138. type FooStructForMapPtrType struct {
  139. PtrBar *map[string]interface{} `form:"ptr_bar"`
  140. }
  141. func TestBindingDefault(t *testing.T) {
  142. assert.Equal(t, Form, Default("GET", ""))
  143. assert.Equal(t, Form, Default("GET", MIMEJSON))
  144. assert.Equal(t, JSON, Default("POST", MIMEJSON))
  145. assert.Equal(t, JSON, Default("PUT", MIMEJSON))
  146. assert.Equal(t, XML, Default("POST", MIMEXML))
  147. assert.Equal(t, XML, Default("PUT", MIMEXML2))
  148. assert.Equal(t, Form, Default("POST", MIMEPOSTForm))
  149. assert.Equal(t, Form, Default("PUT", MIMEPOSTForm))
  150. assert.Equal(t, Form, Default("POST", MIMEMultipartPOSTForm))
  151. assert.Equal(t, Form, Default("PUT", MIMEMultipartPOSTForm))
  152. assert.Equal(t, ProtoBuf, Default("POST", MIMEPROTOBUF))
  153. assert.Equal(t, ProtoBuf, Default("PUT", MIMEPROTOBUF))
  154. assert.Equal(t, MsgPack, Default("POST", MIMEMSGPACK))
  155. assert.Equal(t, MsgPack, Default("PUT", MIMEMSGPACK2))
  156. assert.Equal(t, YAML, Default("POST", MIMEYAML))
  157. assert.Equal(t, YAML, Default("PUT", MIMEYAML))
  158. }
  159. func TestBindingJSONNilBody(t *testing.T) {
  160. var obj FooStruct
  161. req, _ := http.NewRequest(http.MethodPost, "/", nil)
  162. err := JSON.Bind(req, &obj)
  163. assert.Error(t, err)
  164. }
  165. func TestBindingJSON(t *testing.T) {
  166. testBodyBinding(t,
  167. JSON, "json",
  168. "/", "/",
  169. `{"foo": "bar"}`, `{"bar": "foo"}`)
  170. }
  171. func TestBindingJSONUseNumber(t *testing.T) {
  172. testBodyBindingUseNumber(t,
  173. JSON, "json",
  174. "/", "/",
  175. `{"foo": 123}`, `{"bar": "foo"}`)
  176. }
  177. func TestBindingJSONUseNumber2(t *testing.T) {
  178. testBodyBindingUseNumber2(t,
  179. JSON, "json",
  180. "/", "/",
  181. `{"foo": 123}`, `{"bar": "foo"}`)
  182. }
  183. func TestBindingForm(t *testing.T) {
  184. testFormBinding(t, "POST",
  185. "/", "/",
  186. "foo=bar&bar=foo", "bar2=foo")
  187. }
  188. func TestBindingForm2(t *testing.T) {
  189. testFormBinding(t, "GET",
  190. "/?foo=bar&bar=foo", "/?bar2=foo",
  191. "", "")
  192. }
  193. func TestBindingFormDefaultValue(t *testing.T) {
  194. testFormBindingDefaultValue(t, "POST",
  195. "/", "/",
  196. "foo=bar", "bar2=foo")
  197. }
  198. func TestBindingFormDefaultValue2(t *testing.T) {
  199. testFormBindingDefaultValue(t, "GET",
  200. "/?foo=bar", "/?bar2=foo",
  201. "", "")
  202. }
  203. func TestBindingFormForTime(t *testing.T) {
  204. testFormBindingForTime(t, "POST",
  205. "/", "/",
  206. "time_foo=2017-11-15&time_bar=", "bar2=foo")
  207. testFormBindingForTimeNotFormat(t, "POST",
  208. "/", "/",
  209. "time_foo=2017-11-15", "bar2=foo")
  210. testFormBindingForTimeFailFormat(t, "POST",
  211. "/", "/",
  212. "time_foo=2017-11-15", "bar2=foo")
  213. testFormBindingForTimeFailLocation(t, "POST",
  214. "/", "/",
  215. "time_foo=2017-11-15", "bar2=foo")
  216. }
  217. func TestBindingFormForTime2(t *testing.T) {
  218. testFormBindingForTime(t, "GET",
  219. "/?time_foo=2017-11-15&time_bar=", "/?bar2=foo",
  220. "", "")
  221. testFormBindingForTimeNotFormat(t, "GET",
  222. "/?time_foo=2017-11-15", "/?bar2=foo",
  223. "", "")
  224. testFormBindingForTimeFailFormat(t, "GET",
  225. "/?time_foo=2017-11-15", "/?bar2=foo",
  226. "", "")
  227. testFormBindingForTimeFailLocation(t, "GET",
  228. "/?time_foo=2017-11-15", "/?bar2=foo",
  229. "", "")
  230. }
  231. func TestFormBindingIgnoreField(t *testing.T) {
  232. testFormBindingIgnoreField(t, "POST",
  233. "/", "/",
  234. "-=bar", "")
  235. }
  236. func TestBindingFormInvalidName(t *testing.T) {
  237. testFormBindingInvalidName(t, "POST",
  238. "/", "/",
  239. "test_name=bar", "bar2=foo")
  240. }
  241. func TestBindingFormInvalidName2(t *testing.T) {
  242. testFormBindingInvalidName2(t, "POST",
  243. "/", "/",
  244. "map_foo=bar", "bar2=foo")
  245. }
  246. func TestBindingFormForType(t *testing.T) {
  247. testFormBindingForType(t, "POST",
  248. "/", "/",
  249. "map_foo={\"bar\":123}", "map_foo=1", "Map")
  250. testFormBindingForType(t, "POST",
  251. "/", "/",
  252. "slice_foo=1&slice_foo=2", "bar2=1&bar2=2", "Slice")
  253. testFormBindingForType(t, "GET",
  254. "/?slice_foo=1&slice_foo=2", "/?bar2=1&bar2=2",
  255. "", "", "Slice")
  256. testFormBindingForType(t, "POST",
  257. "/", "/",
  258. "slice_map_foo=1&slice_map_foo=2", "bar2=1&bar2=2", "SliceMap")
  259. testFormBindingForType(t, "GET",
  260. "/?slice_map_foo=1&slice_map_foo=2", "/?bar2=1&bar2=2",
  261. "", "", "SliceMap")
  262. testFormBindingForType(t, "POST",
  263. "/", "/",
  264. "int_foo=&int_bar=-12", "bar2=-123", "Int")
  265. testFormBindingForType(t, "GET",
  266. "/?int_foo=&int_bar=-12", "/?bar2=-123",
  267. "", "", "Int")
  268. testFormBindingForType(t, "POST",
  269. "/", "/",
  270. "int8_foo=&int8_bar=-12", "bar2=-123", "Int8")
  271. testFormBindingForType(t, "GET",
  272. "/?int8_foo=&int8_bar=-12", "/?bar2=-123",
  273. "", "", "Int8")
  274. testFormBindingForType(t, "POST",
  275. "/", "/",
  276. "int16_foo=&int16_bar=-12", "bar2=-123", "Int16")
  277. testFormBindingForType(t, "GET",
  278. "/?int16_foo=&int16_bar=-12", "/?bar2=-123",
  279. "", "", "Int16")
  280. testFormBindingForType(t, "POST",
  281. "/", "/",
  282. "int32_foo=&int32_bar=-12", "bar2=-123", "Int32")
  283. testFormBindingForType(t, "GET",
  284. "/?int32_foo=&int32_bar=-12", "/?bar2=-123",
  285. "", "", "Int32")
  286. testFormBindingForType(t, "POST",
  287. "/", "/",
  288. "int64_foo=&int64_bar=-12", "bar2=-123", "Int64")
  289. testFormBindingForType(t, "GET",
  290. "/?int64_foo=&int64_bar=-12", "/?bar2=-123",
  291. "", "", "Int64")
  292. testFormBindingForType(t, "POST",
  293. "/", "/",
  294. "uint_foo=&uint_bar=12", "bar2=123", "Uint")
  295. testFormBindingForType(t, "GET",
  296. "/?uint_foo=&uint_bar=12", "/?bar2=123",
  297. "", "", "Uint")
  298. testFormBindingForType(t, "POST",
  299. "/", "/",
  300. "uint8_foo=&uint8_bar=12", "bar2=123", "Uint8")
  301. testFormBindingForType(t, "GET",
  302. "/?uint8_foo=&uint8_bar=12", "/?bar2=123",
  303. "", "", "Uint8")
  304. testFormBindingForType(t, "POST",
  305. "/", "/",
  306. "uint16_foo=&uint16_bar=12", "bar2=123", "Uint16")
  307. testFormBindingForType(t, "GET",
  308. "/?uint16_foo=&uint16_bar=12", "/?bar2=123",
  309. "", "", "Uint16")
  310. testFormBindingForType(t, "POST",
  311. "/", "/",
  312. "uint32_foo=&uint32_bar=12", "bar2=123", "Uint32")
  313. testFormBindingForType(t, "GET",
  314. "/?uint32_foo=&uint32_bar=12", "/?bar2=123",
  315. "", "", "Uint32")
  316. testFormBindingForType(t, "POST",
  317. "/", "/",
  318. "uint64_foo=&uint64_bar=12", "bar2=123", "Uint64")
  319. testFormBindingForType(t, "GET",
  320. "/?uint64_foo=&uint64_bar=12", "/?bar2=123",
  321. "", "", "Uint64")
  322. testFormBindingForType(t, "POST",
  323. "/", "/",
  324. "bool_foo=&bool_bar=true", "bar2=true", "Bool")
  325. testFormBindingForType(t, "GET",
  326. "/?bool_foo=&bool_bar=true", "/?bar2=true",
  327. "", "", "Bool")
  328. testFormBindingForType(t, "POST",
  329. "/", "/",
  330. "float32_foo=&float32_bar=-12.34", "bar2=12.3", "Float32")
  331. testFormBindingForType(t, "GET",
  332. "/?float32_foo=&float32_bar=-12.34", "/?bar2=12.3",
  333. "", "", "Float32")
  334. testFormBindingForType(t, "POST",
  335. "/", "/",
  336. "float64_foo=&float64_bar=-12.34", "bar2=12.3", "Float64")
  337. testFormBindingForType(t, "GET",
  338. "/?float64_foo=&float64_bar=-12.34", "/?bar2=12.3",
  339. "", "", "Float64")
  340. testFormBindingForType(t, "POST",
  341. "/", "/",
  342. "ptr_bar=test", "bar2=test", "Ptr")
  343. testFormBindingForType(t, "GET",
  344. "/?ptr_bar=test", "/?bar2=test",
  345. "", "", "Ptr")
  346. testFormBindingForType(t, "POST",
  347. "/", "/",
  348. "idx=123", "id1=1", "Struct")
  349. testFormBindingForType(t, "GET",
  350. "/?idx=123", "/?id1=1",
  351. "", "", "Struct")
  352. testFormBindingForType(t, "POST",
  353. "/", "/",
  354. "name=thinkerou", "name1=ou", "StructPointer")
  355. testFormBindingForType(t, "GET",
  356. "/?name=thinkerou", "/?name1=ou",
  357. "", "", "StructPointer")
  358. }
  359. func TestBindingQuery(t *testing.T) {
  360. testQueryBinding(t, "POST",
  361. "/?foo=bar&bar=foo", "/",
  362. "foo=unused", "bar2=foo")
  363. }
  364. func TestBindingQuery2(t *testing.T) {
  365. testQueryBinding(t, "GET",
  366. "/?foo=bar&bar=foo", "/?bar2=foo",
  367. "foo=unused", "")
  368. }
  369. func TestBindingQueryFail(t *testing.T) {
  370. testQueryBindingFail(t, "POST",
  371. "/?map_foo=", "/",
  372. "map_foo=unused", "bar2=foo")
  373. }
  374. func TestBindingQueryFail2(t *testing.T) {
  375. testQueryBindingFail(t, "GET",
  376. "/?map_foo=", "/?bar2=foo",
  377. "map_foo=unused", "")
  378. }
  379. func TestBindingQueryBoolFail(t *testing.T) {
  380. testQueryBindingBoolFail(t, "GET",
  381. "/?bool_foo=fasl", "/?bar2=foo",
  382. "bool_foo=unused", "")
  383. }
  384. func TestBindingXML(t *testing.T) {
  385. testBodyBinding(t,
  386. XML, "xml",
  387. "/", "/",
  388. "<map><foo>bar</foo></map>", "<map><bar>foo</bar></map>")
  389. }
  390. func TestBindingXMLFail(t *testing.T) {
  391. testBodyBindingFail(t,
  392. XML, "xml",
  393. "/", "/",
  394. "<map><foo>bar<foo></map>", "<map><bar>foo</bar></map>")
  395. }
  396. func TestBindingYAML(t *testing.T) {
  397. testBodyBinding(t,
  398. YAML, "yaml",
  399. "/", "/",
  400. `foo: bar`, `bar: foo`)
  401. }
  402. func TestBindingYAMLFail(t *testing.T) {
  403. testBodyBindingFail(t,
  404. YAML, "yaml",
  405. "/", "/",
  406. `foo:\nbar`, `bar: foo`)
  407. }
  408. func createFormPostRequest(t *testing.T) *http.Request {
  409. req, err := http.NewRequest("POST", "/?foo=getfoo&bar=getbar", bytes.NewBufferString("foo=bar&bar=foo"))
  410. assert.NoError(t, err)
  411. req.Header.Set("Content-Type", MIMEPOSTForm)
  412. return req
  413. }
  414. func createDefaultFormPostRequest(t *testing.T) *http.Request {
  415. req, err := http.NewRequest("POST", "/?foo=getfoo&bar=getbar", bytes.NewBufferString("foo=bar"))
  416. assert.NoError(t, err)
  417. req.Header.Set("Content-Type", MIMEPOSTForm)
  418. return req
  419. }
  420. func createFormPostRequestForMap(t *testing.T) *http.Request {
  421. req, err := http.NewRequest("POST", "/?map_foo=getfoo", bytes.NewBufferString("map_foo={\"bar\":123}"))
  422. assert.NoError(t, err)
  423. req.Header.Set("Content-Type", MIMEPOSTForm)
  424. return req
  425. }
  426. func createFormPostRequestForMapFail(t *testing.T) *http.Request {
  427. req, err := http.NewRequest("POST", "/?map_foo=getfoo", bytes.NewBufferString("map_foo=hello"))
  428. assert.NoError(t, err)
  429. req.Header.Set("Content-Type", MIMEPOSTForm)
  430. return req
  431. }
  432. func createFormMultipartRequest(t *testing.T) *http.Request {
  433. boundary := "--testboundary"
  434. body := new(bytes.Buffer)
  435. mw := multipart.NewWriter(body)
  436. defer mw.Close()
  437. assert.NoError(t, mw.SetBoundary(boundary))
  438. assert.NoError(t, mw.WriteField("foo", "bar"))
  439. assert.NoError(t, mw.WriteField("bar", "foo"))
  440. req, err := http.NewRequest("POST", "/?foo=getfoo&bar=getbar", body)
  441. assert.NoError(t, err)
  442. req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)
  443. return req
  444. }
  445. func createFormMultipartRequestForMap(t *testing.T) *http.Request {
  446. boundary := "--testboundary"
  447. body := new(bytes.Buffer)
  448. mw := multipart.NewWriter(body)
  449. defer mw.Close()
  450. assert.NoError(t, mw.SetBoundary(boundary))
  451. assert.NoError(t, mw.WriteField("map_foo", "{\"bar\":123, \"name\":\"thinkerou\", \"pai\": 3.14}"))
  452. req, err := http.NewRequest("POST", "/?map_foo=getfoo", body)
  453. assert.NoError(t, err)
  454. req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)
  455. return req
  456. }
  457. func createFormMultipartRequestForMapFail(t *testing.T) *http.Request {
  458. boundary := "--testboundary"
  459. body := new(bytes.Buffer)
  460. mw := multipart.NewWriter(body)
  461. defer mw.Close()
  462. assert.NoError(t, mw.SetBoundary(boundary))
  463. assert.NoError(t, mw.WriteField("map_foo", "3.14"))
  464. req, err := http.NewRequest("POST", "/?map_foo=getfoo", body)
  465. assert.NoError(t, err)
  466. req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)
  467. return req
  468. }
  469. func TestBindingFormPost(t *testing.T) {
  470. req := createFormPostRequest(t)
  471. var obj FooBarStruct
  472. assert.NoError(t, FormPost.Bind(req, &obj))
  473. assert.Equal(t, "form-urlencoded", FormPost.Name())
  474. assert.Equal(t, "bar", obj.Foo)
  475. assert.Equal(t, "foo", obj.Bar)
  476. }
  477. func TestBindingDefaultValueFormPost(t *testing.T) {
  478. req := createDefaultFormPostRequest(t)
  479. var obj FooDefaultBarStruct
  480. assert.NoError(t, FormPost.Bind(req, &obj))
  481. assert.Equal(t, "bar", obj.Foo)
  482. assert.Equal(t, "hello", obj.Bar)
  483. }
  484. func TestBindingFormPostForMap(t *testing.T) {
  485. req := createFormPostRequestForMap(t)
  486. var obj FooStructForMapType
  487. err := FormPost.Bind(req, &obj)
  488. assert.NoError(t, err)
  489. assert.Equal(t, float64(123), obj.MapFoo["bar"].(float64))
  490. }
  491. func TestBindingFormPostForMapFail(t *testing.T) {
  492. req := createFormPostRequestForMapFail(t)
  493. var obj FooStructForMapType
  494. err := FormPost.Bind(req, &obj)
  495. assert.Error(t, err)
  496. }
  497. func TestBindingFormMultipart(t *testing.T) {
  498. req := createFormMultipartRequest(t)
  499. var obj FooBarStruct
  500. assert.NoError(t, FormMultipart.Bind(req, &obj))
  501. assert.Equal(t, "multipart/form-data", FormMultipart.Name())
  502. assert.Equal(t, "bar", obj.Foo)
  503. assert.Equal(t, "foo", obj.Bar)
  504. }
  505. func TestBindingFormMultipartForMap(t *testing.T) {
  506. req := createFormMultipartRequestForMap(t)
  507. var obj FooStructForMapType
  508. err := FormMultipart.Bind(req, &obj)
  509. assert.NoError(t, err)
  510. assert.Equal(t, float64(123), obj.MapFoo["bar"].(float64))
  511. assert.Equal(t, "thinkerou", obj.MapFoo["name"].(string))
  512. assert.Equal(t, float64(3.14), obj.MapFoo["pai"].(float64))
  513. }
  514. func TestBindingFormMultipartForMapFail(t *testing.T) {
  515. req := createFormMultipartRequestForMapFail(t)
  516. var obj FooStructForMapType
  517. err := FormMultipart.Bind(req, &obj)
  518. assert.Error(t, err)
  519. }
  520. func TestBindingProtoBuf(t *testing.T) {
  521. test := &protoexample.Test{
  522. Label: proto.String("yes"),
  523. }
  524. data, _ := proto.Marshal(test)
  525. testProtoBodyBinding(t,
  526. ProtoBuf, "protobuf",
  527. "/", "/",
  528. string(data), string(data[1:]))
  529. }
  530. func TestBindingProtoBufFail(t *testing.T) {
  531. test := &protoexample.Test{
  532. Label: proto.String("yes"),
  533. }
  534. data, _ := proto.Marshal(test)
  535. testProtoBodyBindingFail(t,
  536. ProtoBuf, "protobuf",
  537. "/", "/",
  538. string(data), string(data[1:]))
  539. }
  540. func TestBindingMsgPack(t *testing.T) {
  541. test := FooStruct{
  542. Foo: "bar",
  543. }
  544. h := new(codec.MsgpackHandle)
  545. assert.NotNil(t, h)
  546. buf := bytes.NewBuffer([]byte{})
  547. assert.NotNil(t, buf)
  548. err := codec.NewEncoder(buf, h).Encode(test)
  549. assert.NoError(t, err)
  550. data := buf.Bytes()
  551. testMsgPackBodyBinding(t,
  552. MsgPack, "msgpack",
  553. "/", "/",
  554. string(data), string(data[1:]))
  555. }
  556. func TestValidationFails(t *testing.T) {
  557. var obj FooStruct
  558. req := requestWithBody("POST", "/", `{"bar": "foo"}`)
  559. err := JSON.Bind(req, &obj)
  560. assert.Error(t, err)
  561. }
  562. func TestValidationDisabled(t *testing.T) {
  563. backup := Validator
  564. Validator = nil
  565. defer func() { Validator = backup }()
  566. var obj FooStruct
  567. req := requestWithBody("POST", "/", `{"bar": "foo"}`)
  568. err := JSON.Bind(req, &obj)
  569. assert.NoError(t, err)
  570. }
  571. func TestExistsSucceeds(t *testing.T) {
  572. type HogeStruct struct {
  573. Hoge *int `json:"hoge" binding:"exists"`
  574. }
  575. var obj HogeStruct
  576. req := requestWithBody("POST", "/", `{"hoge": 0}`)
  577. err := JSON.Bind(req, &obj)
  578. assert.NoError(t, err)
  579. }
  580. func TestExistsFails(t *testing.T) {
  581. type HogeStruct struct {
  582. Hoge *int `json:"foo" binding:"exists"`
  583. }
  584. var obj HogeStruct
  585. req := requestWithBody("POST", "/", `{"boen": 0}`)
  586. err := JSON.Bind(req, &obj)
  587. assert.Error(t, err)
  588. }
  589. func TestUriBinding(t *testing.T) {
  590. b := Uri
  591. assert.Equal(t, "uri", b.Name())
  592. type Tag struct {
  593. Name string `uri:"name"`
  594. }
  595. var tag Tag
  596. m := make(map[string][]string)
  597. m["name"] = []string{"thinkerou"}
  598. assert.NoError(t, b.BindUri(m, &tag))
  599. assert.Equal(t, "thinkerou", tag.Name)
  600. type NotSupportStruct struct {
  601. Name map[string]interface{} `uri:"name"`
  602. }
  603. var not NotSupportStruct
  604. assert.Error(t, b.BindUri(m, &not))
  605. assert.Equal(t, map[string]interface{}(nil), not.Name)
  606. }
  607. func TestUriInnerBinding(t *testing.T) {
  608. type Tag struct {
  609. Name string `uri:"name"`
  610. S struct {
  611. Age int `uri:"age"`
  612. }
  613. }
  614. expectedName := "mike"
  615. expectedAge := 25
  616. m := map[string][]string{
  617. "name": {expectedName},
  618. "age": {strconv.Itoa(expectedAge)},
  619. }
  620. var tag Tag
  621. assert.NoError(t, Uri.BindUri(m, &tag))
  622. assert.Equal(t, tag.Name, expectedName)
  623. assert.Equal(t, tag.S.Age, expectedAge)
  624. }
  625. func testFormBinding(t *testing.T, method, path, badPath, body, badBody string) {
  626. b := Form
  627. assert.Equal(t, "form", b.Name())
  628. obj := FooBarStruct{}
  629. req := requestWithBody(method, path, body)
  630. if method == "POST" {
  631. req.Header.Add("Content-Type", MIMEPOSTForm)
  632. }
  633. err := b.Bind(req, &obj)
  634. assert.NoError(t, err)
  635. assert.Equal(t, "bar", obj.Foo)
  636. assert.Equal(t, "foo", obj.Bar)
  637. obj = FooBarStruct{}
  638. req = requestWithBody(method, badPath, badBody)
  639. err = JSON.Bind(req, &obj)
  640. assert.Error(t, err)
  641. }
  642. func testFormBindingDefaultValue(t *testing.T, method, path, badPath, body, badBody string) {
  643. b := Form
  644. assert.Equal(t, "form", b.Name())
  645. obj := FooDefaultBarStruct{}
  646. req := requestWithBody(method, path, body)
  647. if method == "POST" {
  648. req.Header.Add("Content-Type", MIMEPOSTForm)
  649. }
  650. err := b.Bind(req, &obj)
  651. assert.NoError(t, err)
  652. assert.Equal(t, "bar", obj.Foo)
  653. assert.Equal(t, "hello", obj.Bar)
  654. obj = FooDefaultBarStruct{}
  655. req = requestWithBody(method, badPath, badBody)
  656. err = JSON.Bind(req, &obj)
  657. assert.Error(t, err)
  658. }
  659. func TestFormBindingFail(t *testing.T) {
  660. b := Form
  661. assert.Equal(t, "form", b.Name())
  662. obj := FooBarStruct{}
  663. req, _ := http.NewRequest("POST", "/", nil)
  664. err := b.Bind(req, &obj)
  665. assert.Error(t, err)
  666. }
  667. func TestFormBindingMultipartFail(t *testing.T) {
  668. obj := FooBarStruct{}
  669. req, err := http.NewRequest("POST", "/", strings.NewReader("foo=bar"))
  670. assert.NoError(t, err)
  671. req.Header.Set("Content-Type", MIMEMultipartPOSTForm+";boundary=testboundary")
  672. _, err = req.MultipartReader()
  673. assert.NoError(t, err)
  674. err = Form.Bind(req, &obj)
  675. assert.Error(t, err)
  676. }
  677. func TestFormPostBindingFail(t *testing.T) {
  678. b := FormPost
  679. assert.Equal(t, "form-urlencoded", b.Name())
  680. obj := FooBarStruct{}
  681. req, _ := http.NewRequest("POST", "/", nil)
  682. err := b.Bind(req, &obj)
  683. assert.Error(t, err)
  684. }
  685. func TestFormMultipartBindingFail(t *testing.T) {
  686. b := FormMultipart
  687. assert.Equal(t, "multipart/form-data", b.Name())
  688. obj := FooBarStruct{}
  689. req, _ := http.NewRequest("POST", "/", nil)
  690. err := b.Bind(req, &obj)
  691. assert.Error(t, err)
  692. }
  693. func testFormBindingForTime(t *testing.T, method, path, badPath, body, badBody string) {
  694. b := Form
  695. assert.Equal(t, "form", b.Name())
  696. obj := FooBarStructForTimeType{}
  697. req := requestWithBody(method, path, body)
  698. if method == "POST" {
  699. req.Header.Add("Content-Type", MIMEPOSTForm)
  700. }
  701. err := b.Bind(req, &obj)
  702. assert.NoError(t, err)
  703. assert.Equal(t, int64(1510675200), obj.TimeFoo.Unix())
  704. assert.Equal(t, "Asia/Chongqing", obj.TimeFoo.Location().String())
  705. assert.Equal(t, int64(-62135596800), obj.TimeBar.Unix())
  706. assert.Equal(t, "UTC", obj.TimeBar.Location().String())
  707. obj = FooBarStructForTimeType{}
  708. req = requestWithBody(method, badPath, badBody)
  709. err = JSON.Bind(req, &obj)
  710. assert.Error(t, err)
  711. }
  712. func testFormBindingForTimeNotFormat(t *testing.T, method, path, badPath, body, badBody string) {
  713. b := Form
  714. assert.Equal(t, "form", b.Name())
  715. obj := FooStructForTimeTypeNotFormat{}
  716. req := requestWithBody(method, path, body)
  717. if method == "POST" {
  718. req.Header.Add("Content-Type", MIMEPOSTForm)
  719. }
  720. err := b.Bind(req, &obj)
  721. assert.Error(t, err)
  722. obj = FooStructForTimeTypeNotFormat{}
  723. req = requestWithBody(method, badPath, badBody)
  724. err = JSON.Bind(req, &obj)
  725. assert.Error(t, err)
  726. }
  727. func testFormBindingForTimeFailFormat(t *testing.T, method, path, badPath, body, badBody string) {
  728. b := Form
  729. assert.Equal(t, "form", b.Name())
  730. obj := FooStructForTimeTypeFailFormat{}
  731. req := requestWithBody(method, path, body)
  732. if method == "POST" {
  733. req.Header.Add("Content-Type", MIMEPOSTForm)
  734. }
  735. err := b.Bind(req, &obj)
  736. assert.Error(t, err)
  737. obj = FooStructForTimeTypeFailFormat{}
  738. req = requestWithBody(method, badPath, badBody)
  739. err = JSON.Bind(req, &obj)
  740. assert.Error(t, err)
  741. }
  742. func testFormBindingForTimeFailLocation(t *testing.T, method, path, badPath, body, badBody string) {
  743. b := Form
  744. assert.Equal(t, "form", b.Name())
  745. obj := FooStructForTimeTypeFailLocation{}
  746. req := requestWithBody(method, path, body)
  747. if method == "POST" {
  748. req.Header.Add("Content-Type", MIMEPOSTForm)
  749. }
  750. err := b.Bind(req, &obj)
  751. assert.Error(t, err)
  752. obj = FooStructForTimeTypeFailLocation{}
  753. req = requestWithBody(method, badPath, badBody)
  754. err = JSON.Bind(req, &obj)
  755. assert.Error(t, err)
  756. }
  757. func testFormBindingIgnoreField(t *testing.T, method, path, badPath, body, badBody string) {
  758. b := Form
  759. assert.Equal(t, "form", b.Name())
  760. obj := FooStructForIgnoreFormTag{}
  761. req := requestWithBody(method, path, body)
  762. if method == "POST" {
  763. req.Header.Add("Content-Type", MIMEPOSTForm)
  764. }
  765. err := b.Bind(req, &obj)
  766. assert.NoError(t, err)
  767. assert.Nil(t, obj.Foo)
  768. }
  769. func testFormBindingInvalidName(t *testing.T, method, path, badPath, body, badBody string) {
  770. b := Form
  771. assert.Equal(t, "form", b.Name())
  772. obj := InvalidNameType{}
  773. req := requestWithBody(method, path, body)
  774. if method == "POST" {
  775. req.Header.Add("Content-Type", MIMEPOSTForm)
  776. }
  777. err := b.Bind(req, &obj)
  778. assert.NoError(t, err)
  779. assert.Equal(t, "", obj.TestName)
  780. obj = InvalidNameType{}
  781. req = requestWithBody(method, badPath, badBody)
  782. err = JSON.Bind(req, &obj)
  783. assert.Error(t, err)
  784. }
  785. func testFormBindingInvalidName2(t *testing.T, method, path, badPath, body, badBody string) {
  786. b := Form
  787. assert.Equal(t, "form", b.Name())
  788. obj := InvalidNameMapType{}
  789. req := requestWithBody(method, path, body)
  790. if method == "POST" {
  791. req.Header.Add("Content-Type", MIMEPOSTForm)
  792. }
  793. err := b.Bind(req, &obj)
  794. assert.Error(t, err)
  795. obj = InvalidNameMapType{}
  796. req = requestWithBody(method, badPath, badBody)
  797. err = JSON.Bind(req, &obj)
  798. assert.Error(t, err)
  799. }
  800. func testFormBindingForType(t *testing.T, method, path, badPath, body, badBody string, typ string) {
  801. b := Form
  802. assert.Equal(t, "form", b.Name())
  803. req := requestWithBody(method, path, body)
  804. if method == "POST" {
  805. req.Header.Add("Content-Type", MIMEPOSTForm)
  806. }
  807. switch typ {
  808. case "Int":
  809. obj := FooBarStructForIntType{}
  810. err := b.Bind(req, &obj)
  811. assert.NoError(t, err)
  812. assert.Equal(t, int(0), obj.IntFoo)
  813. assert.Equal(t, int(-12), obj.IntBar)
  814. obj = FooBarStructForIntType{}
  815. req = requestWithBody(method, badPath, badBody)
  816. err = JSON.Bind(req, &obj)
  817. assert.Error(t, err)
  818. case "Int8":
  819. obj := FooBarStructForInt8Type{}
  820. err := b.Bind(req, &obj)
  821. assert.NoError(t, err)
  822. assert.Equal(t, int8(0), obj.Int8Foo)
  823. assert.Equal(t, int8(-12), obj.Int8Bar)
  824. obj = FooBarStructForInt8Type{}
  825. req = requestWithBody(method, badPath, badBody)
  826. err = JSON.Bind(req, &obj)
  827. assert.Error(t, err)
  828. case "Int16":
  829. obj := FooBarStructForInt16Type{}
  830. err := b.Bind(req, &obj)
  831. assert.NoError(t, err)
  832. assert.Equal(t, int16(0), obj.Int16Foo)
  833. assert.Equal(t, int16(-12), obj.Int16Bar)
  834. obj = FooBarStructForInt16Type{}
  835. req = requestWithBody(method, badPath, badBody)
  836. err = JSON.Bind(req, &obj)
  837. assert.Error(t, err)
  838. case "Int32":
  839. obj := FooBarStructForInt32Type{}
  840. err := b.Bind(req, &obj)
  841. assert.NoError(t, err)
  842. assert.Equal(t, int32(0), obj.Int32Foo)
  843. assert.Equal(t, int32(-12), obj.Int32Bar)
  844. obj = FooBarStructForInt32Type{}
  845. req = requestWithBody(method, badPath, badBody)
  846. err = JSON.Bind(req, &obj)
  847. assert.Error(t, err)
  848. case "Int64":
  849. obj := FooBarStructForInt64Type{}
  850. err := b.Bind(req, &obj)
  851. assert.NoError(t, err)
  852. assert.Equal(t, int64(0), obj.Int64Foo)
  853. assert.Equal(t, int64(-12), obj.Int64Bar)
  854. obj = FooBarStructForInt64Type{}
  855. req = requestWithBody(method, badPath, badBody)
  856. err = JSON.Bind(req, &obj)
  857. assert.Error(t, err)
  858. case "Uint":
  859. obj := FooBarStructForUintType{}
  860. err := b.Bind(req, &obj)
  861. assert.NoError(t, err)
  862. assert.Equal(t, uint(0x0), obj.UintFoo)
  863. assert.Equal(t, uint(0xc), obj.UintBar)
  864. obj = FooBarStructForUintType{}
  865. req = requestWithBody(method, badPath, badBody)
  866. err = JSON.Bind(req, &obj)
  867. assert.Error(t, err)
  868. case "Uint8":
  869. obj := FooBarStructForUint8Type{}
  870. err := b.Bind(req, &obj)
  871. assert.NoError(t, err)
  872. assert.Equal(t, uint8(0x0), obj.Uint8Foo)
  873. assert.Equal(t, uint8(0xc), obj.Uint8Bar)
  874. obj = FooBarStructForUint8Type{}
  875. req = requestWithBody(method, badPath, badBody)
  876. err = JSON.Bind(req, &obj)
  877. assert.Error(t, err)
  878. case "Uint16":
  879. obj := FooBarStructForUint16Type{}
  880. err := b.Bind(req, &obj)
  881. assert.NoError(t, err)
  882. assert.Equal(t, uint16(0x0), obj.Uint16Foo)
  883. assert.Equal(t, uint16(0xc), obj.Uint16Bar)
  884. obj = FooBarStructForUint16Type{}
  885. req = requestWithBody(method, badPath, badBody)
  886. err = JSON.Bind(req, &obj)
  887. assert.Error(t, err)
  888. case "Uint32":
  889. obj := FooBarStructForUint32Type{}
  890. err := b.Bind(req, &obj)
  891. assert.NoError(t, err)
  892. assert.Equal(t, uint32(0x0), obj.Uint32Foo)
  893. assert.Equal(t, uint32(0xc), obj.Uint32Bar)
  894. obj = FooBarStructForUint32Type{}
  895. req = requestWithBody(method, badPath, badBody)
  896. err = JSON.Bind(req, &obj)
  897. assert.Error(t, err)
  898. case "Uint64":
  899. obj := FooBarStructForUint64Type{}
  900. err := b.Bind(req, &obj)
  901. assert.NoError(t, err)
  902. assert.Equal(t, uint64(0x0), obj.Uint64Foo)
  903. assert.Equal(t, uint64(0xc), obj.Uint64Bar)
  904. obj = FooBarStructForUint64Type{}
  905. req = requestWithBody(method, badPath, badBody)
  906. err = JSON.Bind(req, &obj)
  907. assert.Error(t, err)
  908. case "Float32":
  909. obj := FooBarStructForFloat32Type{}
  910. err := b.Bind(req, &obj)
  911. assert.NoError(t, err)
  912. assert.Equal(t, float32(0.0), obj.Float32Foo)
  913. assert.Equal(t, float32(-12.34), obj.Float32Bar)
  914. obj = FooBarStructForFloat32Type{}
  915. req = requestWithBody(method, badPath, badBody)
  916. err = JSON.Bind(req, &obj)
  917. assert.Error(t, err)
  918. case "Float64":
  919. obj := FooBarStructForFloat64Type{}
  920. err := b.Bind(req, &obj)
  921. assert.NoError(t, err)
  922. assert.Equal(t, float64(0.0), obj.Float64Foo)
  923. assert.Equal(t, float64(-12.34), obj.Float64Bar)
  924. obj = FooBarStructForFloat64Type{}
  925. req = requestWithBody(method, badPath, badBody)
  926. err = JSON.Bind(req, &obj)
  927. assert.Error(t, err)
  928. case "Bool":
  929. obj := FooBarStructForBoolType{}
  930. err := b.Bind(req, &obj)
  931. assert.NoError(t, err)
  932. assert.False(t, obj.BoolFoo)
  933. assert.True(t, obj.BoolBar)
  934. obj = FooBarStructForBoolType{}
  935. req = requestWithBody(method, badPath, badBody)
  936. err = JSON.Bind(req, &obj)
  937. assert.Error(t, err)
  938. case "Slice":
  939. obj := FooStructForSliceType{}
  940. err := b.Bind(req, &obj)
  941. assert.NoError(t, err)
  942. assert.Equal(t, []int{1, 2}, obj.SliceFoo)
  943. obj = FooStructForSliceType{}
  944. req = requestWithBody(method, badPath, badBody)
  945. err = JSON.Bind(req, &obj)
  946. assert.Error(t, err)
  947. case "Struct":
  948. obj := FooStructForStructType{}
  949. err := b.Bind(req, &obj)
  950. assert.NoError(t, err)
  951. assert.Equal(t,
  952. struct {
  953. Idx int "form:\"idx\""
  954. }(struct {
  955. Idx int "form:\"idx\""
  956. }{Idx: 123}),
  957. obj.StructFoo)
  958. case "StructPointer":
  959. obj := FooStructForStructPointerType{}
  960. err := b.Bind(req, &obj)
  961. assert.NoError(t, err)
  962. assert.Equal(t,
  963. struct {
  964. Name string "form:\"name\""
  965. }(struct {
  966. Name string "form:\"name\""
  967. }{Name: "thinkerou"}),
  968. *obj.StructPointerFoo)
  969. case "Map":
  970. obj := FooStructForMapType{}
  971. err := b.Bind(req, &obj)
  972. assert.NoError(t, err)
  973. assert.Equal(t, float64(123), obj.MapFoo["bar"].(float64))
  974. case "SliceMap":
  975. obj := FooStructForSliceMapType{}
  976. err := b.Bind(req, &obj)
  977. assert.Error(t, err)
  978. case "Ptr":
  979. obj := FooStructForStringPtrType{}
  980. err := b.Bind(req, &obj)
  981. assert.NoError(t, err)
  982. assert.Nil(t, obj.PtrFoo)
  983. assert.Equal(t, "test", *obj.PtrBar)
  984. obj = FooStructForStringPtrType{}
  985. obj.PtrBar = new(string)
  986. err = b.Bind(req, &obj)
  987. assert.NoError(t, err)
  988. assert.Equal(t, "test", *obj.PtrBar)
  989. objErr := FooStructForMapPtrType{}
  990. err = b.Bind(req, &objErr)
  991. assert.Error(t, err)
  992. obj = FooStructForStringPtrType{}
  993. req = requestWithBody(method, badPath, badBody)
  994. err = b.Bind(req, &obj)
  995. assert.Error(t, err)
  996. }
  997. }
  998. func testQueryBinding(t *testing.T, method, path, badPath, body, badBody string) {
  999. b := Query
  1000. assert.Equal(t, "query", b.Name())
  1001. obj := FooBarStruct{}
  1002. req := requestWithBody(method, path, body)
  1003. if method == "POST" {
  1004. req.Header.Add("Content-Type", MIMEPOSTForm)
  1005. }
  1006. err := b.Bind(req, &obj)
  1007. assert.NoError(t, err)
  1008. assert.Equal(t, "bar", obj.Foo)
  1009. assert.Equal(t, "foo", obj.Bar)
  1010. }
  1011. func testQueryBindingFail(t *testing.T, method, path, badPath, body, badBody string) {
  1012. b := Query
  1013. assert.Equal(t, "query", b.Name())
  1014. obj := FooStructForMapType{}
  1015. req := requestWithBody(method, path, body)
  1016. if method == "POST" {
  1017. req.Header.Add("Content-Type", MIMEPOSTForm)
  1018. }
  1019. err := b.Bind(req, &obj)
  1020. assert.Error(t, err)
  1021. }
  1022. func testQueryBindingBoolFail(t *testing.T, method, path, badPath, body, badBody string) {
  1023. b := Query
  1024. assert.Equal(t, "query", b.Name())
  1025. obj := FooStructForBoolType{}
  1026. req := requestWithBody(method, path, body)
  1027. if method == "POST" {
  1028. req.Header.Add("Content-Type", MIMEPOSTForm)
  1029. }
  1030. err := b.Bind(req, &obj)
  1031. assert.Error(t, err)
  1032. }
  1033. func testBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
  1034. assert.Equal(t, name, b.Name())
  1035. obj := FooStruct{}
  1036. req := requestWithBody("POST", path, body)
  1037. err := b.Bind(req, &obj)
  1038. assert.NoError(t, err)
  1039. assert.Equal(t, "bar", obj.Foo)
  1040. obj = FooStruct{}
  1041. req = requestWithBody("POST", badPath, badBody)
  1042. err = JSON.Bind(req, &obj)
  1043. assert.Error(t, err)
  1044. }
  1045. func testBodyBindingUseNumber(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
  1046. assert.Equal(t, name, b.Name())
  1047. obj := FooStructUseNumber{}
  1048. req := requestWithBody("POST", path, body)
  1049. EnableDecoderUseNumber = true
  1050. err := b.Bind(req, &obj)
  1051. assert.NoError(t, err)
  1052. // we hope it is int64(123)
  1053. v, e := obj.Foo.(json.Number).Int64()
  1054. assert.NoError(t, e)
  1055. assert.Equal(t, int64(123), v)
  1056. obj = FooStructUseNumber{}
  1057. req = requestWithBody("POST", badPath, badBody)
  1058. err = JSON.Bind(req, &obj)
  1059. assert.Error(t, err)
  1060. }
  1061. func testBodyBindingUseNumber2(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
  1062. assert.Equal(t, name, b.Name())
  1063. obj := FooStructUseNumber{}
  1064. req := requestWithBody("POST", path, body)
  1065. EnableDecoderUseNumber = false
  1066. err := b.Bind(req, &obj)
  1067. assert.NoError(t, err)
  1068. // it will return float64(123) if not use EnableDecoderUseNumber
  1069. // maybe it is not hoped
  1070. assert.Equal(t, float64(123), obj.Foo)
  1071. obj = FooStructUseNumber{}
  1072. req = requestWithBody("POST", badPath, badBody)
  1073. err = JSON.Bind(req, &obj)
  1074. assert.Error(t, err)
  1075. }
  1076. func testBodyBindingFail(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
  1077. assert.Equal(t, name, b.Name())
  1078. obj := FooStruct{}
  1079. req := requestWithBody("POST", path, body)
  1080. err := b.Bind(req, &obj)
  1081. assert.Error(t, err)
  1082. assert.Equal(t, "", obj.Foo)
  1083. obj = FooStruct{}
  1084. req = requestWithBody("POST", badPath, badBody)
  1085. err = JSON.Bind(req, &obj)
  1086. assert.Error(t, err)
  1087. }
  1088. func testProtoBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
  1089. assert.Equal(t, name, b.Name())
  1090. obj := protoexample.Test{}
  1091. req := requestWithBody("POST", path, body)
  1092. req.Header.Add("Content-Type", MIMEPROTOBUF)
  1093. err := b.Bind(req, &obj)
  1094. assert.NoError(t, err)
  1095. assert.Equal(t, "yes", *obj.Label)
  1096. obj = protoexample.Test{}
  1097. req = requestWithBody("POST", badPath, badBody)
  1098. req.Header.Add("Content-Type", MIMEPROTOBUF)
  1099. err = ProtoBuf.Bind(req, &obj)
  1100. assert.Error(t, err)
  1101. }
  1102. type hook struct{}
  1103. func (h hook) Read([]byte) (int, error) {
  1104. return 0, errors.New("error")
  1105. }
  1106. func testProtoBodyBindingFail(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
  1107. assert.Equal(t, name, b.Name())
  1108. obj := protoexample.Test{}
  1109. req := requestWithBody("POST", path, body)
  1110. req.Body = ioutil.NopCloser(&hook{})
  1111. req.Header.Add("Content-Type", MIMEPROTOBUF)
  1112. err := b.Bind(req, &obj)
  1113. assert.Error(t, err)
  1114. obj = protoexample.Test{}
  1115. req = requestWithBody("POST", badPath, badBody)
  1116. req.Header.Add("Content-Type", MIMEPROTOBUF)
  1117. err = ProtoBuf.Bind(req, &obj)
  1118. assert.Error(t, err)
  1119. }
  1120. func testMsgPackBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
  1121. assert.Equal(t, name, b.Name())
  1122. obj := FooStruct{}
  1123. req := requestWithBody("POST", path, body)
  1124. req.Header.Add("Content-Type", MIMEMSGPACK)
  1125. err := b.Bind(req, &obj)
  1126. assert.NoError(t, err)
  1127. assert.Equal(t, "bar", obj.Foo)
  1128. obj = FooStruct{}
  1129. req = requestWithBody("POST", badPath, badBody)
  1130. req.Header.Add("Content-Type", MIMEMSGPACK)
  1131. err = MsgPack.Bind(req, &obj)
  1132. assert.Error(t, err)
  1133. }
  1134. func requestWithBody(method, path, body string) (req *http.Request) {
  1135. req, _ = http.NewRequest(method, path, bytes.NewBufferString(body))
  1136. return
  1137. }
  1138. func TestCanSet(t *testing.T) {
  1139. type CanSetStruct struct {
  1140. lowerStart string `form:"lower"`
  1141. }
  1142. var c CanSetStruct
  1143. assert.Nil(t, mapForm(&c, nil))
  1144. }
  1145. func formPostRequest(path, body string) *http.Request {
  1146. req := requestWithBody("POST", path, body)
  1147. req.Header.Add("Content-Type", MIMEPOSTForm)
  1148. return req
  1149. }
  1150. func TestBindingSliceDefault(t *testing.T) {
  1151. var s struct {
  1152. Friends []string `form:"friends,default=mike"`
  1153. }
  1154. req := formPostRequest("", "")
  1155. err := Form.Bind(req, &s)
  1156. assert.NoError(t, err)
  1157. assert.Len(t, s.Friends, 1)
  1158. assert.Equal(t, "mike", s.Friends[0])
  1159. }
  1160. func TestBindingStructField(t *testing.T) {
  1161. var s struct {
  1162. Opts struct {
  1163. Port int
  1164. } `form:"opts"`
  1165. }
  1166. req := formPostRequest("", `opts={"Port": 8000}`)
  1167. err := Form.Bind(req, &s)
  1168. assert.NoError(t, err)
  1169. assert.Equal(t, 8000, s.Opts.Port)
  1170. }
  1171. func TestBindingUnknownTypeChan(t *testing.T) {
  1172. var s struct {
  1173. Stop chan bool `form:"stop"`
  1174. }
  1175. req := formPostRequest("", "stop=true")
  1176. err := Form.Bind(req, &s)
  1177. assert.Error(t, err)
  1178. assert.Equal(t, errUnknownType, err)
  1179. }
  1180. func TestBindingTimeDuration(t *testing.T) {
  1181. var s struct {
  1182. Timeout time.Duration `form:"timeout"`
  1183. }
  1184. // ok
  1185. req := formPostRequest("", "timeout=5s")
  1186. err := Form.Bind(req, &s)
  1187. assert.NoError(t, err)
  1188. assert.Equal(t, 5*time.Second, s.Timeout)
  1189. // error
  1190. req = formPostRequest("", "timeout=wrong")
  1191. err = Form.Bind(req, &s)
  1192. assert.Error(t, err)
  1193. }