binding_test.go
This file
Path
binding/binding_test.go
1,434 lines · 38.6 KiB · Go
Last changed by
chore(binding): upgrade bson dependency to mongo-driver v2 (#4549)Bob Dubefore adoptionba093d1
History of this fileTake it
The walk stopped after 200 commits: lines older than cf32d2d point at it.
chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d
lines 1–23why, one step back1// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2// Use of this source code is governed by a MIT style3// license that can be found in the LICENSE file.45package binding67import (8 "bytes"9 "encoding/json"10 "errors"11 "io"12 "mime/multipart"13 "net/http"14 "os"15 "reflect"16 "strconv"17 "strings"18 "testing"19 "time"2021 "github.com/gin-gonic/gin/testdata/protoexample"22 "github.com/stretchr/testify/assert"23 "github.com/stretchr/testify/require"chore(binding): upgrade bson dependency to mongo-driver v2 (#4549)Bob Dubefore adoptionba093d1
line 24why, one step back24 "go.mongodb.org/mongo-driver/v2/bson"chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d
lines 25–175why, one step back25 "google.golang.org/protobuf/proto"26)2728type appkey struct {29 Appkey string `json:"appkey" form:"appkey"`30}3132type QueryTest struct {33 Page int `json:"page" form:"page"`34 Size int `json:"size" form:"size"`35 appkey36}3738type FooStruct struct {39 Foo string `msgpack:"foo" json:"foo" form:"foo" xml:"foo" binding:"required,max=32"`40}4142type FooBarStruct struct {43 FooStruct44 Bar string `msgpack:"bar" json:"bar" form:"bar" xml:"bar" binding:"required"`45}4647type FooBarFileStruct struct {48 FooBarStruct49 File *multipart.FileHeader `form:"file" binding:"required"`50}5152type FooBarFileFailStruct struct {53 FooBarStruct54 File *multipart.FileHeader `invalid_name:"file" binding:"required"`55}5657type FooDefaultBarStruct struct {58 FooStruct59 Bar string `msgpack:"bar" json:"bar" form:"bar,default=hello" xml:"bar" binding:"required"`60}6162type FooStructUseNumber struct {63 Foo any `json:"foo" binding:"required"`64}6566type FooStructDisallowUnknownFields struct {67 Foo any `json:"foo" binding:"required"`68}6970type FooBarStructForTimeType struct {71 TimeFoo time.Time `form:"time_foo" time_format:"2006-01-02" time_utc:"1" time_location:"Asia/Chongqing"`72 TimeBar time.Time `form:"time_bar" time_format:"2006-01-02" time_utc:"1"`73 CreateTime time.Time `form:"createTime" time_format:"unixNano"`74 UnixTime time.Time `form:"unixTime" time_format:"unix"`75 UnixMilliTime time.Time `form:"unixMilliTime" time_format:"unixmilli"`76 UnixMicroTime time.Time `form:"unixMicroTime" time_format:"uNiXmiCrO"`77}7879type FooStructForTimeTypeNotUnixFormat struct {80 CreateTime time.Time `form:"createTime" time_format:"unixNano"`81 UnixTime time.Time `form:"unixTime" time_format:"unix"`82 UnixMilliTime time.Time `form:"unixMilliTime" time_format:"unixMilli"`83 UnixMicroTime time.Time `form:"unixMicroTime" time_format:"unixMicro"`84}8586type FooStructForTimeTypeNotFormat struct {87 TimeFoo time.Time `form:"time_foo"`88}8990type FooStructForTimeTypeFailFormat struct {91 TimeFoo time.Time `form:"time_foo" time_format:"2017-11-15"`92}9394type FooStructForTimeTypeFailLocation struct {95 TimeFoo time.Time `form:"time_foo" time_format:"2006-01-02" time_location:"/asia/chongqing"`96}9798type FooStructForMapType struct {99 MapFoo map[string]any `form:"map_foo"`100}101102type FooStructForIgnoreFormTag struct {103 Foo *string `form:"-"`104}105106type InvalidNameType struct {107 TestName string `invalid_name:"test_name"`108}109110type InvalidNameMapType struct {111 TestName struct {112 MapFoo map[string]any `form:"map_foo"`113 }114}115116type FooStructForSliceType struct {117 SliceFoo []int `form:"slice_foo"`118}119120type FooStructForStructType struct {121 StructFoo struct {122 Idx int `form:"idx"`123 }124}125126type FooStructForStructPointerType struct {127 StructPointerFoo *struct {128 Name string `form:"name"`129 }130}131132type FooStructForSliceMapType struct {133 // Unknown type: not support map134 SliceMapFoo []map[string]any `form:"slice_map_foo"`135}136137type FooStructForBoolType struct {138 BoolFoo bool `form:"bool_foo"`139}140141type FooStructForStringPtrType struct {142 PtrFoo *string `form:"ptr_foo"`143 PtrBar *string `form:"ptr_bar" binding:"required"`144}145146type FooStructForMapPtrType struct {147 PtrBar *map[string]any `form:"ptr_bar"`148}149150func TestBindingDefault(t *testing.T) {151 assert.Equal(t, Form, Default(http.MethodGet, ""))152 assert.Equal(t, Form, Default(http.MethodGet, MIMEJSON))153154 assert.Equal(t, JSON, Default(http.MethodPost, MIMEJSON))155 assert.Equal(t, JSON, Default(http.MethodPut, MIMEJSON))156157 assert.Equal(t, XML, Default(http.MethodPost, MIMEXML))158 assert.Equal(t, XML, Default(http.MethodPut, MIMEXML2))159160 assert.Equal(t, Form, Default(http.MethodPost, MIMEPOSTForm))161 assert.Equal(t, Form, Default(http.MethodPut, MIMEPOSTForm))162163 assert.Equal(t, FormMultipart, Default(http.MethodPost, MIMEMultipartPOSTForm))164 assert.Equal(t, FormMultipart, Default(http.MethodPut, MIMEMultipartPOSTForm))165166 assert.Equal(t, ProtoBuf, Default(http.MethodPost, MIMEPROTOBUF))167 assert.Equal(t, ProtoBuf, Default(http.MethodPut, MIMEPROTOBUF))168169 assert.Equal(t, YAML, Default(http.MethodPost, MIMEYAML))170 assert.Equal(t, YAML, Default(http.MethodPut, MIMEYAML))171 assert.Equal(t, YAML, Default(http.MethodPost, MIMEYAML2))172 assert.Equal(t, YAML, Default(http.MethodPut, MIMEYAML2))173174 assert.Equal(t, TOML, Default(http.MethodPost, MIMETOML))175 assert.Equal(t, TOML, Default(http.MethodPut, MIMETOML))feat(render): add bson protocol (#4145)Laurent Caumontbefore adoptiond7776de
lines 176–178why, one step back176177 assert.Equal(t, BSON, Default(http.MethodPost, MIMEBSON))178 assert.Equal(t, BSON, Default(http.MethodPut, MIMEBSON))chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d
lines 179–735why, one step back179}180181func TestBindingJSONNilBody(t *testing.T) {182 var obj FooStruct183 req, _ := http.NewRequest(http.MethodPost, "/", nil)184 err := JSON.Bind(req, &obj)185 require.Error(t, err)186}187188func TestBindingJSON(t *testing.T) {189 testBodyBinding(t,190 JSON, "json",191 "/", "/",192 `{"foo": "bar"}`, `{"bar": "foo"}`)193}194195func TestBindingJSONSlice(t *testing.T) {196 EnableDecoderDisallowUnknownFields = true197 defer func() {198 EnableDecoderDisallowUnknownFields = false199 }()200201 testBodyBindingSlice(t, JSON, "json", "/", "/", `[]`, ``)202 testBodyBindingSlice(t, JSON, "json", "/", "/", `[{"foo": "123"}]`, `[{}]`)203 testBodyBindingSlice(t, JSON, "json", "/", "/", `[{"foo": "123"}]`, `[{"foo": ""}]`)204 testBodyBindingSlice(t, JSON, "json", "/", "/", `[{"foo": "123"}]`, `[{"foo": 123}]`)205 testBodyBindingSlice(t, JSON, "json", "/", "/", `[{"foo": "123"}]`, `[{"bar": 123}]`)206 testBodyBindingSlice(t, JSON, "json", "/", "/", `[{"foo": "123"}]`, `[{"foo": "123456789012345678901234567890123"}]`)207}208209func TestBindingJSONUseNumber(t *testing.T) {210 testBodyBindingUseNumber(t,211 JSON, "json",212 "/", "/",213 `{"foo": 123}`, `{"bar": "foo"}`)214}215216func TestBindingJSONUseNumber2(t *testing.T) {217 testBodyBindingUseNumber2(t,218 JSON, "json",219 "/", "/",220 `{"foo": 123}`, `{"bar": "foo"}`)221}222223func TestBindingJSONDisallowUnknownFields(t *testing.T) {224 testBodyBindingDisallowUnknownFields(t, JSON,225 "/", "/",226 `{"foo": "bar"}`, `{"foo": "bar", "what": "this"}`)227}228229func TestBindingJSONStringMap(t *testing.T) {230 testBodyBindingStringMap(t, JSON,231 "/", "/",232 `{"foo": "bar", "hello": "world"}`, `{"num": 2}`)233}234235func TestBindingForm(t *testing.T) {236 testFormBinding(t, http.MethodPost,237 "/", "/",238 "foo=bar&bar=foo", "bar2=foo")239}240241func TestBindingForm2(t *testing.T) {242 testFormBinding(t, http.MethodGet,243 "/?foo=bar&bar=foo", "/?bar2=foo",244 "", "")245}246247func TestBindingFormEmbeddedStruct(t *testing.T) {248 testFormBindingEmbeddedStruct(t, http.MethodPost,249 "/", "/",250 "page=1&size=2&appkey=test-appkey", "bar2=foo")251}252253func TestBindingFormEmbeddedStruct2(t *testing.T) {254 testFormBindingEmbeddedStruct(t, http.MethodGet,255 "/?page=1&size=2&appkey=test-appkey", "/?bar2=foo",256 "", "")257}258259func TestBindingFormDefaultValue(t *testing.T) {260 testFormBindingDefaultValue(t, http.MethodPost,261 "/", "/",262 "foo=bar", "bar2=foo")263}264265func TestBindingFormDefaultValue2(t *testing.T) {266 testFormBindingDefaultValue(t, http.MethodGet,267 "/?foo=bar", "/?bar2=foo",268 "", "")269}270271func TestBindingFormForTime(t *testing.T) {272 testFormBindingForTime(t, http.MethodPost,273 "/", "/",274 "time_foo=2017-11-15&time_bar=&createTime=1562400033000000123&unixTime=1562400033&unixMilliTime=1562400033001&unixMicroTime=1562400033000012", "bar2=foo")275 testFormBindingForTimeNotUnixFormat(t, http.MethodPost,276 "/", "/",277 "time_foo=2017-11-15&createTime=bad&unixTime=bad&unixMilliTime=bad&unixMicroTime=bad", "bar2=foo")278 testFormBindingForTimeNotFormat(t, http.MethodPost,279 "/", "/",280 "time_foo=2017-11-15", "bar2=foo")281 testFormBindingForTimeFailFormat(t, http.MethodPost,282 "/", "/",283 "time_foo=2017-11-15", "bar2=foo")284 testFormBindingForTimeFailLocation(t, http.MethodPost,285 "/", "/",286 "time_foo=2017-11-15", "bar2=foo")287}288289func TestBindingFormForTime2(t *testing.T) {290 testFormBindingForTime(t, http.MethodGet,291 "/?time_foo=2017-11-15&time_bar=&createTime=1562400033000000123&unixTime=1562400033&unixMilliTime=1562400033001&unixMicroTime=1562400033000012", "/?bar2=foo",292 "", "")293 testFormBindingForTimeNotUnixFormat(t, http.MethodPost,294 "/", "/",295 "time_foo=2017-11-15&createTime=bad&unixTime=bad&unixMilliTime=bad&unixMicroTime=bad", "bar2=foo")296 testFormBindingForTimeNotFormat(t, http.MethodGet,297 "/?time_foo=2017-11-15", "/?bar2=foo",298 "", "")299 testFormBindingForTimeFailFormat(t, http.MethodGet,300 "/?time_foo=2017-11-15", "/?bar2=foo",301 "", "")302 testFormBindingForTimeFailLocation(t, http.MethodGet,303 "/?time_foo=2017-11-15", "/?bar2=foo",304 "", "")305}306307func TestFormBindingIgnoreField(t *testing.T) {308 testFormBindingIgnoreField(t, http.MethodPost,309 "/", "/",310 "-=bar", "")311}312313func TestBindingFormInvalidName(t *testing.T) {314 testFormBindingInvalidName(t, http.MethodPost,315 "/", "/",316 "test_name=bar", "bar2=foo")317}318319func TestBindingFormInvalidName2(t *testing.T) {320 testFormBindingInvalidName2(t, http.MethodPost,321 "/", "/",322 "map_foo=bar", "bar2=foo")323}324325func TestBindingFormForType(t *testing.T) {326 testFormBindingForType(t, http.MethodPost,327 "/", "/",328 "map_foo={\"bar\":123}", "map_foo=1", "Map")329330 testFormBindingForType(t, http.MethodPost,331 "/", "/",332 "slice_foo=1&slice_foo=2", "bar2=1&bar2=2", "Slice")333334 testFormBindingForType(t, http.MethodGet,335 "/?slice_foo=1&slice_foo=2", "/?bar2=1&bar2=2",336 "", "", "Slice")337338 testFormBindingForType(t, http.MethodPost,339 "/", "/",340 "slice_map_foo=1&slice_map_foo=2", "bar2=1&bar2=2", "SliceMap")341342 testFormBindingForType(t, http.MethodGet,343 "/?slice_map_foo=1&slice_map_foo=2", "/?bar2=1&bar2=2",344 "", "", "SliceMap")345346 testFormBindingForType(t, http.MethodPost,347 "/", "/",348 "ptr_bar=test", "bar2=test", "Ptr")349350 testFormBindingForType(t, http.MethodGet,351 "/?ptr_bar=test", "/?bar2=test",352 "", "", "Ptr")353354 testFormBindingForType(t, http.MethodPost,355 "/", "/",356 "idx=123", "id1=1", "Struct")357358 testFormBindingForType(t, http.MethodGet,359 "/?idx=123", "/?id1=1",360 "", "", "Struct")361362 testFormBindingForType(t, http.MethodPost,363 "/", "/",364 "name=thinkerou", "name1=ou", "StructPointer")365366 testFormBindingForType(t, http.MethodGet,367 "/?name=thinkerou", "/?name1=ou",368 "", "", "StructPointer")369}370371func TestBindingFormStringMap(t *testing.T) {372 testBodyBindingStringMap(t, Form,373 "/", "",374 `foo=bar&hello=world`, "")375 // Should pick the last value376 testBodyBindingStringMap(t, Form,377 "/", "",378 `foo=something&foo=bar&hello=world`, "")379}380381func TestBindingFormStringSliceMap(t *testing.T) {382 obj := make(map[string][]string)383 req := requestWithBody(http.MethodPost, "/", "foo=something&foo=bar&hello=world")384 req.Header.Add("Content-Type", MIMEPOSTForm)385 err := Form.Bind(req, &obj)386 require.NoError(t, err)387 assert.NotNil(t, obj)388 assert.Len(t, obj, 2)389 target := map[string][]string{390 "foo": {"something", "bar"},391 "hello": {"world"},392 }393 assert.True(t, reflect.DeepEqual(obj, target))394395 objInvalid := make(map[string][]int)396 req = requestWithBody(http.MethodPost, "/", "foo=something&foo=bar&hello=world")397 req.Header.Add("Content-Type", MIMEPOSTForm)398 err = Form.Bind(req, &objInvalid)399 require.Error(t, err)400}401402func TestBindingQuery(t *testing.T) {403 testQueryBinding(t, http.MethodPost,404 "/?foo=bar&bar=foo", "/",405 "foo=unused", "bar2=foo")406}407408func TestBindingQuery2(t *testing.T) {409 testQueryBinding(t, http.MethodGet,410 "/?foo=bar&bar=foo", "/?bar2=foo",411 "foo=unused", "")412}413414func TestBindingQueryFail(t *testing.T) {415 testQueryBindingFail(t, http.MethodPost,416 "/?map_foo=", "/",417 "map_foo=unused", "bar2=foo")418}419420func TestBindingQueryFail2(t *testing.T) {421 testQueryBindingFail(t, http.MethodGet,422 "/?map_foo=", "/?bar2=foo",423 "map_foo=unused", "")424}425426func TestBindingQueryBoolFail(t *testing.T) {427 testQueryBindingBoolFail(t, http.MethodGet,428 "/?bool_foo=fasl", "/?bar2=foo",429 "bool_foo=unused", "")430}431432func TestBindingQueryStringMap(t *testing.T) {433 b := Query434435 obj := make(map[string]string)436 req := requestWithBody(http.MethodGet, "/?foo=bar&hello=world", "")437 err := b.Bind(req, &obj)438 require.NoError(t, err)439 assert.NotNil(t, obj)440 assert.Len(t, obj, 2)441 assert.Equal(t, "bar", obj["foo"])442 assert.Equal(t, "world", obj["hello"])443444 obj = make(map[string]string)445 req = requestWithBody(http.MethodGet, "/?foo=bar&foo=2&hello=world", "") // should pick last446 err = b.Bind(req, &obj)447 require.NoError(t, err)448 assert.NotNil(t, obj)449 assert.Len(t, obj, 2)450 assert.Equal(t, "2", obj["foo"])451 assert.Equal(t, "world", obj["hello"])452}453454func TestBindingXML(t *testing.T) {455 testBodyBinding(t,456 XML, "xml",457 "/", "/",458 "<map><foo>bar</foo></map>", "<map><bar>foo</bar></map>")459}460461func TestBindingXMLFail(t *testing.T) {462 testBodyBindingFail(t,463 XML, "xml",464 "/", "/",465 "<map><foo>bar<foo></map>", "<map><bar>foo</bar></map>")466}467468func TestBindingTOML(t *testing.T) {469 testBodyBinding(t,470 TOML, "toml",471 "/", "/",472 `foo="bar"`, `bar="foo"`)473}474475func TestBindingTOMLFail(t *testing.T) {476 testBodyBindingFail(t,477 TOML, "toml",478 "/", "/",479 `foo=\n"bar"`, `bar="foo"`)480}481482func TestBindingYAML(t *testing.T) {483 testBodyBinding(t,484 YAML, "yaml",485 "/", "/",486 `foo: bar`, `bar: foo`)487}488489func TestBindingYAMLStringMap(t *testing.T) {490 // YAML is a superset of JSON, so the test below is JSON (to avoid newlines)491 testBodyBindingStringMap(t, YAML,492 "/", "/",493 `{"foo": "bar", "hello": "world"}`, `{"nested": {"foo": "bar"}}`)494}495496func TestBindingYAMLFail(t *testing.T) {497 testBodyBindingFail(t,498 YAML, "yaml",499 "/", "/",500 `foo:\nbar`, `bar: foo`)501}502503func createFormPostRequest(t *testing.T) *http.Request {504 req, err := http.NewRequest(http.MethodPost, "/?foo=getfoo&bar=getbar", bytes.NewBufferString("foo=bar&bar=foo"))505 require.NoError(t, err)506 req.Header.Set("Content-Type", MIMEPOSTForm)507 return req508}509510func createDefaultFormPostRequest(t *testing.T) *http.Request {511 req, err := http.NewRequest(http.MethodPost, "/?foo=getfoo&bar=getbar", bytes.NewBufferString("foo=bar"))512 require.NoError(t, err)513 req.Header.Set("Content-Type", MIMEPOSTForm)514 return req515}516517func createFormPostRequestForMap(t *testing.T) *http.Request {518 req, err := http.NewRequest(http.MethodPost, "/?map_foo=getfoo", bytes.NewBufferString("map_foo={\"bar\":123}"))519 require.NoError(t, err)520 req.Header.Set("Content-Type", MIMEPOSTForm)521 return req522}523524func createFormPostRequestForMapFail(t *testing.T) *http.Request {525 req, err := http.NewRequest(http.MethodPost, "/?map_foo=getfoo", bytes.NewBufferString("map_foo=hello"))526 require.NoError(t, err)527 req.Header.Set("Content-Type", MIMEPOSTForm)528 return req529}530531func createFormFilesMultipartRequest(t *testing.T) *http.Request {532 boundary := "--testboundary"533 body := new(bytes.Buffer)534 mw := multipart.NewWriter(body)535 defer mw.Close()536537 require.NoError(t, mw.SetBoundary(boundary))538 require.NoError(t, mw.WriteField("foo", "bar"))539 require.NoError(t, mw.WriteField("bar", "foo"))540541 f, err := os.Open("form.go")542 require.NoError(t, err)543 defer f.Close()544 fw, err1 := mw.CreateFormFile("file", "form.go")545 require.NoError(t, err1)546 _, err = io.Copy(fw, f)547 require.NoError(t, err)548549 req, err2 := http.NewRequest(http.MethodPost, "/?foo=getfoo&bar=getbar", body)550 require.NoError(t, err2)551 req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)552553 return req554}555556func createFormFilesMultipartRequestFail(t *testing.T) *http.Request {557 boundary := "--testboundary"558 body := new(bytes.Buffer)559 mw := multipart.NewWriter(body)560 defer mw.Close()561562 require.NoError(t, mw.SetBoundary(boundary))563 require.NoError(t, mw.WriteField("foo", "bar"))564 require.NoError(t, mw.WriteField("bar", "foo"))565566 f, err := os.Open("form.go")567 require.NoError(t, err)568 defer f.Close()569 fw, err1 := mw.CreateFormFile("file_foo", "form_foo.go")570 require.NoError(t, err1)571 _, err = io.Copy(fw, f)572 require.NoError(t, err)573574 req, err2 := http.NewRequest(http.MethodPost, "/?foo=getfoo&bar=getbar", body)575 require.NoError(t, err2)576 req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)577578 return req579}580581func createFormMultipartRequest(t *testing.T) *http.Request {582 boundary := "--testboundary"583 body := new(bytes.Buffer)584 mw := multipart.NewWriter(body)585 defer mw.Close()586587 require.NoError(t, mw.SetBoundary(boundary))588 require.NoError(t, mw.WriteField("foo", "bar"))589 require.NoError(t, mw.WriteField("bar", "foo"))590 req, err := http.NewRequest(http.MethodPost, "/?foo=getfoo&bar=getbar", body)591 require.NoError(t, err)592 req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)593 return req594}595596func createFormMultipartRequestForMap(t *testing.T) *http.Request {597 boundary := "--testboundary"598 body := new(bytes.Buffer)599 mw := multipart.NewWriter(body)600 defer mw.Close()601602 require.NoError(t, mw.SetBoundary(boundary))603 require.NoError(t, mw.WriteField("map_foo", "{\"bar\":123, \"name\":\"thinkerou\", \"pai\": 3.14}"))604 req, err := http.NewRequest(http.MethodPost, "/?map_foo=getfoo", body)605 require.NoError(t, err)606 req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)607 return req608}609610func createFormMultipartRequestForMapFail(t *testing.T) *http.Request {611 boundary := "--testboundary"612 body := new(bytes.Buffer)613 mw := multipart.NewWriter(body)614 defer mw.Close()615616 require.NoError(t, mw.SetBoundary(boundary))617 require.NoError(t, mw.WriteField("map_foo", "3.14"))618 req, err := http.NewRequest(http.MethodPost, "/?map_foo=getfoo", body)619 require.NoError(t, err)620 req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)621 return req622}623624func TestBindingFormPost(t *testing.T) {625 req := createFormPostRequest(t)626 var obj FooBarStruct627 require.NoError(t, FormPost.Bind(req, &obj))628629 assert.Equal(t, "form-urlencoded", FormPost.Name())630 assert.Equal(t, "bar", obj.Foo)631 assert.Equal(t, "foo", obj.Bar)632}633634func TestBindingDefaultValueFormPost(t *testing.T) {635 req := createDefaultFormPostRequest(t)636 var obj FooDefaultBarStruct637 require.NoError(t, FormPost.Bind(req, &obj))638639 assert.Equal(t, "bar", obj.Foo)640 assert.Equal(t, "hello", obj.Bar)641}642643func TestBindingFormPostForMap(t *testing.T) {644 req := createFormPostRequestForMap(t)645 var obj FooStructForMapType646 err := FormPost.Bind(req, &obj)647 require.NoError(t, err)648 assert.InDelta(t, float64(123), obj.MapFoo["bar"].(float64), 0.01)649}650651func TestBindingFormPostForMapFail(t *testing.T) {652 req := createFormPostRequestForMapFail(t)653 var obj FooStructForMapType654 err := FormPost.Bind(req, &obj)655 require.Error(t, err)656}657658func TestBindingFormFilesMultipart(t *testing.T) {659 req := createFormFilesMultipartRequest(t)660 var obj FooBarFileStruct661 err := FormMultipart.Bind(req, &obj)662 require.NoError(t, err)663664 // file from os665 f, _ := os.Open("form.go")666 defer f.Close()667 fileActual, _ := io.ReadAll(f)668669 // file from multipart670 mf, _ := obj.File.Open()671 defer mf.Close()672 fileExpect, _ := io.ReadAll(mf)673674 assert.Equal(t, "multipart/form-data", FormMultipart.Name())675 assert.Equal(t, "bar", obj.Foo)676 assert.Equal(t, "foo", obj.Bar)677 assert.Equal(t, fileExpect, fileActual)678}679680func TestBindingFormFilesMultipartFail(t *testing.T) {681 req := createFormFilesMultipartRequestFail(t)682 var obj FooBarFileFailStruct683 err := FormMultipart.Bind(req, &obj)684 require.Error(t, err)685}686687func TestBindingFormMultipart(t *testing.T) {688 req := createFormMultipartRequest(t)689 var obj FooBarStruct690 require.NoError(t, FormMultipart.Bind(req, &obj))691692 assert.Equal(t, "multipart/form-data", FormMultipart.Name())693 assert.Equal(t, "bar", obj.Foo)694 assert.Equal(t, "foo", obj.Bar)695}696697func TestBindingFormMultipartForMap(t *testing.T) {698 req := createFormMultipartRequestForMap(t)699 var obj FooStructForMapType700 err := FormMultipart.Bind(req, &obj)701 require.NoError(t, err)702 assert.InDelta(t, float64(123), obj.MapFoo["bar"].(float64), 0.01)703 assert.Equal(t, "thinkerou", obj.MapFoo["name"].(string))704 assert.InDelta(t, float64(3.14), obj.MapFoo["pai"].(float64), 0.01)705}706707func TestBindingFormMultipartForMapFail(t *testing.T) {708 req := createFormMultipartRequestForMapFail(t)709 var obj FooStructForMapType710 err := FormMultipart.Bind(req, &obj)711 require.Error(t, err)712}713714func TestBindingProtoBuf(t *testing.T) {715 test := &protoexample.Test{716 Label: proto.String("yes"),717 }718 data, _ := proto.Marshal(test)719720 testProtoBodyBinding(t,721 ProtoBuf, "protobuf",722 "/", "/",723 string(data), string(data[1:]))724}725726func TestBindingProtoBufFail(t *testing.T) {727 test := &protoexample.Test{728 Label: proto.String("yes"),729 }730 data, _ := proto.Marshal(test)731732 testProtoBodyBindingFail(t,733 ProtoBuf, "protobuf",734 "/", "/",735 string(data), string(data[1:]))feat(render): add bson protocol (#4145)Laurent Caumontbefore adoptiond7776de
lines 736–747why, one step back736}737738func TestBindingBSON(t *testing.T) {739 var obj FooStruct740 obj.Foo = "bar"741 data, _ := bson.Marshal(&obj)742 testBodyBinding(t,743 BSON, "bson",744 "/", "/",745 string(data),746 // note: for badbody, we remove first byte to make it invalid747 string(data[1:]))chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d
lines 748–1079why, one step back748}749750func TestValidationFails(t *testing.T) {751 var obj FooStruct752 req := requestWithBody(http.MethodPost, "/", `{"bar": "foo"}`)753 err := JSON.Bind(req, &obj)754 require.Error(t, err)755}756757func TestValidationDisabled(t *testing.T) {758 backup := Validator759 Validator = nil760 defer func() { Validator = backup }()761762 var obj FooStruct763 req := requestWithBody(http.MethodPost, "/", `{"bar": "foo"}`)764 err := JSON.Bind(req, &obj)765 require.NoError(t, err)766}767768func TestRequiredSucceeds(t *testing.T) {769 type HogeStruct struct {770 Hoge *int `json:"hoge" binding:"required"`771 }772773 var obj HogeStruct774 req := requestWithBody(http.MethodPost, "/", `{"hoge": 0}`)775 err := JSON.Bind(req, &obj)776 require.NoError(t, err)777}778779func TestRequiredFails(t *testing.T) {780 type HogeStruct struct {781 Hoge *int `json:"foo" binding:"required"`782 }783784 var obj HogeStruct785 req := requestWithBody(http.MethodPost, "/", `{"boen": 0}`)786 err := JSON.Bind(req, &obj)787 require.Error(t, err)788}789790func TestHeaderBinding(t *testing.T) {791 h := Header792 assert.Equal(t, "header", h.Name())793794 type tHeader struct {795 Limit int `header:"limit"`796 }797798 var theader tHeader799 req := requestWithBody(http.MethodGet, "/", "")800 req.Header.Add("limit", "1000")801 require.NoError(t, h.Bind(req, &theader))802 assert.Equal(t, 1000, theader.Limit)803804 req = requestWithBody(http.MethodGet, "/", "")805 req.Header.Add("fail", `{fail:fail}`)806807 type failStruct struct {808 Fail map[string]any `header:"fail"`809 }810811 err := h.Bind(req, &failStruct{})812 require.Error(t, err)813}814815func TestUriBinding(t *testing.T) {816 b := Uri817 assert.Equal(t, "uri", b.Name())818819 type Tag struct {820 Name string `uri:"name"`821 }822 var tag Tag823 m := make(map[string][]string)824 m["name"] = []string{"thinkerou"}825 require.NoError(t, b.BindUri(m, &tag))826 assert.Equal(t, "thinkerou", tag.Name)827828 type NotSupportStruct struct {829 Name map[string]any `uri:"name"`830 }831 var not NotSupportStruct832 require.Error(t, b.BindUri(m, ¬))833 assert.Equal(t, map[string]any(nil), not.Name)834}835836func TestUriInnerBinding(t *testing.T) {837 type Tag struct {838 Name string `uri:"name"`839 S struct {840 Age int `uri:"age"`841 }842 }843844 expectedName := "mike"845 expectedAge := 25846847 m := map[string][]string{848 "name": {expectedName},849 "age": {strconv.Itoa(expectedAge)},850 }851852 var tag Tag853 require.NoError(t, Uri.BindUri(m, &tag))854 assert.Equal(t, expectedName, tag.Name)855 assert.Equal(t, expectedAge, tag.S.Age)856}857858func testFormBindingEmbeddedStruct(t *testing.T, method, path, badPath, body, badBody string) {859 b := Form860 assert.Equal(t, "form", b.Name())861862 obj := QueryTest{}863 req := requestWithBody(method, path, body)864 if method == http.MethodPost {865 req.Header.Add("Content-Type", MIMEPOSTForm)866 }867 err := b.Bind(req, &obj)868 require.NoError(t, err)869 assert.Equal(t, 1, obj.Page)870 assert.Equal(t, 2, obj.Size)871 assert.Equal(t, "test-appkey", obj.Appkey)872}873874func testFormBinding(t *testing.T, method, path, badPath, body, badBody string) {875 b := Form876 assert.Equal(t, "form", b.Name())877878 obj := FooBarStruct{}879 req := requestWithBody(method, path, body)880 if method == http.MethodPost {881 req.Header.Add("Content-Type", MIMEPOSTForm)882 }883 err := b.Bind(req, &obj)884 require.NoError(t, err)885 assert.Equal(t, "bar", obj.Foo)886 assert.Equal(t, "foo", obj.Bar)887888 obj = FooBarStruct{}889 req = requestWithBody(method, badPath, badBody)890 err = JSON.Bind(req, &obj)891 require.Error(t, err)892}893894func testFormBindingDefaultValue(t *testing.T, method, path, badPath, body, badBody string) {895 b := Form896 assert.Equal(t, "form", b.Name())897898 obj := FooDefaultBarStruct{}899 req := requestWithBody(method, path, body)900 if method == http.MethodPost {901 req.Header.Add("Content-Type", MIMEPOSTForm)902 }903 err := b.Bind(req, &obj)904 require.NoError(t, err)905 assert.Equal(t, "bar", obj.Foo)906 assert.Equal(t, "hello", obj.Bar)907908 obj = FooDefaultBarStruct{}909 req = requestWithBody(method, badPath, badBody)910 err = JSON.Bind(req, &obj)911 require.Error(t, err)912}913914func TestFormBindingFail(t *testing.T) {915 b := Form916 assert.Equal(t, "form", b.Name())917918 obj := FooBarStruct{}919 req, _ := http.NewRequest(http.MethodPost, "/", nil)920 err := b.Bind(req, &obj)921 require.Error(t, err)922}923924func TestFormBindingMultipartFail(t *testing.T) {925 obj := FooBarStruct{}926 req, err := http.NewRequest(http.MethodPost, "/", strings.NewReader("foo=bar"))927 require.NoError(t, err)928 req.Header.Set("Content-Type", MIMEMultipartPOSTForm+";boundary=testboundary")929 _, err = req.MultipartReader()930 require.NoError(t, err)931 err = Form.Bind(req, &obj)932 require.Error(t, err)933}934935func TestFormPostBindingFail(t *testing.T) {936 b := FormPost937 assert.Equal(t, "form-urlencoded", b.Name())938939 obj := FooBarStruct{}940 req, _ := http.NewRequest(http.MethodPost, "/", nil)941 err := b.Bind(req, &obj)942 require.Error(t, err)943}944945func TestFormMultipartBindingFail(t *testing.T) {946 b := FormMultipart947 assert.Equal(t, "multipart/form-data", b.Name())948949 obj := FooBarStruct{}950 req, _ := http.NewRequest(http.MethodPost, "/", nil)951 err := b.Bind(req, &obj)952 require.Error(t, err)953}954955func testFormBindingForTime(t *testing.T, method, path, badPath, body, badBody string) {956 b := Form957 assert.Equal(t, "form", b.Name())958959 obj := FooBarStructForTimeType{}960 req := requestWithBody(method, path, body)961 if method == http.MethodPost {962 req.Header.Add("Content-Type", MIMEPOSTForm)963 }964 err := b.Bind(req, &obj)965966 require.NoError(t, err)967 assert.Equal(t, int64(1510675200), obj.TimeFoo.Unix())968 assert.Equal(t, "Asia/Chongqing", obj.TimeFoo.Location().String())969 assert.Equal(t, int64(-62135596800), obj.TimeBar.Unix())970 assert.Equal(t, "UTC", obj.TimeBar.Location().String())971 assert.Equal(t, int64(1562400033000000123), obj.CreateTime.UnixNano())972 assert.Equal(t, int64(1562400033), obj.UnixTime.Unix())973 assert.Equal(t, int64(1562400033001), obj.UnixMilliTime.UnixMilli())974 assert.Equal(t, int64(1562400033000012), obj.UnixMicroTime.UnixMicro())975976 obj = FooBarStructForTimeType{}977 req = requestWithBody(method, badPath, badBody)978 err = JSON.Bind(req, &obj)979 require.Error(t, err)980}981982func testFormBindingForTimeNotUnixFormat(t *testing.T, method, path, badPath, body, badBody string) {983 b := Form984 assert.Equal(t, "form", b.Name())985986 obj := FooStructForTimeTypeNotUnixFormat{}987 req := requestWithBody(method, path, body)988 if method == http.MethodPost {989 req.Header.Add("Content-Type", MIMEPOSTForm)990 }991 err := b.Bind(req, &obj)992 require.Error(t, err)993994 obj = FooStructForTimeTypeNotUnixFormat{}995 req = requestWithBody(method, badPath, badBody)996 err = JSON.Bind(req, &obj)997 require.Error(t, err)998}9991000func testFormBindingForTimeNotFormat(t *testing.T, method, path, badPath, body, badBody string) {1001 b := Form1002 assert.Equal(t, "form", b.Name())10031004 obj := FooStructForTimeTypeNotFormat{}1005 req := requestWithBody(method, path, body)1006 if method == http.MethodPost {1007 req.Header.Add("Content-Type", MIMEPOSTForm)1008 }1009 err := b.Bind(req, &obj)1010 require.Error(t, err)10111012 obj = FooStructForTimeTypeNotFormat{}1013 req = requestWithBody(method, badPath, badBody)1014 err = JSON.Bind(req, &obj)1015 require.Error(t, err)1016}10171018func testFormBindingForTimeFailFormat(t *testing.T, method, path, badPath, body, badBody string) {1019 b := Form1020 assert.Equal(t, "form", b.Name())10211022 obj := FooStructForTimeTypeFailFormat{}1023 req := requestWithBody(method, path, body)1024 if method == http.MethodPost {1025 req.Header.Add("Content-Type", MIMEPOSTForm)1026 }1027 err := b.Bind(req, &obj)1028 require.Error(t, err)10291030 obj = FooStructForTimeTypeFailFormat{}1031 req = requestWithBody(method, badPath, badBody)1032 err = JSON.Bind(req, &obj)1033 require.Error(t, err)1034}10351036func testFormBindingForTimeFailLocation(t *testing.T, method, path, badPath, body, badBody string) {1037 b := Form1038 assert.Equal(t, "form", b.Name())10391040 obj := FooStructForTimeTypeFailLocation{}1041 req := requestWithBody(method, path, body)1042 if method == http.MethodPost {1043 req.Header.Add("Content-Type", MIMEPOSTForm)1044 }1045 err := b.Bind(req, &obj)1046 require.Error(t, err)10471048 obj = FooStructForTimeTypeFailLocation{}1049 req = requestWithBody(method, badPath, badBody)1050 err = JSON.Bind(req, &obj)1051 require.Error(t, err)1052}10531054func testFormBindingIgnoreField(t *testing.T, method, path, badPath, body, badBody string) {1055 b := Form1056 assert.Equal(t, "form", b.Name())10571058 obj := FooStructForIgnoreFormTag{}1059 req := requestWithBody(method, path, body)1060 if method == http.MethodPost {1061 req.Header.Add("Content-Type", MIMEPOSTForm)1062 }1063 err := b.Bind(req, &obj)1064 require.NoError(t, err)10651066 assert.Nil(t, obj.Foo)1067}10681069func testFormBindingInvalidName(t *testing.T, method, path, badPath, body, badBody string) {1070 b := Form1071 assert.Equal(t, "form", b.Name())10721073 obj := InvalidNameType{}1074 req := requestWithBody(method, path, body)1075 if method == http.MethodPost {1076 req.Header.Add("Content-Type", MIMEPOSTForm)1077 }1078 err := b.Bind(req, &obj)1079 require.NoError(t, err)ci(golangci-lint): update configuration and fix lint issues (#4247)Flc゛before adoptionc4287b1
line 1080why, one step back1080 assert.Empty(t, obj.TestName)chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d
lines 1081–1334why, one step back10811082 obj = InvalidNameType{}1083 req = requestWithBody(method, badPath, badBody)1084 err = JSON.Bind(req, &obj)1085 require.Error(t, err)1086}10871088func testFormBindingInvalidName2(t *testing.T, method, path, badPath, body, badBody string) {1089 b := Form1090 assert.Equal(t, "form", b.Name())10911092 obj := InvalidNameMapType{}1093 req := requestWithBody(method, path, body)1094 if method == http.MethodPost {1095 req.Header.Add("Content-Type", MIMEPOSTForm)1096 }1097 err := b.Bind(req, &obj)1098 require.Error(t, err)10991100 obj = InvalidNameMapType{}1101 req = requestWithBody(method, badPath, badBody)1102 err = JSON.Bind(req, &obj)1103 require.Error(t, err)1104}11051106func testFormBindingForType(t *testing.T, method, path, badPath, body, badBody string, typ string) {1107 b := Form1108 assert.Equal(t, "form", b.Name())11091110 req := requestWithBody(method, path, body)1111 if method == http.MethodPost {1112 req.Header.Add("Content-Type", MIMEPOSTForm)1113 }1114 switch typ {1115 case "Slice":1116 obj := FooStructForSliceType{}1117 err := b.Bind(req, &obj)1118 require.NoError(t, err)1119 assert.Equal(t, []int{1, 2}, obj.SliceFoo)11201121 obj = FooStructForSliceType{}1122 req = requestWithBody(method, badPath, badBody)1123 err = JSON.Bind(req, &obj)1124 require.Error(t, err)1125 case "Struct":1126 obj := FooStructForStructType{}1127 err := b.Bind(req, &obj)1128 require.NoError(t, err)1129 assert.Equal(t,1130 struct {1131 Idx int "form:\"idx\""1132 }{Idx: 123},1133 obj.StructFoo)1134 case "StructPointer":1135 obj := FooStructForStructPointerType{}1136 err := b.Bind(req, &obj)1137 require.NoError(t, err)1138 assert.Equal(t,1139 struct {1140 Name string "form:\"name\""1141 }{Name: "thinkerou"},1142 *obj.StructPointerFoo)1143 case "Map":1144 obj := FooStructForMapType{}1145 err := b.Bind(req, &obj)1146 require.NoError(t, err)1147 assert.InDelta(t, float64(123), obj.MapFoo["bar"].(float64), 0.01)1148 case "SliceMap":1149 obj := FooStructForSliceMapType{}1150 err := b.Bind(req, &obj)1151 require.Error(t, err)1152 case "Ptr":1153 obj := FooStructForStringPtrType{}1154 err := b.Bind(req, &obj)1155 require.NoError(t, err)1156 assert.Nil(t, obj.PtrFoo)1157 assert.Equal(t, "test", *obj.PtrBar)11581159 obj = FooStructForStringPtrType{}1160 obj.PtrBar = new(string)1161 err = b.Bind(req, &obj)1162 require.NoError(t, err)1163 assert.Equal(t, "test", *obj.PtrBar)11641165 objErr := FooStructForMapPtrType{}1166 err = b.Bind(req, &objErr)1167 require.Error(t, err)11681169 obj = FooStructForStringPtrType{}1170 req = requestWithBody(method, badPath, badBody)1171 err = b.Bind(req, &obj)1172 require.Error(t, err)1173 }1174}11751176func testQueryBinding(t *testing.T, method, path, badPath, body, badBody string) {1177 b := Query1178 assert.Equal(t, "query", b.Name())11791180 obj := FooBarStruct{}1181 req := requestWithBody(method, path, body)1182 if method == http.MethodPost {1183 req.Header.Add("Content-Type", MIMEPOSTForm)1184 }1185 err := b.Bind(req, &obj)1186 require.NoError(t, err)1187 assert.Equal(t, "bar", obj.Foo)1188 assert.Equal(t, "foo", obj.Bar)1189}11901191func testQueryBindingFail(t *testing.T, method, path, badPath, body, badBody string) {1192 b := Query1193 assert.Equal(t, "query", b.Name())11941195 obj := FooStructForMapType{}1196 req := requestWithBody(method, path, body)1197 if method == http.MethodPost {1198 req.Header.Add("Content-Type", MIMEPOSTForm)1199 }1200 err := b.Bind(req, &obj)1201 require.Error(t, err)1202}12031204func testQueryBindingBoolFail(t *testing.T, method, path, badPath, body, badBody string) {1205 b := Query1206 assert.Equal(t, "query", b.Name())12071208 obj := FooStructForBoolType{}1209 req := requestWithBody(method, path, body)1210 if method == http.MethodPost {1211 req.Header.Add("Content-Type", MIMEPOSTForm)1212 }1213 err := b.Bind(req, &obj)1214 require.Error(t, err)1215}12161217func testBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) {1218 assert.Equal(t, name, b.Name())12191220 obj := FooStruct{}1221 req := requestWithBody(http.MethodPost, path, body)1222 err := b.Bind(req, &obj)1223 require.NoError(t, err)1224 assert.Equal(t, "bar", obj.Foo)12251226 obj = FooStruct{}1227 req = requestWithBody(http.MethodPost, badPath, badBody)1228 err = JSON.Bind(req, &obj)1229 require.Error(t, err)1230}12311232func testBodyBindingSlice(t *testing.T, b Binding, name, path, badPath, body, badBody string) {1233 assert.Equal(t, name, b.Name())12341235 var obj1 []FooStruct1236 req := requestWithBody(http.MethodPost, path, body)1237 err := b.Bind(req, &obj1)1238 require.NoError(t, err)12391240 var obj2 []FooStruct1241 req = requestWithBody(http.MethodPost, badPath, badBody)1242 err = JSON.Bind(req, &obj2)1243 require.Error(t, err)1244}12451246func testBodyBindingStringMap(t *testing.T, b Binding, path, badPath, body, badBody string) {1247 obj := make(map[string]string)1248 req := requestWithBody(http.MethodPost, path, body)1249 if b.Name() == "form" {1250 req.Header.Add("Content-Type", MIMEPOSTForm)1251 }1252 err := b.Bind(req, &obj)1253 require.NoError(t, err)1254 assert.NotNil(t, obj)1255 assert.Len(t, obj, 2)1256 assert.Equal(t, "bar", obj["foo"])1257 assert.Equal(t, "world", obj["hello"])12581259 if badPath != "" && badBody != "" {1260 obj = make(map[string]string)1261 req = requestWithBody(http.MethodPost, badPath, badBody)1262 err = b.Bind(req, &obj)1263 require.Error(t, err)1264 }12651266 objInt := make(map[string]int)1267 req = requestWithBody(http.MethodPost, path, body)1268 err = b.Bind(req, &objInt)1269 require.Error(t, err)1270}12711272func testBodyBindingUseNumber(t *testing.T, b Binding, name, path, badPath, body, badBody string) {1273 assert.Equal(t, name, b.Name())12741275 obj := FooStructUseNumber{}1276 req := requestWithBody(http.MethodPost, path, body)1277 EnableDecoderUseNumber = true1278 err := b.Bind(req, &obj)1279 require.NoError(t, err)1280 // we hope it is int64(123)1281 v, e := obj.Foo.(json.Number).Int64()1282 require.NoError(t, e)1283 assert.Equal(t, int64(123), v)12841285 obj = FooStructUseNumber{}1286 req = requestWithBody(http.MethodPost, badPath, badBody)1287 err = JSON.Bind(req, &obj)1288 require.Error(t, err)1289}12901291func testBodyBindingUseNumber2(t *testing.T, b Binding, name, path, badPath, body, badBody string) {1292 assert.Equal(t, name, b.Name())12931294 obj := FooStructUseNumber{}1295 req := requestWithBody(http.MethodPost, path, body)1296 EnableDecoderUseNumber = false1297 err := b.Bind(req, &obj)1298 require.NoError(t, err)1299 // it will return float64(123) if not use EnableDecoderUseNumber1300 // maybe it is not hoped1301 assert.InDelta(t, float64(123), obj.Foo, 0.01)13021303 obj = FooStructUseNumber{}1304 req = requestWithBody(http.MethodPost, badPath, badBody)1305 err = JSON.Bind(req, &obj)1306 require.Error(t, err)1307}13081309func testBodyBindingDisallowUnknownFields(t *testing.T, b Binding, path, badPath, body, badBody string) {1310 EnableDecoderDisallowUnknownFields = true1311 defer func() {1312 EnableDecoderDisallowUnknownFields = false1313 }()13141315 obj := FooStructDisallowUnknownFields{}1316 req := requestWithBody(http.MethodPost, path, body)1317 err := b.Bind(req, &obj)1318 require.NoError(t, err)1319 assert.Equal(t, "bar", obj.Foo)13201321 obj = FooStructDisallowUnknownFields{}1322 req = requestWithBody(http.MethodPost, badPath, badBody)1323 err = JSON.Bind(req, &obj)1324 require.Error(t, err)1325 assert.Contains(t, err.Error(), "what")1326}13271328func testBodyBindingFail(t *testing.T, b Binding, name, path, badPath, body, badBody string) {1329 assert.Equal(t, name, b.Name())13301331 obj := FooStruct{}1332 req := requestWithBody(http.MethodPost, path, body)1333 err := b.Bind(req, &obj)1334 require.Error(t, err)ci(golangci-lint): update configuration and fix lint issues (#4247)Flc゛before adoptionc4287b1
line 1335why, one step back1335 assert.Empty(t, obj.Foo)chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d
lines 1336–1434why, one step back13361337 obj = FooStruct{}1338 req = requestWithBody(http.MethodPost, badPath, badBody)1339 err = JSON.Bind(req, &obj)1340 require.Error(t, err)1341}13421343func testProtoBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) {1344 assert.Equal(t, name, b.Name())13451346 obj := protoexample.Test{}1347 req := requestWithBody(http.MethodPost, path, body)1348 req.Header.Add("Content-Type", MIMEPROTOBUF)1349 err := b.Bind(req, &obj)1350 require.NoError(t, err)1351 assert.Equal(t, "yes", *obj.Label)13521353 obj = protoexample.Test{}1354 req = requestWithBody(http.MethodPost, badPath, badBody)1355 req.Header.Add("Content-Type", MIMEPROTOBUF)1356 err = ProtoBuf.Bind(req, &obj)1357 require.Error(t, err)1358}13591360type hook struct{}13611362func (h hook) Read([]byte) (int, error) {1363 return 0, errors.New("error")1364}13651366type failRead struct{}13671368func (f *failRead) Read(b []byte) (n int, err error) {1369 return 0, errors.New("my fail")1370}13711372func (f *failRead) Close() error {1373 return nil1374}13751376func TestPlainBinding(t *testing.T) {1377 p := Plain1378 assert.Equal(t, "plain", p.Name())13791380 var s string1381 req := requestWithBody(http.MethodPost, "/", "test string")1382 require.NoError(t, p.Bind(req, &s))1383 assert.Equal(t, "test string", s)13841385 var bs []byte1386 req = requestWithBody(http.MethodPost, "/", "test []byte")1387 require.NoError(t, p.Bind(req, &bs))1388 assert.Equal(t, bs, []byte("test []byte"))13891390 var i int1391 req = requestWithBody(http.MethodPost, "/", "test fail")1392 require.Error(t, p.Bind(req, &i))13931394 req = requestWithBody(http.MethodPost, "/", "")1395 req.Body = &failRead{}1396 require.Error(t, p.Bind(req, &s))13971398 req = requestWithBody(http.MethodPost, "/", "")1399 require.NoError(t, p.Bind(req, nil))14001401 var ptr *string1402 req = requestWithBody(http.MethodPost, "/", "")1403 require.NoError(t, p.Bind(req, ptr))1404}14051406func testProtoBodyBindingFail(t *testing.T, b Binding, name, path, badPath, body, badBody string) {1407 assert.Equal(t, name, b.Name())14081409 obj := protoexample.Test{}1410 req := requestWithBody(http.MethodPost, path, body)14111412 req.Body = io.NopCloser(&hook{})1413 req.Header.Add("Content-Type", MIMEPROTOBUF)1414 err := b.Bind(req, &obj)1415 require.Error(t, err)14161417 invalidobj := FooStruct{}1418 req.Body = io.NopCloser(strings.NewReader(`{"msg":"hello"}`))1419 req.Header.Add("Content-Type", MIMEPROTOBUF)1420 err = b.Bind(req, &invalidobj)1421 require.Error(t, err)1422 assert.Equal(t, "obj is not ProtoMessage", err.Error())14231424 obj = protoexample.Test{}1425 req = requestWithBody(http.MethodPost, badPath, badBody)1426 req.Header.Add("Content-Type", MIMEPROTOBUF)1427 err = ProtoBuf.Bind(req, &obj)1428 require.Error(t, err)1429}14301431func requestWithBody(method, path, body string) (req *http.Request) {1432 req, _ = http.NewRequest(method, path, bytes.NewBufferString(body))1433 return1434}