Skip to content
Myr

ci(lint): enable usestdlibvars linter (#4091)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Matthieu MOREL · committed by GitHub · parent 02c1144 · Browse files · 16 files+317 added−314 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Signed-off-by: Matthieu MOREL <matthieu.morel35@gmail.com>

Diff stats

16 files+317 added−314 removed

  • other:+317 added−314 removed

16 files+317 added−314 removed

modified:binding/binding_msgpack_test.go+5 added-4 removed
6 unmodified lines
7package binding89import (10 "bytes"11 "net/http"12 "testing"1314 "github.com/stretchr/testify/assert"15 "github.com/stretchr/testify/require"
23 unmodified lines
39func testMsgPackBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) {40 assert.Equal(t, name, b.Name())4142 obj := FooStruct{}42 req := requestWithBody("POST", path, body)43 req := requestWithBody(http.MethodPost, path, body)44 req.Header.Add("Content-Type", MIMEMSGPACK)45 err := b.Bind(req, &obj)46 require.NoError(t, err)47 assert.Equal(t, "bar", obj.Foo)4849 obj = FooStruct{}49 req = requestWithBody("POST", badPath, badBody)50 req = requestWithBody(http.MethodPost, badPath, badBody)51 req.Header.Add("Content-Type", MIMEMSGPACK)52 err = MsgPack.Bind(req, &obj)53 require.Error(t, err)54}5556func TestBindingDefaultMsgPack(t *testing.T) {56 assert.Equal(t, MsgPack, Default("POST", MIMEMSGPACK))57 assert.Equal(t, MsgPack, Default("PUT", MIMEMSGPACK2))57 assert.Equal(t, MsgPack, Default(http.MethodPost, MIMEMSGPACK))58 assert.Equal(t, MsgPack, Default(http.MethodPut, MIMEMSGPACK2))59}
modified:binding/binding_test.go+116 added-116 removed
143 unmodified lines
144 PtrBar *map[string]any `form:"ptr_bar"`145}146147func TestBindingDefault(t *testing.T) {148 assert.Equal(t, Form, Default("GET", ""))149 assert.Equal(t, Form, Default("GET", MIMEJSON))148 assert.Equal(t, Form, Default(http.MethodGet, ""))149 assert.Equal(t, Form, Default(http.MethodGet, MIMEJSON))150151 assert.Equal(t, JSON, Default("POST", MIMEJSON))152 assert.Equal(t, JSON, Default("PUT", MIMEJSON))151 assert.Equal(t, JSON, Default(http.MethodPost, MIMEJSON))152 assert.Equal(t, JSON, Default(http.MethodPut, MIMEJSON))153154 assert.Equal(t, XML, Default("POST", MIMEXML))155 assert.Equal(t, XML, Default("PUT", MIMEXML2))154 assert.Equal(t, XML, Default(http.MethodPost, MIMEXML))155 assert.Equal(t, XML, Default(http.MethodPut, MIMEXML2))156157 assert.Equal(t, Form, Default("POST", MIMEPOSTForm))158 assert.Equal(t, Form, Default("PUT", MIMEPOSTForm))157 assert.Equal(t, Form, Default(http.MethodPost, MIMEPOSTForm))158 assert.Equal(t, Form, Default(http.MethodPut, MIMEPOSTForm))159160 assert.Equal(t, FormMultipart, Default("POST", MIMEMultipartPOSTForm))161 assert.Equal(t, FormMultipart, Default("PUT", MIMEMultipartPOSTForm))160 assert.Equal(t, FormMultipart, Default(http.MethodPost, MIMEMultipartPOSTForm))161 assert.Equal(t, FormMultipart, Default(http.MethodPut, MIMEMultipartPOSTForm))162163 assert.Equal(t, ProtoBuf, Default("POST", MIMEPROTOBUF))164 assert.Equal(t, ProtoBuf, Default("PUT", MIMEPROTOBUF))163 assert.Equal(t, ProtoBuf, Default(http.MethodPost, MIMEPROTOBUF))164 assert.Equal(t, ProtoBuf, Default(http.MethodPut, MIMEPROTOBUF))165166 assert.Equal(t, YAML, Default("POST", MIMEYAML))167 assert.Equal(t, YAML, Default("PUT", MIMEYAML))168 assert.Equal(t, YAML, Default("POST", MIMEYAML2))169 assert.Equal(t, YAML, Default("PUT", MIMEYAML2))166 assert.Equal(t, YAML, Default(http.MethodPost, MIMEYAML))167 assert.Equal(t, YAML, Default(http.MethodPut, MIMEYAML))168 assert.Equal(t, YAML, Default(http.MethodPost, MIMEYAML2))169 assert.Equal(t, YAML, Default(http.MethodPut, MIMEYAML2))170171 assert.Equal(t, TOML, Default("POST", MIMETOML))172 assert.Equal(t, TOML, Default("PUT", MIMETOML))171 assert.Equal(t, TOML, Default(http.MethodPost, MIMETOML))172 assert.Equal(t, TOML, Default(http.MethodPut, MIMETOML))173}174175func TestBindingJSONNilBody(t *testing.T) {176 var obj FooStruct
49 unmodified lines
226 `{"foo": "bar", "hello": "world"}`, `{"num": 2}`)227}228229func TestBindingForm(t *testing.T) {230 testFormBinding(t, "POST",230 testFormBinding(t, http.MethodPost,231 "/", "/",232 "foo=bar&bar=foo", "bar2=foo")233}234235func TestBindingForm2(t *testing.T) {236 testFormBinding(t, "GET",236 testFormBinding(t, http.MethodGet,237 "/?foo=bar&bar=foo", "/?bar2=foo",238 "", "")239}240241func TestBindingFormEmbeddedStruct(t *testing.T) {242 testFormBindingEmbeddedStruct(t, "POST",242 testFormBindingEmbeddedStruct(t, http.MethodPost,243 "/", "/",244 "page=1&size=2&appkey=test-appkey", "bar2=foo")245}246247func TestBindingFormEmbeddedStruct2(t *testing.T) {248 testFormBindingEmbeddedStruct(t, "GET",248 testFormBindingEmbeddedStruct(t, http.MethodGet,249 "/?page=1&size=2&appkey=test-appkey", "/?bar2=foo",250 "", "")251}252253func TestBindingFormDefaultValue(t *testing.T) {254 testFormBindingDefaultValue(t, "POST",254 testFormBindingDefaultValue(t, http.MethodPost,255 "/", "/",256 "foo=bar", "bar2=foo")257}258259func TestBindingFormDefaultValue2(t *testing.T) {260 testFormBindingDefaultValue(t, "GET",260 testFormBindingDefaultValue(t, http.MethodGet,261 "/?foo=bar", "/?bar2=foo",262 "", "")263}264265func TestBindingFormForTime(t *testing.T) {266 testFormBindingForTime(t, "POST",266 testFormBindingForTime(t, http.MethodPost,267 "/", "/",268 "time_foo=2017-11-15&time_bar=&createTime=1562400033000000123&unixTime=1562400033", "bar2=foo")269 testFormBindingForTimeNotUnixFormat(t, "POST",269 testFormBindingForTimeNotUnixFormat(t, http.MethodPost,270 "/", "/",271 "time_foo=2017-11-15&createTime=bad&unixTime=bad", "bar2=foo")272 testFormBindingForTimeNotFormat(t, "POST",272 testFormBindingForTimeNotFormat(t, http.MethodPost,273 "/", "/",274 "time_foo=2017-11-15", "bar2=foo")275 testFormBindingForTimeFailFormat(t, "POST",275 testFormBindingForTimeFailFormat(t, http.MethodPost,276 "/", "/",277 "time_foo=2017-11-15", "bar2=foo")278 testFormBindingForTimeFailLocation(t, "POST",278 testFormBindingForTimeFailLocation(t, http.MethodPost,279 "/", "/",280 "time_foo=2017-11-15", "bar2=foo")281}282283func TestBindingFormForTime2(t *testing.T) {284 testFormBindingForTime(t, "GET",284 testFormBindingForTime(t, http.MethodGet,285 "/?time_foo=2017-11-15&time_bar=&createTime=1562400033000000123&unixTime=1562400033", "/?bar2=foo",286 "", "")287 testFormBindingForTimeNotUnixFormat(t, "POST",287 testFormBindingForTimeNotUnixFormat(t, http.MethodPost,288 "/", "/",289 "time_foo=2017-11-15&createTime=bad&unixTime=bad", "bar2=foo")290 testFormBindingForTimeNotFormat(t, "GET",290 testFormBindingForTimeNotFormat(t, http.MethodGet,291 "/?time_foo=2017-11-15", "/?bar2=foo",292 "", "")293 testFormBindingForTimeFailFormat(t, "GET",293 testFormBindingForTimeFailFormat(t, http.MethodGet,294 "/?time_foo=2017-11-15", "/?bar2=foo",295 "", "")296 testFormBindingForTimeFailLocation(t, "GET",296 testFormBindingForTimeFailLocation(t, http.MethodGet,297 "/?time_foo=2017-11-15", "/?bar2=foo",298 "", "")299}300301func TestFormBindingIgnoreField(t *testing.T) {302 testFormBindingIgnoreField(t, "POST",302 testFormBindingIgnoreField(t, http.MethodPost,303 "/", "/",304 "-=bar", "")305}306307func TestBindingFormInvalidName(t *testing.T) {308 testFormBindingInvalidName(t, "POST",308 testFormBindingInvalidName(t, http.MethodPost,309 "/", "/",310 "test_name=bar", "bar2=foo")311}312313func TestBindingFormInvalidName2(t *testing.T) {314 testFormBindingInvalidName2(t, "POST",314 testFormBindingInvalidName2(t, http.MethodPost,315 "/", "/",316 "map_foo=bar", "bar2=foo")317}318319func TestBindingFormForType(t *testing.T) {320 testFormBindingForType(t, "POST",320 testFormBindingForType(t, http.MethodPost,321 "/", "/",322 "map_foo={\"bar\":123}", "map_foo=1", "Map")323324 testFormBindingForType(t, "POST",324 testFormBindingForType(t, http.MethodPost,325 "/", "/",326 "slice_foo=1&slice_foo=2", "bar2=1&bar2=2", "Slice")327328 testFormBindingForType(t, "GET",328 testFormBindingForType(t, http.MethodGet,329 "/?slice_foo=1&slice_foo=2", "/?bar2=1&bar2=2",330 "", "", "Slice")331332 testFormBindingForType(t, "POST",332 testFormBindingForType(t, http.MethodPost,333 "/", "/",334 "slice_map_foo=1&slice_map_foo=2", "bar2=1&bar2=2", "SliceMap")335336 testFormBindingForType(t, "GET",336 testFormBindingForType(t, http.MethodGet,337 "/?slice_map_foo=1&slice_map_foo=2", "/?bar2=1&bar2=2",338 "", "", "SliceMap")339340 testFormBindingForType(t, "POST",340 testFormBindingForType(t, http.MethodPost,341 "/", "/",342 "ptr_bar=test", "bar2=test", "Ptr")343344 testFormBindingForType(t, "GET",344 testFormBindingForType(t, http.MethodGet,345 "/?ptr_bar=test", "/?bar2=test",346 "", "", "Ptr")347348 testFormBindingForType(t, "POST",348 testFormBindingForType(t, http.MethodPost,349 "/", "/",350 "idx=123", "id1=1", "Struct")351352 testFormBindingForType(t, "GET",352 testFormBindingForType(t, http.MethodGet,353 "/?idx=123", "/?id1=1",354 "", "", "Struct")355356 testFormBindingForType(t, "POST",356 testFormBindingForType(t, http.MethodPost,357 "/", "/",358 "name=thinkerou", "name1=ou", "StructPointer")359360 testFormBindingForType(t, "GET",360 testFormBindingForType(t, http.MethodGet,361 "/?name=thinkerou", "/?name1=ou",362 "", "", "StructPointer")363}364
8 unmodified lines
373}374375func TestBindingFormStringSliceMap(t *testing.T) {376 obj := make(map[string][]string)377 req := requestWithBody("POST", "/", "foo=something&foo=bar&hello=world")377 req := requestWithBody(http.MethodPost, "/", "foo=something&foo=bar&hello=world")378 req.Header.Add("Content-Type", MIMEPOSTForm)379 err := Form.Bind(req, &obj)380 require.NoError(t, err)381 assert.NotNil(t, obj)
4 unmodified lines
386 }387 assert.True(t, reflect.DeepEqual(obj, target))388389 objInvalid := make(map[string][]int)390 req = requestWithBody("POST", "/", "foo=something&foo=bar&hello=world")390 req = requestWithBody(http.MethodPost, "/", "foo=something&foo=bar&hello=world")391 req.Header.Add("Content-Type", MIMEPOSTForm)392 err = Form.Bind(req, &objInvalid)393 require.Error(t, err)394}395396func TestBindingQuery(t *testing.T) {397 testQueryBinding(t, "POST",397 testQueryBinding(t, http.MethodPost,398 "/?foo=bar&bar=foo", "/",399 "foo=unused", "bar2=foo")400}401402func TestBindingQuery2(t *testing.T) {403 testQueryBinding(t, "GET",403 testQueryBinding(t, http.MethodGet,404 "/?foo=bar&bar=foo", "/?bar2=foo",405 "foo=unused", "")406}407408func TestBindingQueryFail(t *testing.T) {409 testQueryBindingFail(t, "POST",409 testQueryBindingFail(t, http.MethodPost,410 "/?map_foo=", "/",411 "map_foo=unused", "bar2=foo")412}413414func TestBindingQueryFail2(t *testing.T) {415 testQueryBindingFail(t, "GET",415 testQueryBindingFail(t, http.MethodGet,416 "/?map_foo=", "/?bar2=foo",417 "map_foo=unused", "")418}419420func TestBindingQueryBoolFail(t *testing.T) {421 testQueryBindingBoolFail(t, "GET",421 testQueryBindingBoolFail(t, http.MethodGet,422 "/?bool_foo=fasl", "/?bar2=foo",423 "bool_foo=unused", "")424}425426func TestBindingQueryStringMap(t *testing.T) {427 b := Query428429 obj := make(map[string]string)430 req := requestWithBody("GET", "/?foo=bar&hello=world", "")430 req := requestWithBody(http.MethodGet, "/?foo=bar&hello=world", "")431 err := b.Bind(req, &obj)432 require.NoError(t, err)433 assert.NotNil(t, obj)434 assert.Len(t, obj, 2)435 assert.Equal(t, "bar", obj["foo"])436 assert.Equal(t, "world", obj["hello"])437438 obj = make(map[string]string)439 req = requestWithBody("GET", "/?foo=bar&foo=2&hello=world", "") // should pick last439 req = requestWithBody(http.MethodGet, "/?foo=bar&foo=2&hello=world", "") // should pick last440 err = b.Bind(req, &obj)441 require.NoError(t, err)442 assert.NotNil(t, obj)443 assert.Len(t, obj, 2)
50 unmodified lines
494 `foo:\nbar`, `bar: foo`)495}496497func createFormPostRequest(t *testing.T) *http.Request {498 req, err := http.NewRequest("POST", "/?foo=getfoo&bar=getbar", bytes.NewBufferString("foo=bar&bar=foo"))498 req, err := http.NewRequest(http.MethodPost, "/?foo=getfoo&bar=getbar", bytes.NewBufferString("foo=bar&bar=foo"))499 require.NoError(t, err)500 req.Header.Set("Content-Type", MIMEPOSTForm)501 return req502}503504func createDefaultFormPostRequest(t *testing.T) *http.Request {505 req, err := http.NewRequest("POST", "/?foo=getfoo&bar=getbar", bytes.NewBufferString("foo=bar"))505 req, err := http.NewRequest(http.MethodPost, "/?foo=getfoo&bar=getbar", bytes.NewBufferString("foo=bar"))506 require.NoError(t, err)507 req.Header.Set("Content-Type", MIMEPOSTForm)508 return req509}510511func createFormPostRequestForMap(t *testing.T) *http.Request {512 req, err := http.NewRequest("POST", "/?map_foo=getfoo", bytes.NewBufferString("map_foo={\"bar\":123}"))512 req, err := http.NewRequest(http.MethodPost, "/?map_foo=getfoo", bytes.NewBufferString("map_foo={\"bar\":123}"))513 require.NoError(t, err)514 req.Header.Set("Content-Type", MIMEPOSTForm)515 return req516}517518func createFormPostRequestForMapFail(t *testing.T) *http.Request {519 req, err := http.NewRequest("POST", "/?map_foo=getfoo", bytes.NewBufferString("map_foo=hello"))519 req, err := http.NewRequest(http.MethodPost, "/?map_foo=getfoo", bytes.NewBufferString("map_foo=hello"))520 require.NoError(t, err)521 req.Header.Set("Content-Type", MIMEPOSTForm)522 return req523}
15 unmodified lines
539 require.NoError(t, err1)540 _, err = io.Copy(fw, f)541 require.NoError(t, err)542543 req, err2 := http.NewRequest("POST", "/?foo=getfoo&bar=getbar", body)543 req, err2 := http.NewRequest(http.MethodPost, "/?foo=getfoo&bar=getbar", body)544 require.NoError(t, err2)545 req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)546547 return req
16 unmodified lines
564 require.NoError(t, err1)565 _, err = io.Copy(fw, f)566 require.NoError(t, err)567568 req, err2 := http.NewRequest("POST", "/?foo=getfoo&bar=getbar", body)568 req, err2 := http.NewRequest(http.MethodPost, "/?foo=getfoo&bar=getbar", body)569 require.NoError(t, err2)570 req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)571572 return req
7 unmodified lines
580581 require.NoError(t, mw.SetBoundary(boundary))582 require.NoError(t, mw.WriteField("foo", "bar"))583 require.NoError(t, mw.WriteField("bar", "foo"))584 req, err := http.NewRequest("POST", "/?foo=getfoo&bar=getbar", body)584 req, err := http.NewRequest(http.MethodPost, "/?foo=getfoo&bar=getbar", body)585 require.NoError(t, err)586 req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)587 return req588}
5 unmodified lines
594 defer mw.Close()595596 require.NoError(t, mw.SetBoundary(boundary))597 require.NoError(t, mw.WriteField("map_foo", "{\"bar\":123, \"name\":\"thinkerou\", \"pai\": 3.14}"))598 req, err := http.NewRequest("POST", "/?map_foo=getfoo", body)598 req, err := http.NewRequest(http.MethodPost, "/?map_foo=getfoo", body)599 require.NoError(t, err)600 req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)601 return req602}
5 unmodified lines
608 defer mw.Close()609610 require.NoError(t, mw.SetBoundary(boundary))611 require.NoError(t, mw.WriteField("map_foo", "3.14"))612 req, err := http.NewRequest("POST", "/?map_foo=getfoo", body)612 req, err := http.NewRequest(http.MethodPost, "/?map_foo=getfoo", body)613 require.NoError(t, err)614 req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)615 return req616}
113 unmodified lines
730}731732func TestValidationFails(t *testing.T) {733 var obj FooStruct734 req := requestWithBody("POST", "/", `{"bar": "foo"}`)734 req := requestWithBody(http.MethodPost, "/", `{"bar": "foo"}`)735 err := JSON.Bind(req, &obj)736 require.Error(t, err)737}738
2 unmodified lines
741 Validator = nil742 defer func() { Validator = backup }()743744 var obj FooStruct745 req := requestWithBody("POST", "/", `{"bar": "foo"}`)745 req := requestWithBody(http.MethodPost, "/", `{"bar": "foo"}`)746 err := JSON.Bind(req, &obj)747 require.NoError(t, err)748}749
2 unmodified lines
752 Hoge *int `json:"hoge" binding:"required"`753 }754755 var obj HogeStruct756 req := requestWithBody("POST", "/", `{"hoge": 0}`)756 req := requestWithBody(http.MethodPost, "/", `{"hoge": 0}`)757 err := JSON.Bind(req, &obj)758 require.NoError(t, err)759}760
2 unmodified lines
763 Hoge *int `json:"foo" binding:"required"`764 }765766 var obj HogeStruct767 req := requestWithBody("POST", "/", `{"boen": 0}`)767 req := requestWithBody(http.MethodPost, "/", `{"boen": 0}`)768 err := JSON.Bind(req, &obj)769 require.Error(t, err)770}771
5 unmodified lines
777 Limit int `header:"limit"`778 }779780 var theader tHeader781 req := requestWithBody("GET", "/", "")781 req := requestWithBody(http.MethodGet, "/", "")782 req.Header.Add("limit", "1000")783 require.NoError(t, h.Bind(req, &theader))784 assert.Equal(t, 1000, theader.Limit)785786 req = requestWithBody("GET", "/", "")786 req = requestWithBody(http.MethodGet, "/", "")787 req.Header.Add("fail", `{fail:fail}`)788789 type failStruct struct {790 Fail map[string]any `header:"fail"`
51 unmodified lines
842 assert.Equal(t, "form", b.Name())843844 obj := QueryTest{}845 req := requestWithBody(method, path, body)846 if method == "POST" {846 if method == http.MethodPost {847 req.Header.Add("Content-Type", MIMEPOSTForm)848 }849 err := b.Bind(req, &obj)850 require.NoError(t, err)
7 unmodified lines
858 assert.Equal(t, "form", b.Name())859860 obj := FooBarStruct{}861 req := requestWithBody(method, path, body)862 if method == "POST" {862 if method == http.MethodPost {863 req.Header.Add("Content-Type", MIMEPOSTForm)864 }865 err := b.Bind(req, &obj)866 require.NoError(t, err)
11 unmodified lines
878 assert.Equal(t, "form", b.Name())879880 obj := FooDefaultBarStruct{}881 req := requestWithBody(method, path, body)882 if method == "POST" {882 if method == http.MethodPost {883 req.Header.Add("Content-Type", MIMEPOSTForm)884 }885 err := b.Bind(req, &obj)886 require.NoError(t, err)
10 unmodified lines
897 b := Form898 assert.Equal(t, "form", b.Name())899900 obj := FooBarStruct{}901 req, _ := http.NewRequest("POST", "/", nil)901 req, _ := http.NewRequest(http.MethodPost, "/", nil)902 err := b.Bind(req, &obj)903 require.Error(t, err)904}905906func TestFormBindingMultipartFail(t *testing.T) {907 obj := FooBarStruct{}908 req, err := http.NewRequest("POST", "/", strings.NewReader("foo=bar"))908 req, err := http.NewRequest(http.MethodPost, "/", strings.NewReader("foo=bar"))909 require.NoError(t, err)910 req.Header.Set("Content-Type", MIMEMultipartPOSTForm+";boundary=testboundary")911 _, err = req.MultipartReader()912 require.NoError(t, err)
5 unmodified lines
918 b := FormPost919 assert.Equal(t, "form-urlencoded", b.Name())920921 obj := FooBarStruct{}922 req, _ := http.NewRequest("POST", "/", nil)922 req, _ := http.NewRequest(http.MethodPost, "/", nil)923 err := b.Bind(req, &obj)924 require.Error(t, err)925}926
1 unmodified line
928 b := FormMultipart929 assert.Equal(t, "multipart/form-data", b.Name())930931 obj := FooBarStruct{}932 req, _ := http.NewRequest("POST", "/", nil)932 req, _ := http.NewRequest(http.MethodPost, "/", nil)933 err := b.Bind(req, &obj)934 require.Error(t, err)935}936
2 unmodified lines
939 assert.Equal(t, "form", b.Name())940941 obj := FooBarStructForTimeType{}942 req := requestWithBody(method, path, body)943 if method == "POST" {943 if method == http.MethodPost {944 req.Header.Add("Content-Type", MIMEPOSTForm)945 }946 err := b.Bind(req, &obj)947
16 unmodified lines
964 assert.Equal(t, "form", b.Name())965966 obj := FooStructForTimeTypeNotUnixFormat{}967 req := requestWithBody(method, path, body)968 if method == "POST" {968 if method == http.MethodPost {969 req.Header.Add("Content-Type", MIMEPOSTForm)970 }971 err := b.Bind(req, &obj)972 require.Error(t, err)
9 unmodified lines
982 assert.Equal(t, "form", b.Name())983984 obj := FooStructForTimeTypeNotFormat{}985 req := requestWithBody(method, path, body)986 if method == "POST" {986 if method == http.MethodPost {987 req.Header.Add("Content-Type", MIMEPOSTForm)988 }989 err := b.Bind(req, &obj)990 require.Error(t, err)
9 unmodified lines
1000 assert.Equal(t, "form", b.Name())10011002 obj := FooStructForTimeTypeFailFormat{}1003 req := requestWithBody(method, path, body)1004 if method == "POST" {1004 if method == http.MethodPost {1005 req.Header.Add("Content-Type", MIMEPOSTForm)1006 }1007 err := b.Bind(req, &obj)1008 require.Error(t, err)
9 unmodified lines
1018 assert.Equal(t, "form", b.Name())10191020 obj := FooStructForTimeTypeFailLocation{}1021 req := requestWithBody(method, path, body)1022 if method == "POST" {1022 if method == http.MethodPost {1023 req.Header.Add("Content-Type", MIMEPOSTForm)1024 }1025 err := b.Bind(req, &obj)1026 require.Error(t, err)
9 unmodified lines
1036 assert.Equal(t, "form", b.Name())10371038 obj := FooStructForIgnoreFormTag{}1039 req := requestWithBody(method, path, body)1040 if method == "POST" {1040 if method == http.MethodPost {1041 req.Header.Add("Content-Type", MIMEPOSTForm)1042 }1043 err := b.Bind(req, &obj)1044 require.NoError(t, err)
6 unmodified lines
1051 assert.Equal(t, "form", b.Name())10521053 obj := InvalidNameType{}1054 req := requestWithBody(method, path, body)1055 if method == "POST" {1055 if method == http.MethodPost {1056 req.Header.Add("Content-Type", MIMEPOSTForm)1057 }1058 err := b.Bind(req, &obj)1059 require.NoError(t, err)
10 unmodified lines
1070 assert.Equal(t, "form", b.Name())10711072 obj := InvalidNameMapType{}1073 req := requestWithBody(method, path, body)1074 if method == "POST" {1074 if method == http.MethodPost {1075 req.Header.Add("Content-Type", MIMEPOSTForm)1076 }1077 err := b.Bind(req, &obj)1078 require.Error(t, err)
8 unmodified lines
1087 b := Form1088 assert.Equal(t, "form", b.Name())10891090 req := requestWithBody(method, path, body)1091 if method == "POST" {1091 if method == http.MethodPost {1092 req.Header.Add("Content-Type", MIMEPOSTForm)1093 }1094 switch typ {1095 case "Slice":
62 unmodified lines
1158 assert.Equal(t, "query", b.Name())11591160 obj := FooBarStruct{}1161 req := requestWithBody(method, path, body)1162 if method == "POST" {1162 if method == http.MethodPost {1163 req.Header.Add("Content-Type", MIMEPOSTForm)1164 }1165 err := b.Bind(req, &obj)1166 require.NoError(t, err)
6 unmodified lines
1173 assert.Equal(t, "query", b.Name())11741175 obj := FooStructForMapType{}1176 req := requestWithBody(method, path, body)1177 if method == "POST" {1177 if method == http.MethodPost {1178 req.Header.Add("Content-Type", MIMEPOSTForm)1179 }1180 err := b.Bind(req, &obj)1181 require.Error(t, err)
4 unmodified lines
1186 assert.Equal(t, "query", b.Name())11871188 obj := FooStructForBoolType{}1189 req := requestWithBody(method, path, body)1190 if method == "POST" {1190 if method == http.MethodPost {1191 req.Header.Add("Content-Type", MIMEPOSTForm)1192 }1193 err := b.Bind(req, &obj)1194 require.Error(t, err)
2 unmodified lines
1197func testBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) {1198 assert.Equal(t, name, b.Name())11991200 obj := FooStruct{}1201 req := requestWithBody("POST", path, body)1201 req := requestWithBody(http.MethodPost, path, body)1202 err := b.Bind(req, &obj)1203 require.NoError(t, err)1204 assert.Equal(t, "bar", obj.Foo)12051206 obj = FooStruct{}1207 req = requestWithBody("POST", badPath, badBody)1207 req = requestWithBody(http.MethodPost, badPath, badBody)1208 err = JSON.Bind(req, &obj)1209 require.Error(t, err)1210}12111212func testBodyBindingSlice(t *testing.T, b Binding, name, path, badPath, body, badBody string) {1213 assert.Equal(t, name, b.Name())12141215 var obj1 []FooStruct1216 req := requestWithBody("POST", path, body)1216 req := requestWithBody(http.MethodPost, path, body)1217 err := b.Bind(req, &obj1)1218 require.NoError(t, err)12191220 var obj2 []FooStruct1221 req = requestWithBody("POST", badPath, badBody)1221 req = requestWithBody(http.MethodPost, badPath, badBody)1222 err = JSON.Bind(req, &obj2)1223 require.Error(t, err)1224}12251226func testBodyBindingStringMap(t *testing.T, b Binding, path, badPath, body, badBody string) {1227 obj := make(map[string]string)1228 req := requestWithBody("POST", path, body)1228 req := requestWithBody(http.MethodPost, path, body)1229 if b.Name() == "form" {1230 req.Header.Add("Content-Type", MIMEPOSTForm)1231 }1232 err := b.Bind(req, &obj)
4 unmodified lines
1237 assert.Equal(t, "world", obj["hello"])12381239 if badPath != "" && badBody != "" {1240 obj = make(map[string]string)1241 req = requestWithBody("POST", badPath, badBody)1241 req = requestWithBody(http.MethodPost, badPath, badBody)1242 err = b.Bind(req, &obj)1243 require.Error(t, err)1244 }12451246 objInt := make(map[string]int)1247 req = requestWithBody("POST", path, body)1247 req = requestWithBody(http.MethodPost, path, body)1248 err = b.Bind(req, &objInt)1249 require.Error(t, err)1250}12511252func testBodyBindingUseNumber(t *testing.T, b Binding, name, path, badPath, body, badBody string) {1253 assert.Equal(t, name, b.Name())12541255 obj := FooStructUseNumber{}1256 req := requestWithBody("POST", path, body)1256 req := requestWithBody(http.MethodPost, path, body)1257 EnableDecoderUseNumber = true1258 err := b.Bind(req, &obj)1259 require.NoError(t, err)1260 // we hope it is int64(123)
1 unmodified line
1262 require.NoError(t, e)1263 assert.Equal(t, int64(123), v)12641265 obj = FooStructUseNumber{}1266 req = requestWithBody("POST", badPath, badBody)1266 req = requestWithBody(http.MethodPost, badPath, badBody)1267 err = JSON.Bind(req, &obj)1268 require.Error(t, err)1269}12701271func testBodyBindingUseNumber2(t *testing.T, b Binding, name, path, badPath, body, badBody string) {1272 assert.Equal(t, name, b.Name())12731274 obj := FooStructUseNumber{}1275 req := requestWithBody("POST", path, body)1275 req := requestWithBody(http.MethodPost, path, body)1276 EnableDecoderUseNumber = false1277 err := b.Bind(req, &obj)1278 require.NoError(t, err)1279 // it will return float64(123) if not use EnableDecoderUseNumber1280 // maybe it is not hoped1281 assert.InDelta(t, float64(123), obj.Foo, 0.01)12821283 obj = FooStructUseNumber{}1284 req = requestWithBody("POST", badPath, badBody)1284 req = requestWithBody(http.MethodPost, badPath, badBody)1285 err = JSON.Bind(req, &obj)1286 require.Error(t, err)1287}1288
3 unmodified lines
1292 EnableDecoderDisallowUnknownFields = false1293 }()12941295 obj := FooStructDisallowUnknownFields{}1296 req := requestWithBody("POST", path, body)1296 req := requestWithBody(http.MethodPost, path, body)1297 err := b.Bind(req, &obj)1298 require.NoError(t, err)1299 assert.Equal(t, "bar", obj.Foo)13001301 obj = FooStructDisallowUnknownFields{}1302 req = requestWithBody("POST", badPath, badBody)1302 req = requestWithBody(http.MethodPost, badPath, badBody)1303 err = JSON.Bind(req, &obj)1304 require.Error(t, err)1305 assert.Contains(t, err.Error(), "what")1306}
1 unmodified line
1308func testBodyBindingFail(t *testing.T, b Binding, name, path, badPath, body, badBody string) {1309 assert.Equal(t, name, b.Name())13101311 obj := FooStruct{}1312 req := requestWithBody("POST", path, body)1312 req := requestWithBody(http.MethodPost, path, body)1313 err := b.Bind(req, &obj)1314 require.Error(t, err)1315 assert.Equal(t, "", obj.Foo)13161317 obj = FooStruct{}1318 req = requestWithBody("POST", badPath, badBody)1318 req = requestWithBody(http.MethodPost, badPath, badBody)1319 err = JSON.Bind(req, &obj)1320 require.Error(t, err)1321}13221323func testProtoBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) {1324 assert.Equal(t, name, b.Name())13251326 obj := protoexample.Test{}1327 req := requestWithBody("POST", path, body)1327 req := requestWithBody(http.MethodPost, path, body)1328 req.Header.Add("Content-Type", MIMEPROTOBUF)1329 err := b.Bind(req, &obj)1330 require.NoError(t, err)1331 assert.Equal(t, "yes", *obj.Label)13321333 obj = protoexample.Test{}1334 req = requestWithBody("POST", badPath, badBody)1334 req = requestWithBody(http.MethodPost, badPath, badBody)1335 req.Header.Add("Content-Type", MIMEPROTOBUF)1336 err = ProtoBuf.Bind(req, &obj)1337 require.Error(t, err)1338}
18 unmodified lines
1357 p := Plain1358 assert.Equal(t, "plain", p.Name())13591360 var s string1361 req := requestWithBody("POST", "/", "test string")1361 req := requestWithBody(http.MethodPost, "/", "test string")1362 require.NoError(t, p.Bind(req, &s))1363 assert.Equal(t, "test string", s)13641365 var bs []byte1366 req = requestWithBody("POST", "/", "test []byte")1366 req = requestWithBody(http.MethodPost, "/", "test []byte")1367 require.NoError(t, p.Bind(req, &bs))1368 assert.Equal(t, bs, []byte("test []byte"))13691370 var i int1371 req = requestWithBody("POST", "/", "test fail")1371 req = requestWithBody(http.MethodPost, "/", "test fail")1372 require.Error(t, p.Bind(req, &i))13731374 req = requestWithBody("POST", "/", "")1374 req = requestWithBody(http.MethodPost, "/", "")1375 req.Body = &failRead{}1376 require.Error(t, p.Bind(req, &s))13771378 req = requestWithBody("POST", "/", "")1378 req = requestWithBody(http.MethodPost, "/", "")1379 require.NoError(t, p.Bind(req, nil))13801381 var ptr *string1382 req = requestWithBody("POST", "/", "")1382 req = requestWithBody(http.MethodPost, "/", "")1383 require.NoError(t, p.Bind(req, ptr))1384}13851386func testProtoBodyBindingFail(t *testing.T, b Binding, name, path, badPath, body, badBody string) {1387 assert.Equal(t, name, b.Name())13881389 obj := protoexample.Test{}1390 req := requestWithBody("POST", path, body)1390 req := requestWithBody(http.MethodPost, path, body)13911392 req.Body = io.NopCloser(&hook{})1393 req.Header.Add("Content-Type", MIMEPROTOBUF)1394 err := b.Bind(req, &obj)
6 unmodified lines
1401 require.Error(t, err)1402 assert.Equal(t, "obj is not ProtoMessage", err.Error())14031404 obj = protoexample.Test{}1405 req = requestWithBody("POST", badPath, badBody)1405 req = requestWithBody(http.MethodPost, badPath, badBody)1406 req.Header.Add("Content-Type", MIMEPROTOBUF)1407 err = ProtoBuf.Bind(req, &obj)1408 require.Error(t, err)1409}
5 unmodified lines
modified:binding/multipart_form_mapping_test.go+1 added-1 removed
114 unmodified lines
115 }116 err := mw.Close()117 require.NoError(t, err)118119 req, err := http.NewRequest("POST", "/", &body)119 req, err := http.NewRequest(http.MethodPost, "/", &body)120 require.NoError(t, err)121122 req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+mw.Boundary())123 return req
16 unmodified lines
modified:render/render_test.go+1 added-1 removed
367 unmodified lines
368 assert.Equal(t, "application/xml; charset=utf-8", w.Header().Get("Content-Type"))369}370371func TestRenderRedirect(t *testing.T) {372 req, err := http.NewRequest("GET", "/test-redirect", nil)372 req, err := http.NewRequest(http.MethodGet, "/test-redirect", nil)373 require.NoError(t, err)374375 data1 := Redirect{376 Code: http.StatusMovedPermanently,
218 unmodified lines
modified:.golangci.yml+1 added
modified:auth_test.go+5 added-5 removed
88 unmodified lines
89 c.String(http.StatusOK, c.MustGet(AuthUserKey).(string))90 })9192 w := httptest.NewRecorder()93 req, _ := http.NewRequest("GET", "/login", nil)93 req, _ := http.NewRequest(http.MethodGet, "/login", nil)94 req.Header.Set("Authorization", authorizationHeader("admin", "password"))95 router.ServeHTTP(w, req)9697 assert.Equal(t, http.StatusOK, w.Code)
10 unmodified lines
108 c.String(http.StatusOK, c.MustGet(AuthUserKey).(string))109 })110111 w := httptest.NewRecorder()112 req, _ := http.NewRequest("GET", "/login", nil)112 req, _ := http.NewRequest(http.MethodGet, "/login", nil)113 req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password")))114 router.ServeHTTP(w, req)115116 assert.False(t, called)
11 unmodified lines
128 c.String(http.StatusOK, c.MustGet(AuthUserKey).(string))129 })130131 w := httptest.NewRecorder()132 req, _ := http.NewRequest("GET", "/login", nil)132 req, _ := http.NewRequest(http.MethodGet, "/login", nil)133 req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password")))134 router.ServeHTTP(w, req)135136 assert.False(t, called)
9 unmodified lines
146 c.String(http.StatusOK, c.MustGet(AuthProxyUserKey).(string))147 })148149 w := httptest.NewRecorder()150 req, _ := http.NewRequest("GET", "/test", nil)150 req, _ := http.NewRequest(http.MethodGet, "/test", nil)151 req.Header.Set("Proxy-Authorization", authorizationHeader("admin", "password"))152 router.ServeHTTP(w, req)153154 assert.Equal(t, http.StatusOK, w.Code)
10 unmodified lines
165 c.String(http.StatusOK, c.MustGet(AuthProxyUserKey).(string))166 })167168 w := httptest.NewRecorder()169 req, _ := http.NewRequest("GET", "/test", nil)169 req, _ := http.NewRequest(http.MethodGet, "/test", nil)170 req.Header.Set("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password")))171 router.ServeHTTP(w, req)172173 assert.False(t, called)
3 unmodified lines
modified:benchmarks_test.go+12 added-12 removed
12 unmodified lines
1314func BenchmarkOneRoute(B *testing.B) {15 router := New()16 router.GET("/ping", func(c *Context) {})17 runRequest(B, router, "GET", "/ping")17 runRequest(B, router, http.MethodGet, "/ping")18}1920func BenchmarkRecoveryMiddleware(B *testing.B) {21 router := New()22 router.Use(Recovery())23 router.GET("/", func(c *Context) {})24 runRequest(B, router, "GET", "/")24 runRequest(B, router, http.MethodGet, "/")25}2627func BenchmarkLoggerMiddleware(B *testing.B) {28 router := New()29 router.Use(LoggerWithWriter(newMockWriter()))30 router.GET("/", func(c *Context) {})31 runRequest(B, router, "GET", "/")31 runRequest(B, router, http.MethodGet, "/")32}3334func BenchmarkManyHandlers(B *testing.B) {35 router := New()36 router.Use(Recovery(), LoggerWithWriter(newMockWriter()))37 router.Use(func(c *Context) {})38 router.Use(func(c *Context) {})39 router.GET("/ping", func(c *Context) {})40 runRequest(B, router, "GET", "/ping")40 runRequest(B, router, http.MethodGet, "/ping")41}4243func Benchmark5Params(B *testing.B) {44 DefaultWriter = os.Stdout45 router := New()46 router.Use(func(c *Context) {})47 router.GET("/param/:param1/:params2/:param3/:param4/:param5", func(c *Context) {})48 runRequest(B, router, "GET", "/param/path/to/parameter/john/12345")48 runRequest(B, router, http.MethodGet, "/param/path/to/parameter/john/12345")49}5051func BenchmarkOneRouteJSON(B *testing.B) {52 router := New()
2 unmodified lines
55 }{"ok"}56 router.GET("/json", func(c *Context) {57 c.JSON(http.StatusOK, data)58 })59 runRequest(B, router, "GET", "/json")59 runRequest(B, router, http.MethodGet, "/json")60}6162func BenchmarkOneRouteHTML(B *testing.B) {63 router := New()
3 unmodified lines
6768 router.GET("/html", func(c *Context) {69 c.HTML(http.StatusOK, "index", "hola")70 })71 runRequest(B, router, "GET", "/html")71 runRequest(B, router, http.MethodGet, "/html")72}7374func BenchmarkOneRouteSet(B *testing.B) {75 router := New()76 router.GET("/ping", func(c *Context) {77 c.Set("key", "value")78 })79 runRequest(B, router, "GET", "/ping")79 runRequest(B, router, http.MethodGet, "/ping")80}8182func BenchmarkOneRouteString(B *testing.B) {83 router := New()84 router.GET("/text", func(c *Context) {85 c.String(http.StatusOK, "this is a plain text")86 })87 runRequest(B, router, "GET", "/text")87 runRequest(B, router, http.MethodGet, "/text")88}8990func BenchmarkManyRoutesFist(B *testing.B) {91 router := New()92 router.Any("/ping", func(c *Context) {})93 runRequest(B, router, "GET", "/ping")93 runRequest(B, router, http.MethodGet, "/ping")94}9596func BenchmarkManyRoutesLast(B *testing.B) {97 router := New()
4 unmodified lines
102func Benchmark404(B *testing.B) {103 router := New()104 router.Any("/something", func(c *Context) {})105 router.NoRoute(func(c *Context) {})106 runRequest(B, router, "GET", "/ping")106 runRequest(B, router, http.MethodGet, "/ping")107}108109func Benchmark404Many(B *testing.B) {110 router := New()
6 unmodified lines
117 router.GET("/delete/:id", func(c *Context) {})118 router.GET("/user/:id/:mode", func(c *Context) {})119120 router.NoRoute(func(c *Context) {})121 runRequest(B, router, "GET", "/viewfake")121 runRequest(B, router, http.MethodGet, "/viewfake")122}123124type mockWriter struct {125 headers http.Header
35 unmodified lines
modified:context_test.go+77 added-77 removed
58 unmodified lines
59 must(mw.WriteField("time_utc", "31/12/2016 14:55"))60 must(mw.WriteField("time_location", "31/12/2016 14:55"))61 must(mw.WriteField("names[a]", "thinkerou"))62 must(mw.WriteField("names[b]", "tianou"))63 req, err := http.NewRequest("POST", "/", body)63 req, err := http.NewRequest(http.MethodPost, "/", body)64 must(err)65 req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)66 return req67}
12 unmodified lines
80 _, err = w.Write([]byte("test"))81 require.NoError(t, err)82 mw.Close()83 c, _ := CreateTestContext(httptest.NewRecorder())84 c.Request, _ = http.NewRequest("POST", "/", buf)84 c.Request, _ = http.NewRequest(http.MethodPost, "/", buf)85 c.Request.Header.Set("Content-Type", mw.FormDataContentType())86 f, err := c.FormFile("file")87 require.NoError(t, err)88 assert.Equal(t, "test", f.Filename)
5 unmodified lines
94 buf := new(bytes.Buffer)95 mw := multipart.NewWriter(buf)96 mw.Close()97 c, _ := CreateTestContext(httptest.NewRecorder())98 c.Request, _ = http.NewRequest("POST", "/", nil)98 c.Request, _ = http.NewRequest(http.MethodPost, "/", nil)99 c.Request.Header.Set("Content-Type", mw.FormDataContentType())100 c.engine.MaxMultipartMemory = 8 << 20101 f, err := c.FormFile("file")102 require.Error(t, err)
9 unmodified lines
112 _, err = w.Write([]byte("test"))113 require.NoError(t, err)114 mw.Close()115 c, _ := CreateTestContext(httptest.NewRecorder())116 c.Request, _ = http.NewRequest("POST", "/", buf)116 c.Request, _ = http.NewRequest(http.MethodPost, "/", buf)117 c.Request.Header.Set("Content-Type", mw.FormDataContentType())118 f, err := c.MultipartForm()119 require.NoError(t, err)120 assert.NotNil(t, f)
6 unmodified lines
127 mw := multipart.NewWriter(buf)128 mw.Close()129130 c, _ := CreateTestContext(httptest.NewRecorder())131 c.Request, _ = http.NewRequest("POST", "/", buf)131 c.Request, _ = http.NewRequest(http.MethodPost, "/", buf)132 c.Request.Header.Set("Content-Type", mw.FormDataContentType())133134 f := &multipart.FileHeader{135 Filename: "file",
9 unmodified lines
145 _, err = w.Write([]byte("test"))146 require.NoError(t, err)147 mw.Close()148 c, _ := CreateTestContext(httptest.NewRecorder())149 c.Request, _ = http.NewRequest("POST", "/", buf)149 c.Request, _ = http.NewRequest(http.MethodPost, "/", buf)150 c.Request.Header.Set("Content-Type", mw.FormDataContentType())151 f, err := c.FormFile("file")152 require.NoError(t, err)153 assert.Equal(t, "test", f.Filename)
326 unmodified lines
480481func TestContextCopy(t *testing.T) {482 c, _ := CreateTestContext(httptest.NewRecorder())483 c.index = 2484 c.Request, _ = http.NewRequest("POST", "/hola", nil)484 c.Request, _ = http.NewRequest(http.MethodPost, "/hola", nil)485 c.handlers = HandlersChain{func(c *Context) {}}486 c.Params = Params{Param{Key: "foo", Value: "bar"}}487 c.Set("foo", "bar")488 c.fullPath = "/hola"
48 unmodified lines
537}538539func TestContextQuery(t *testing.T) {540 c, _ := CreateTestContext(httptest.NewRecorder())541 c.Request, _ = http.NewRequest("GET", "http://example.com/?foo=bar&page=10&id=", nil)541 c.Request, _ = http.NewRequest(http.MethodGet, "http://example.com/?foo=bar&page=10&id=", nil)542543 value, ok := c.GetQuery("foo")544 assert.True(t, ok)545 assert.Equal(t, "bar", value)
84 unmodified lines
630631func TestContextQueryAndPostForm(t *testing.T) {632 c, _ := CreateTestContext(httptest.NewRecorder())633 body := bytes.NewBufferString("foo=bar&page=11&both=&foo=second")634 c.Request, _ = http.NewRequest("POST",634 c.Request, _ = http.NewRequest(http.MethodPost,635 "/?both=GET&id=main&id=omit&array[]=first&array[]=second&ids[a]=hi&ids[b]=3.14", body)636 c.Request.Header.Add("Content-Type", MIMEPOSTForm)637638 assert.Equal(t, "bar", c.DefaultPostForm("foo", "none"))
11 unmodified lines
650 assert.True(t, ok)651 assert.Empty(t, value)652 assert.Empty(t, c.PostForm("both"))653 assert.Empty(t, c.DefaultPostForm("both", "nothing"))654 assert.Equal(t, "GET", c.Query("both"), "GET")654 assert.Equal(t, http.MethodGet, c.Query("both"), http.MethodGet)655656 value, ok = c.GetQuery("id")657 assert.True(t, ok)658 assert.Equal(t, "main", value)
39 unmodified lines
698 assert.Empty(t, values)699700 values = c.QueryArray("both")701 assert.Len(t, values, 1)702 assert.Equal(t, "GET", values[0])702 assert.Equal(t, http.MethodGet, values[0])703704 dicts, ok := c.GetQueryMap("ids")705 assert.True(t, ok)706 assert.Equal(t, "hi", dicts["a"])
126 unmodified lines
833}834835func TestContextGetCookie(t *testing.T) {836 c, _ := CreateTestContext(httptest.NewRecorder())837 c.Request, _ = http.NewRequest("GET", "/get", nil)837 c.Request, _ = http.NewRequest(http.MethodGet, "/get", nil)838 c.Request.Header.Set("Cookie", "user=gin")839 cookie, _ := c.Cookie("user")840 assert.Equal(t, "gin", cookie)841
43 unmodified lines
885// and Content-Type is set to application/javascript886func TestContextRenderJSONP(t *testing.T) {887 w := httptest.NewRecorder()888 c, _ := CreateTestContext(w)889 c.Request, _ = http.NewRequest("GET", "http://example.com/?callback=x", nil)889 c.Request, _ = http.NewRequest(http.MethodGet, "http://example.com/?callback=x", nil)890891 c.JSONP(http.StatusCreated, H{"foo": "bar"})892893 assert.Equal(t, http.StatusCreated, w.Code)
5 unmodified lines
899// and Content-Type is set to application/json900func TestContextRenderJSONPWithoutCallback(t *testing.T) {901 w := httptest.NewRecorder()902 c, _ := CreateTestContext(w)903 c.Request, _ = http.NewRequest("GET", "http://example.com", nil)903 c.Request, _ = http.NewRequest(http.MethodGet, "http://example.com", nil)904905 c.JSONP(http.StatusCreated, H{"foo": "bar"})906907 assert.Equal(t, http.StatusCreated, w.Code)
134 unmodified lines
1042 w := httptest.NewRecorder()1043 c, router := CreateTestContext(w)10441045 // print debug warning log when Engine.trees > 01046 router.addRoute("GET", "/", HandlersChain{func(_ *Context) {}})1046 router.addRoute(http.MethodGet, "/", HandlersChain{func(_ *Context) {}})1047 assert.Len(t, router.trees, 1)10481049 templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))1050 re := captureOutput(t, func() {
147 unmodified lines
1198func TestContextRenderFile(t *testing.T) {1199 w := httptest.NewRecorder()1200 c, _ := CreateTestContext(w)12011202 c.Request, _ = http.NewRequest("GET", "/", nil)1202 c.Request, _ = http.NewRequest(http.MethodGet, "/", nil)1203 c.File("./gin.go")12041205 assert.Equal(t, http.StatusOK, w.Code)1206 assert.Contains(t, w.Body.String(), "func New(opts ...OptionFunc) *Engine {")
5 unmodified lines
1212func TestContextRenderFileFromFS(t *testing.T) {1213 w := httptest.NewRecorder()1214 c, _ := CreateTestContext(w)12151216 c.Request, _ = http.NewRequest("GET", "/some/path", nil)1216 c.Request, _ = http.NewRequest(http.MethodGet, "/some/path", nil)1217 c.FileFromFS("./gin.go", Dir(".", false))12181219 assert.Equal(t, http.StatusOK, w.Code)1220 assert.Contains(t, w.Body.String(), "func New(opts ...OptionFunc) *Engine {")
7 unmodified lines
1228 w := httptest.NewRecorder()1229 c, _ := CreateTestContext(w)1230 newFilename := "new_filename.go"12311232 c.Request, _ = http.NewRequest("GET", "/", nil)1232 c.Request, _ = http.NewRequest(http.MethodGet, "/", nil)1233 c.FileAttachment("./gin.go", newFilename)12341235 assert.Equal(t, 200, w.Code)1236 assert.Contains(t, w.Body.String(), "func New(opts ...OptionFunc) *Engine {")
5 unmodified lines
1242 c, _ := CreateTestContext(w)1243 maliciousFilename := "tampering_field.sh\"; \\\"; dummy=.go"1244 actualEscapedResponseFilename := "tampering_field.sh\\\"; \\\\\\\"; dummy=.go"12451246 c.Request, _ = http.NewRequest("GET", "/", nil)1246 c.Request, _ = http.NewRequest(http.MethodGet, "/", nil)1247 c.FileAttachment("./gin.go", maliciousFilename)12481249 assert.Equal(t, 200, w.Code)1250 assert.Contains(t, w.Body.String(), "func New(opts ...OptionFunc) *Engine {")
4 unmodified lines
1255 w := httptest.NewRecorder()1256 c, _ := CreateTestContext(w)1257 newFilename := "new🧡_filename.go"12581259 c.Request, _ = http.NewRequest("GET", "/", nil)1259 c.Request, _ = http.NewRequest(http.MethodGet, "/", nil)1260 c.FileAttachment("./gin.go", newFilename)12611262 assert.Equal(t, 200, w.Code)1263 assert.Contains(t, w.Body.String(), "func New(opts ...OptionFunc) *Engine {")
70 unmodified lines
1334func TestContextRenderRedirectWithRelativePath(t *testing.T) {1335 w := httptest.NewRecorder()1336 c, _ := CreateTestContext(w)13371338 c.Request, _ = http.NewRequest("POST", "http://example.com", nil)1338 c.Request, _ = http.NewRequest(http.MethodPost, "http://example.com", nil)1339 assert.Panics(t, func() { c.Redirect(299, "/new_path") })1340 assert.Panics(t, func() { c.Redirect(309, "/new_path") })13411342 c.Redirect(http.StatusMovedPermanently, "/path")
5 unmodified lines
1348func TestContextRenderRedirectWithAbsolutePath(t *testing.T) {1349 w := httptest.NewRecorder()1350 c, _ := CreateTestContext(w)13511352 c.Request, _ = http.NewRequest("POST", "http://example.com", nil)1352 c.Request, _ = http.NewRequest(http.MethodPost, "http://example.com", nil)1353 c.Redirect(http.StatusFound, "http://google.com")1354 c.Writer.WriteHeaderNow()13551356 assert.Equal(t, http.StatusFound, w.Code)
3 unmodified lines
1360func TestContextRenderRedirectWith201(t *testing.T) {1361 w := httptest.NewRecorder()1362 c, _ := CreateTestContext(w)13631364 c.Request, _ = http.NewRequest("POST", "http://example.com", nil)1364 c.Request, _ = http.NewRequest(http.MethodPost, "http://example.com", nil)1365 c.Redirect(http.StatusCreated, "/resource")1366 c.Writer.WriteHeaderNow()13671368 assert.Equal(t, http.StatusCreated, w.Code)
1 unmodified line
1370}13711372func TestContextRenderRedirectAll(t *testing.T) {1373 c, _ := CreateTestContext(httptest.NewRecorder())1374 c.Request, _ = http.NewRequest("POST", "http://example.com", nil)1374 c.Request, _ = http.NewRequest(http.MethodPost, "http://example.com", nil)1375 assert.Panics(t, func() { c.Redirect(http.StatusOK, "/resource") })1376 assert.Panics(t, func() { c.Redirect(http.StatusAccepted, "/resource") })1377 assert.Panics(t, func() { c.Redirect(299, "/resource") })1378 assert.Panics(t, func() { c.Redirect(309, "/resource") })
3 unmodified lines
13821383func TestContextNegotiationWithJSON(t *testing.T) {1384 w := httptest.NewRecorder()1385 c, _ := CreateTestContext(w)1386 c.Request, _ = http.NewRequest("POST", "", nil)1386 c.Request, _ = http.NewRequest(http.MethodPost, "", nil)13871388 c.Negotiate(http.StatusOK, Negotiate{1389 Offered: []string{MIMEJSON, MIMEXML, MIMEYAML, MIMEYAML2},1390 Data: H{"foo": "bar"},
6 unmodified lines
13971398func TestContextNegotiationWithXML(t *testing.T) {1399 w := httptest.NewRecorder()1400 c, _ := CreateTestContext(w)1401 c.Request, _ = http.NewRequest("POST", "", nil)1401 c.Request, _ = http.NewRequest(http.MethodPost, "", nil)14021403 c.Negotiate(http.StatusOK, Negotiate{1404 Offered: []string{MIMEXML, MIMEJSON, MIMEYAML, MIMEYAML2},1405 Data: H{"foo": "bar"},
6 unmodified lines
14121413func TestContextNegotiationWithYAML(t *testing.T) {1414 w := httptest.NewRecorder()1415 c, _ := CreateTestContext(w)1416 c.Request, _ = http.NewRequest("POST", "", nil)1416 c.Request, _ = http.NewRequest(http.MethodPost, "", nil)14171418 c.Negotiate(http.StatusOK, Negotiate{1419 Offered: []string{MIMEYAML, MIMEXML, MIMEJSON, MIMETOML, MIMEYAML2},1420 Data: H{"foo": "bar"},
6 unmodified lines
14271428func TestContextNegotiationWithTOML(t *testing.T) {1429 w := httptest.NewRecorder()1430 c, _ := CreateTestContext(w)1431 c.Request, _ = http.NewRequest("POST", "", nil)1431 c.Request, _ = http.NewRequest(http.MethodPost, "", nil)14321433 c.Negotiate(http.StatusOK, Negotiate{1434 Offered: []string{MIMETOML, MIMEXML, MIMEJSON, MIMEYAML, MIMEYAML2},1435 Data: H{"foo": "bar"},
6 unmodified lines
14421443func TestContextNegotiationWithHTML(t *testing.T) {1444 w := httptest.NewRecorder()1445 c, router := CreateTestContext(w)1446 c.Request, _ = http.NewRequest("POST", "", nil)1446 c.Request, _ = http.NewRequest(http.MethodPost, "", nil)1447 templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))1448 router.SetHTMLTemplate(templ)14491450 c.Negotiate(http.StatusOK, Negotiate{
9 unmodified lines
14601461func TestContextNegotiationNotSupport(t *testing.T) {1462 w := httptest.NewRecorder()1463 c, _ := CreateTestContext(w)1464 c.Request, _ = http.NewRequest("POST", "", nil)1464 c.Request, _ = http.NewRequest(http.MethodPost, "", nil)14651466 c.Negotiate(http.StatusOK, Negotiate{1467 Offered: []string{MIMEPOSTForm},1468 })
4 unmodified lines
1473}14741475func TestContextNegotiationFormat(t *testing.T) {1476 c, _ := CreateTestContext(httptest.NewRecorder())1477 c.Request, _ = http.NewRequest("POST", "", nil)1477 c.Request, _ = http.NewRequest(http.MethodPost, "", nil)14781479 assert.Panics(t, func() { c.NegotiateFormat() })1480 assert.Equal(t, MIMEJSON, c.NegotiateFormat(MIMEJSON, MIMEXML))1481 assert.Equal(t, MIMEHTML, c.NegotiateFormat(MIMEHTML, MIMEJSON))1482}14831484func TestContextNegotiationFormatWithAccept(t *testing.T) {1485 c, _ := CreateTestContext(httptest.NewRecorder())1486 c.Request, _ = http.NewRequest("POST", "/", nil)1486 c.Request, _ = http.NewRequest(http.MethodPost, "/", nil)1487 c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9;q=0.8")14881489 assert.Equal(t, MIMEXML, c.NegotiateFormat(MIMEJSON, MIMEXML))1490 assert.Equal(t, MIMEHTML, c.NegotiateFormat(MIMEXML, MIMEHTML))
1 unmodified line
1492}14931494func TestContextNegotiationFormatWithWildcardAccept(t *testing.T) {1495 c, _ := CreateTestContext(httptest.NewRecorder())1496 c.Request, _ = http.NewRequest("POST", "/", nil)1496 c.Request, _ = http.NewRequest(http.MethodPost, "/", nil)1497 c.Request.Header.Add("Accept", "*/*")14981499 assert.Equal(t, "*/*", c.NegotiateFormat("*/*"))1500 assert.Equal(t, "text/*", c.NegotiateFormat("text/*"))
2 unmodified lines
1503 assert.Equal(t, MIMEXML, c.NegotiateFormat(MIMEXML))1504 assert.Equal(t, MIMEHTML, c.NegotiateFormat(MIMEHTML))15051506 c, _ = CreateTestContext(httptest.NewRecorder())1507 c.Request, _ = http.NewRequest("POST", "/", nil)1507 c.Request, _ = http.NewRequest(http.MethodPost, "/", nil)1508 c.Request.Header.Add("Accept", "text/*")15091510 assert.Equal(t, "*/*", c.NegotiateFormat("*/*"))1511 assert.Equal(t, "text/*", c.NegotiateFormat("text/*"))
4 unmodified lines
1516}15171518func TestContextNegotiationFormatCustom(t *testing.T) {1519 c, _ := CreateTestContext(httptest.NewRecorder())1520 c.Request, _ = http.NewRequest("POST", "/", nil)1520 c.Request, _ = http.NewRequest(http.MethodPost, "/", nil)1521 c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9;q=0.8")15221523 c.Accepted = nil1524 c.SetAccepted(MIMEJSON, MIMEXML)
4 unmodified lines
1529}15301531func TestContextNegotiationFormat2(t *testing.T) {1532 c, _ := CreateTestContext(httptest.NewRecorder())1533 c.Request, _ = http.NewRequest("POST", "/", nil)1533 c.Request, _ = http.NewRequest(http.MethodPost, "/", nil)1534 c.Request.Header.Add("Accept", "image/tiff-fx")15351536 assert.Equal(t, "", c.NegotiateFormat("image/tiff"))1537}
119 unmodified lines
1657}16581659func TestContextClientIP(t *testing.T) {1660 c, _ := CreateTestContext(httptest.NewRecorder())1661 c.Request, _ = http.NewRequest("POST", "/", nil)1661 c.Request, _ = http.NewRequest(http.MethodPost, "/", nil)1662 c.engine.trustedCIDRs, _ = c.engine.prepareTrustedCIDRs()1663 resetContextForClientIPTests(c)16641665 // Legacy tests (validating that the defaults don't break the
134 unmodified lines
1800}18011802func TestContextContentType(t *testing.T) {1803 c, _ := CreateTestContext(httptest.NewRecorder())1804 c.Request, _ = http.NewRequest("POST", "/", nil)1804 c.Request, _ = http.NewRequest(http.MethodPost, "/", nil)1805 c.Request.Header.Set("Content-Type", "application/json; charset=utf-8")18061807 assert.Equal(t, "application/json", c.ContentType())1808}18091810func TestContextAutoBindJSON(t *testing.T) {1811 c, _ := CreateTestContext(httptest.NewRecorder())1812 c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))1812 c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))1813 c.Request.Header.Add("Content-Type", MIMEJSON)18141815 var obj struct {1816 Foo string `json:"foo"`
8 unmodified lines
1825func TestContextBindWithJSON(t *testing.T) {1826 w := httptest.NewRecorder()1827 c, _ := CreateTestContext(w)18281829 c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))1829 c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))1830 c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type18311832 var obj struct {1833 Foo string `json:"foo"`
8 unmodified lines
1842func TestContextBindWithXML(t *testing.T) {1843 w := httptest.NewRecorder()1844 c, _ := CreateTestContext(w)18451846 c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString(`<?xml version="1.0" encoding="UTF-8"?>1846 c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString(`<?xml version="1.0" encoding="UTF-8"?>1847 <root>1848 <foo>FOO</foo>1849 <bar>BAR</bar>1850 </root>`))
12 unmodified lines
1863func TestContextBindPlain(t *testing.T) {1864 // string1865 w := httptest.NewRecorder()1866 c, _ := CreateTestContext(w)1867 c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString(`test string`))1867 c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString(`test string`))1868 c.Request.Header.Add("Content-Type", MIMEPlain)18691870 var s string1871
1 unmodified line
1873 assert.Equal(t, "test string", s)1874 assert.Equal(t, 0, w.Body.Len())18751876 // []byte1877 c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString(`test []byte`))1877 c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString(`test []byte`))1878 c.Request.Header.Add("Content-Type", MIMEPlain)18791880 var bs []byte1881
5 unmodified lines
1887func TestContextBindHeader(t *testing.T) {1888 w := httptest.NewRecorder()1889 c, _ := CreateTestContext(w)18901891 c.Request, _ = http.NewRequest("POST", "/", nil)1891 c.Request, _ = http.NewRequest(http.MethodPost, "/", nil)1892 c.Request.Header.Add("rate", "8000")1893 c.Request.Header.Add("domain", "music")1894 c.Request.Header.Add("limit", "1000")1895
13 unmodified lines
1909func TestContextBindWithQuery(t *testing.T) {1910 w := httptest.NewRecorder()1911 c, _ := CreateTestContext(w)19121913 c.Request, _ = http.NewRequest("POST", "/?foo=bar&bar=foo", bytes.NewBufferString("foo=unused"))1913 c.Request, _ = http.NewRequest(http.MethodPost, "/?foo=bar&bar=foo", bytes.NewBufferString("foo=unused"))19141915 var obj struct {1916 Foo string `form:"foo"`1917 Bar string `form:"bar"`
7 unmodified lines
1925func TestContextBindWithYAML(t *testing.T) {1926 w := httptest.NewRecorder()1927 c, _ := CreateTestContext(w)19281929 c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("foo: bar\nbar: foo"))1929 c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString("foo: bar\nbar: foo"))1930 c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type19311932 var obj struct {1933 Foo string `yaml:"foo"`
8 unmodified lines
1942func TestContextBindWithTOML(t *testing.T) {1943 w := httptest.NewRecorder()1944 c, _ := CreateTestContext(w)19451946 c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("foo = 'bar'\nbar = 'foo'"))1946 c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString("foo = 'bar'\nbar = 'foo'"))1947 c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type19481949 var obj struct {1950 Foo string `toml:"foo"`
8 unmodified lines
1959func TestContextBadAutoBind(t *testing.T) {1960 w := httptest.NewRecorder()1961 c, _ := CreateTestContext(w)19621963 c.Request, _ = http.NewRequest("POST", "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}"))1963 c.Request, _ = http.NewRequest(http.MethodPost, "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}"))1964 c.Request.Header.Add("Content-Type", MIMEJSON)1965 var obj struct {1966 Foo string `json:"foo"`1967 Bar string `json:"bar"`
10 unmodified lines
1978}19791980func TestContextAutoShouldBindJSON(t *testing.T) {1981 c, _ := CreateTestContext(httptest.NewRecorder())1982 c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))1982 c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))1983 c.Request.Header.Add("Content-Type", MIMEJSON)19841985 var obj struct {1986 Foo string `json:"foo"`
8 unmodified lines
1995func TestContextShouldBindWithJSON(t *testing.T) {1996 w := httptest.NewRecorder()1997 c, _ := CreateTestContext(w)19981999 c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))1999 c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))2000 c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type20012002 var obj struct {2003 Foo string `json:"foo"`
8 unmodified lines
2012func TestContextShouldBindWithXML(t *testing.T) {2013 w := httptest.NewRecorder()2014 c, _ := CreateTestContext(w)20152016 c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString(`<?xml version="1.0" encoding="UTF-8"?>2016 c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString(`<?xml version="1.0" encoding="UTF-8"?>2017 <root>2018 <foo>FOO</foo>2019 <bar>BAR</bar>2020 </root>`))
12 unmodified lines
2033func TestContextShouldBindPlain(t *testing.T) {2034 // string2035 w := httptest.NewRecorder()2036 c, _ := CreateTestContext(w)2037 c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString(`test string`))2037 c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString(`test string`))2038 c.Request.Header.Add("Content-Type", MIMEPlain)20392040 var s string2041
1 unmodified line
2043 assert.Equal(t, "test string", s)2044 assert.Equal(t, 0, w.Body.Len())2045 // []byte20462047 c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString(`test []byte`))2047 c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString(`test []byte`))2048 c.Request.Header.Add("Content-Type", MIMEPlain)20492050 var bs []byte2051
5 unmodified lines
2057func TestContextShouldBindHeader(t *testing.T) {2058 w := httptest.NewRecorder()2059 c, _ := CreateTestContext(w)20602061 c.Request, _ = http.NewRequest("POST", "/", nil)2061 c.Request, _ = http.NewRequest(http.MethodPost, "/", nil)2062 c.Request.Header.Add("rate", "8000")2063 c.Request.Header.Add("domain", "music")2064 c.Request.Header.Add("limit", "1000")2065
13 unmodified lines
2079func TestContextShouldBindWithQuery(t *testing.T) {2080 w := httptest.NewRecorder()2081 c, _ := CreateTestContext(w)20822083 c.Request, _ = http.NewRequest("POST", "/?foo=bar&bar=foo&Foo=bar1&Bar=foo1", bytes.NewBufferString("foo=unused"))2083 c.Request, _ = http.NewRequest(http.MethodPost, "/?foo=bar&bar=foo&Foo=bar1&Bar=foo1", bytes.NewBufferString("foo=unused"))20842085 var obj struct {2086 Foo string `form:"foo"`2087 Bar string `form:"bar"`
11 unmodified lines
2099func TestContextShouldBindWithYAML(t *testing.T) {2100 w := httptest.NewRecorder()2101 c, _ := CreateTestContext(w)21022103 c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("foo: bar\nbar: foo"))2103 c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString("foo: bar\nbar: foo"))2104 c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type21052106 var obj struct {2107 Foo string `yaml:"foo"`
8 unmodified lines
2116func TestContextShouldBindWithTOML(t *testing.T) {2117 w := httptest.NewRecorder()2118 c, _ := CreateTestContext(w)21192120 c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("foo='bar'\nbar= 'foo'"))2120 c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString("foo='bar'\nbar= 'foo'"))2121 c.Request.Header.Add("Content-Type", MIMETOML) // set fake content-type21222123 var obj struct {2124 Foo string `toml:"foo"`
8 unmodified lines
2133func TestContextBadAutoShouldBind(t *testing.T) {2134 w := httptest.NewRecorder()2135 c, _ := CreateTestContext(w)21362137 c.Request, _ = http.NewRequest("POST", "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}"))2137 c.Request, _ = http.NewRequest(http.MethodPost, "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}"))2138 c.Request.Header.Add("Content-Type", MIMEJSON)2139 var obj struct {2140 Foo string `json:"foo"`2141 Bar string `json:"bar"`
55 unmodified lines
2197 {2198 w := httptest.NewRecorder()2199 c, _ := CreateTestContext(w)2200 c.Request, _ = http.NewRequest(2201 "POST", "http://example.com", bytes.NewBufferString(tt.bodyA),2201 http.MethodPost, "http://example.com", bytes.NewBufferString(tt.bodyA),2202 )2203 // When it binds to typeA and typeB, it finds the body is2204 // not typeB but typeA.2205 objA := typeA{}
9 unmodified lines
2215 // not typeA but typeB.2216 w := httptest.NewRecorder()2217 c, _ := CreateTestContext(w)2218 c.Request, _ = http.NewRequest(2219 "POST", "http://example.com", bytes.NewBufferString(tt.bodyB),2219 http.MethodPost, "http://example.com", bytes.NewBufferString(tt.bodyB),2220 )2221 objA := typeA{}2222 require.Error(t, c.ShouldBindBodyWith(&objA, tt.bindingA))2223 assert.NotEqual(t, typeA{"FOO"}, objA)
38 unmodified lines
22622263 w := httptest.NewRecorder()2264 c, _ := CreateTestContext(w)22652266 c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString(tt.body))2266 c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString(tt.body))22672268 type typeJSON struct {2269 Foo string `json:"foo" binding:"required"`2270 }
55 unmodified lines
23262327 w := httptest.NewRecorder()2328 c, _ := CreateTestContext(w)23292330 c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString(tt.body))2330 c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString(tt.body))23312332 type typeXML struct {2333 Foo string `xml:"foo" binding:"required"`2334 }
55 unmodified lines
23902391 w := httptest.NewRecorder()2392 c, _ := CreateTestContext(w)23932394 c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString(tt.body))2394 c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString(tt.body))23952396 type typeYAML struct {2397 Foo string `yaml:"foo" binding:"required"`2398 }
56 unmodified lines
24552456 w := httptest.NewRecorder()2457 c, _ := CreateTestContext(w)24582459 c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString(tt.body))2459 c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString(tt.body))24602461 type typeTOML struct {2462 Foo string `toml:"foo" binding:"required"`2463 }
60 unmodified lines
25242525 w := httptest.NewRecorder()2526 c, _ := CreateTestContext(w)25272528 c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString(tt.body))2528 c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString(tt.body))25292530 type typeJSON struct {2531 Foo string `json:"foo" binding:"required"`2532 }
28 unmodified lines
2561}25622563func TestContextGolangContext(t *testing.T) {2564 c, _ := CreateTestContext(httptest.NewRecorder())2565 c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))2565 c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))2566 require.NoError(t, c.Err())2567 assert.Nil(t, c.Done())2568 ti, ok := c.Deadline()2569 assert.Equal(t, time.Time{}, ti)
9 unmodified lines
25792580func TestWebsocketsRequired(t *testing.T) {2581 // Example request from spec: https://tools.ietf.org/html/rfc6455#section-1.22582 c, _ := CreateTestContext(httptest.NewRecorder())2583 c.Request, _ = http.NewRequest("GET", "/chat", nil)2583 c.Request, _ = http.NewRequest(http.MethodGet, "/chat", nil)2584 c.Request.Header.Set("Host", "server.example.com")2585 c.Request.Header.Set("Upgrade", "websocket")2586 c.Request.Header.Set("Connection", "Upgrade")2587 c.Request.Header.Set("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==")
4 unmodified lines
2592 assert.True(t, c.IsWebsocket())25932594 // Normal request, no websocket required.2595 c, _ = CreateTestContext(httptest.NewRecorder())2596 c.Request, _ = http.NewRequest("GET", "/chat", nil)2596 c.Request, _ = http.NewRequest(http.MethodGet, "/chat", nil)2597 c.Request.Header.Set("Host", "server.example.com")25982599 assert.False(t, c.IsWebsocket())2600}26012602func TestGetRequestHeaderValue(t *testing.T) {2603 c, _ := CreateTestContext(httptest.NewRecorder())2604 c.Request, _ = http.NewRequest("GET", "/chat", nil)2604 c.Request, _ = http.NewRequest(http.MethodGet, "/chat", nil)2605 c.Request.Header.Set("Gin-Version", "1.0.0")26062607 assert.Equal(t, "1.0.0", c.GetHeader("Gin-Version"))2608 assert.Empty(t, c.GetHeader("Connection"))
1 unmodified line
26102611func TestContextGetRawData(t *testing.T) {2612 c, _ := CreateTestContext(httptest.NewRecorder())2613 body := bytes.NewBufferString("Fetch binary post data")2614 c.Request, _ = http.NewRequest("POST", "/", body)2614 c.Request, _ = http.NewRequest(http.MethodPost, "/", body)2615 c.Request.Header.Add("Content-Type", MIMEPOSTForm)26162617 data, err := c.GetRawData()2618 require.NoError(t, err)
120 unmodified lines
2739 assert.Equal(t, c.Param("name"), param)2740 }(c.Copy(), c.Param("name"))2741 })2742 }2743 PerformRequest(router, "GET", "/name1/api")2744 PerformRequest(router, "GET", "/name2/api")2743 PerformRequest(router, http.MethodGet, "/name1/api")2744 PerformRequest(router, http.MethodGet, "/name2/api")2745 wg.Wait()2746}27472748func TestContextWithKeysMutex(t *testing.T) {
10 unmodified lines
2759}27602761func TestRemoteIPFail(t *testing.T) {2762 c, _ := CreateTestContext(httptest.NewRecorder())2763 c.Request, _ = http.NewRequest("POST", "/", nil)2763 c.Request, _ = http.NewRequest(http.MethodPost, "/", nil)2764 c.Request.RemoteAddr = "[:::]:80"2765 ip := net.ParseIP(c.RemoteIP())2766 trust := c.engine.isTrustedProxy(ip)2767 assert.Nil(t, ip)
93 unmodified lines
2861 var key KeyStruct2862 c, _ := CreateTestContext(httptest.NewRecorder())2863 // enable ContextWithFallback feature flag2864 c.engine.ContextWithFallback = true2865 c.Request, _ = http.NewRequest("POST", "/", nil)2865 c.Request, _ = http.NewRequest(http.MethodPost, "/", nil)2866 c.Request = c.Request.WithContext(context.WithValue(context.TODO(), key, "value"))2867 return c, key2868 },2869 value: "value",
3 unmodified lines
2873 getContextAndKey: func() (*Context, any) {2874 c, _ := CreateTestContext(httptest.NewRecorder())2875 // enable ContextWithFallback feature flag2876 c.engine.ContextWithFallback = true2877 c.Request, _ = http.NewRequest("POST", "/", nil)2877 c.Request, _ = http.NewRequest(http.MethodPost, "/", nil)2878 c.Request = c.Request.WithContext(context.WithValue(context.TODO(), contextKey("key"), "value"))2879 return c, contextKey("key")2880 },2881 value: "value",
14 unmodified lines
2896 getContextAndKey: func() (*Context, any) {2897 c, _ := CreateTestContext(httptest.NewRecorder())2898 // enable ContextWithFallback feature flag2899 c.engine.ContextWithFallback = true2900 c.Request, _ = http.NewRequest("POST", "/", nil)2900 c.Request, _ = http.NewRequest(http.MethodPost, "/", nil)2901 return c, "key"2902 },2903 value: nil,2904 },
123 unmodified lines
3028 c.Header("X-Test", "original")3029 c.Header("X-Test-2", "present")3030 c.String(http.StatusOK, "hello world")3031 })3032 c.Request = httptest.NewRequest("GET", "/", nil)3032 c.Request = httptest.NewRequest(http.MethodGet, "/", nil)3033 r.HandleContext(c)3034 // Result() has headers frozen when WriteHeaderNow() has been called3035 // Compared to this time, this is when the response headers will be flushed3036 // As response is flushed on c.String, the Header cannot be set by the first
48 unmodified lines
modified:debug_test.go+3 added-2 removed
8 unmodified lines
9 "fmt"10 "html/template"11 "io"12 "log"13 "net/http"14 "os"15 "runtime"16 "strings"17 "sync"
42 unmodified lines
6061func TestDebugPrintRoutes(t *testing.T) {62 re := captureOutput(t, func() {63 SetMode(DebugMode)63 debugPrintRoute("GET", "/path/to/route/:param", HandlersChain{func(c *Context) {}, handlerNameTest})64 debugPrintRoute(http.MethodGet, "/path/to/route/:param", HandlersChain{func(c *Context) {}, handlerNameTest})65 SetMode(TestMode)66 })67 assert.Regexp(t, `^\[GIN-debug\] GET /path/to/route/:param --> (.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest \(2 handlers\)\n$`, re)68}
3 unmodified lines
72 fmt.Fprintf(DefaultWriter, "[GIN-debug] %-6s %-40s --> %s (%d handlers)\n", httpMethod, absolutePath, handlerName, nuHandlers)73 }74 re := captureOutput(t, func() {75 SetMode(DebugMode)75 debugPrintRoute("GET", "/path/to/route/:param1/:param2", HandlersChain{func(c *Context) {}, handlerNameTest})76 debugPrintRoute(http.MethodGet, "/path/to/route/:param1/:param2", HandlersChain{func(c *Context) {}, handlerNameTest})77 SetMode(TestMode)78 })79 assert.Regexp(t, `^\[GIN-debug\] GET /path/to/route/:param1/:param2 --> (.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest \(2 handlers\)\n$`, re)80}
88 unmodified lines
modified:deprecated_test.go+1 added-1 removed
16 unmodified lines
17func TestBindWith(t *testing.T) {18 w := httptest.NewRecorder()19 c, _ := CreateTestContext(w)2021 c.Request, _ = http.NewRequest("POST", "/?foo=bar&bar=foo", bytes.NewBufferString("foo=unused"))21 c.Request, _ = http.NewRequest(http.MethodPost, "/?foo=bar&bar=foo", bytes.NewBufferString("foo=unused"))2223 var obj struct {24 Foo string `form:"foo"`25 Bar string `form:"bar"`
8 unmodified lines
modified:gin_test.go+24 added-24 removed
325 unmodified lines
326}327328func TestAddRoute(t *testing.T) {329 router := New()330 router.addRoute("GET", "/", HandlersChain{func(_ *Context) {}})330 router.addRoute(http.MethodGet, "/", HandlersChain{func(_ *Context) {}})331332 assert.Len(t, router.trees, 1)333 assert.NotNil(t, router.trees.get("GET"))334 assert.Nil(t, router.trees.get("POST"))333 assert.NotNil(t, router.trees.get(http.MethodGet))334 assert.Nil(t, router.trees.get(http.MethodPost))335336 router.addRoute("POST", "/", HandlersChain{func(_ *Context) {}})336 router.addRoute(http.MethodPost, "/", HandlersChain{func(_ *Context) {}})337338 assert.Len(t, router.trees, 2)339 assert.NotNil(t, router.trees.get("GET"))340 assert.NotNil(t, router.trees.get("POST"))339 assert.NotNil(t, router.trees.get(http.MethodGet))340 assert.NotNil(t, router.trees.get(http.MethodPost))341342 router.addRoute("POST", "/post", HandlersChain{func(_ *Context) {}})342 router.addRoute(http.MethodPost, "/post", HandlersChain{func(_ *Context) {}})343 assert.Len(t, router.trees, 2)344}345346func TestAddRouteFails(t *testing.T) {347 router := New()348 assert.Panics(t, func() { router.addRoute("", "/", HandlersChain{func(_ *Context) {}}) })349 assert.Panics(t, func() { router.addRoute("GET", "a", HandlersChain{func(_ *Context) {}}) })350 assert.Panics(t, func() { router.addRoute("GET", "/", HandlersChain{}) })349 assert.Panics(t, func() { router.addRoute(http.MethodGet, "a", HandlersChain{func(_ *Context) {}}) })350 assert.Panics(t, func() { router.addRoute(http.MethodGet, "/", HandlersChain{}) })351352 router.addRoute("POST", "/post", HandlersChain{func(_ *Context) {}})352 router.addRoute(http.MethodPost, "/post", HandlersChain{func(_ *Context) {}})353 assert.Panics(t, func() {354 router.addRoute("POST", "/post", HandlersChain{func(_ *Context) {}})354 router.addRoute(http.MethodPost, "/post", HandlersChain{func(_ *Context) {}})355 })356}357358func TestCreateDefaultRouter(t *testing.T) {
133 unmodified lines
492 list := router.Routes()493494 assert.Len(t, list, 7)495 assertRoutePresent(t, list, RouteInfo{496 Method: "GET",496 Method: http.MethodGet,497 Path: "/favicon.ico",498 Handler: "^(.*/vendor/)?github.com/gin-gonic/gin.handlerTest1$",499 })500 assertRoutePresent(t, list, RouteInfo{501 Method: "GET",501 Method: http.MethodGet,502 Path: "/",503 Handler: "^(.*/vendor/)?github.com/gin-gonic/gin.handlerTest1$",504 })505 assertRoutePresent(t, list, RouteInfo{506 Method: "GET",506 Method: http.MethodGet,507 Path: "/users/",508 Handler: "^(.*/vendor/)?github.com/gin-gonic/gin.handlerTest2$",509 })510 assertRoutePresent(t, list, RouteInfo{511 Method: "GET",511 Method: http.MethodGet,512 Path: "/users/:id",513 Handler: "^(.*/vendor/)?github.com/gin-gonic/gin.handlerTest1$",514 })515 assertRoutePresent(t, list, RouteInfo{516 Method: "POST",516 Method: http.MethodPost,517 Path: "/users/:id",518 Handler: "^(.*/vendor/)?github.com/gin-gonic/gin.handlerTest2$",519 })520}
9 unmodified lines
530 v2.GET("/", func(c *Context) {})531 }532533 assert.NotPanics(t, func() {534 w := PerformRequest(r, "GET", "/")534 w := PerformRequest(r, http.MethodGet, "/")535 assert.Equal(t, 301, w.Code)536 })537}538
24 unmodified lines
563 atomic.AddInt64(&handlerCounter, 1)564 })565566 assert.NotPanics(t, func() {567 w := PerformRequest(r, "GET", "/"+strconv.Itoa(expectValue-1)) // include 0 value567 w := PerformRequest(r, http.MethodGet, "/"+strconv.Itoa(expectValue-1)) // include 0 value568 assert.Equal(t, 200, w.Code)569 assert.Equal(t, expectValue, w.Body.Len())570 })571
139 unmodified lines
711712 r := New(fc)713714 routes := r.Routes()715 assertRoutePresent(t, routes, RouteInfo{Path: "/test1", Method: "GET", Handler: "github.com/gin-gonic/gin.handlerTest1"})716 assertRoutePresent(t, routes, RouteInfo{Path: "/test2", Method: "GET", Handler: "github.com/gin-gonic/gin.handlerTest2"})715 assertRoutePresent(t, routes, RouteInfo{Path: "/test1", Method: http.MethodGet, Handler: "github.com/gin-gonic/gin.handlerTest1"})716 assertRoutePresent(t, routes, RouteInfo{Path: "/test2", Method: http.MethodGet, Handler: "github.com/gin-gonic/gin.handlerTest2"})717}718719func TestWithOptionFunc(t *testing.T) {720 r := New()
7 unmodified lines
728 })729 })730731 routes := r.Routes()732 assertRoutePresent(t, routes, RouteInfo{Path: "/test1", Method: "GET", Handler: "github.com/gin-gonic/gin.handlerTest1"})733 assertRoutePresent(t, routes, RouteInfo{Path: "/test2", Method: "GET", Handler: "github.com/gin-gonic/gin.handlerTest2"})732 assertRoutePresent(t, routes, RouteInfo{Path: "/test1", Method: http.MethodGet, Handler: "github.com/gin-gonic/gin.handlerTest1"})733 assertRoutePresent(t, routes, RouteInfo{Path: "/test2", Method: http.MethodGet, Handler: "github.com/gin-gonic/gin.handlerTest2"})734}735736type Birthday string737
10 unmodified lines
748 route.GET("/test", func(ctx *Context) {749 _ = ctx.BindQuery(&request)750 ctx.JSON(200, request.Birthday)751 })752 req := httptest.NewRequest("GET", "/test?birthday=2000-01-01", nil)752 req := httptest.NewRequest(http.MethodGet, "/test?birthday=2000-01-01", nil)753 w := httptest.NewRecorder()754 route.ServeHTTP(w, req)755 assert.Equal(t, 200, w.Code)756 assert.Equal(t, `"2000/01/01"`, w.Body.String())
3 unmodified lines
760func TestMethodNotAllowedNoRoute(t *testing.T) {761 g := New()762 g.HandleMethodNotAllowed = true763764 req := httptest.NewRequest("GET", "/", nil)764 req := httptest.NewRequest(http.MethodGet, "/", nil)765 resp := httptest.NewRecorder()766 assert.NotPanics(t, func() { g.ServeHTTP(resp, req) })767 assert.Equal(t, http.StatusNotFound, resp.Code)768}
modified:logger_test.go+42 added-42 removed
29 unmodified lines
30 router.PATCH("/example", func(c *Context) {})31 router.HEAD("/example", func(c *Context) {})32 router.OPTIONS("/example", func(c *Context) {})3334 PerformRequest(router, "GET", "/example?a=100")34 PerformRequest(router, http.MethodGet, "/example?a=100")35 assert.Contains(t, buffer.String(), "200")36 assert.Contains(t, buffer.String(), "GET")36 assert.Contains(t, buffer.String(), http.MethodGet)37 assert.Contains(t, buffer.String(), "/example")38 assert.Contains(t, buffer.String(), "a=100")3940 // I wrote these first (extending the above) but then realized they are more41 // like integration tests because they test the whole logging process rather42 // than individual functions. Im not sure where these should go.43 buffer.Reset()44 PerformRequest(router, "POST", "/example")44 PerformRequest(router, http.MethodPost, "/example")45 assert.Contains(t, buffer.String(), "200")46 assert.Contains(t, buffer.String(), "POST")46 assert.Contains(t, buffer.String(), http.MethodPost)47 assert.Contains(t, buffer.String(), "/example")4849 buffer.Reset()50 PerformRequest(router, "PUT", "/example")50 PerformRequest(router, http.MethodPut, "/example")51 assert.Contains(t, buffer.String(), "200")52 assert.Contains(t, buffer.String(), "PUT")52 assert.Contains(t, buffer.String(), http.MethodPut)53 assert.Contains(t, buffer.String(), "/example")5455 buffer.Reset()56 PerformRequest(router, "DELETE", "/example")56 PerformRequest(router, http.MethodDelete, "/example")57 assert.Contains(t, buffer.String(), "200")58 assert.Contains(t, buffer.String(), "DELETE")58 assert.Contains(t, buffer.String(), http.MethodDelete)59 assert.Contains(t, buffer.String(), "/example")6061 buffer.Reset()62 PerformRequest(router, "PATCH", "/example")
13 unmodified lines
76 assert.Contains(t, buffer.String(), "OPTIONS")77 assert.Contains(t, buffer.String(), "/example")7879 buffer.Reset()80 PerformRequest(router, "GET", "/notfound")80 PerformRequest(router, http.MethodGet, "/notfound")81 assert.Contains(t, buffer.String(), "404")82 assert.Contains(t, buffer.String(), "GET")82 assert.Contains(t, buffer.String(), http.MethodGet)83 assert.Contains(t, buffer.String(), "/notfound")84}8586func TestLoggerWithConfig(t *testing.T) {
7 unmodified lines
94 router.PATCH("/example", func(c *Context) {})95 router.HEAD("/example", func(c *Context) {})96 router.OPTIONS("/example", func(c *Context) {})9798 PerformRequest(router, "GET", "/example?a=100")98 PerformRequest(router, http.MethodGet, "/example?a=100")99 assert.Contains(t, buffer.String(), "200")100 assert.Contains(t, buffer.String(), "GET")100 assert.Contains(t, buffer.String(), http.MethodGet)101 assert.Contains(t, buffer.String(), "/example")102 assert.Contains(t, buffer.String(), "a=100")103104 // I wrote these first (extending the above) but then realized they are more105 // like integration tests because they test the whole logging process rather106 // than individual functions. Im not sure where these should go.107 buffer.Reset()108 PerformRequest(router, "POST", "/example")108 PerformRequest(router, http.MethodPost, "/example")109 assert.Contains(t, buffer.String(), "200")110 assert.Contains(t, buffer.String(), "POST")110 assert.Contains(t, buffer.String(), http.MethodPost)111 assert.Contains(t, buffer.String(), "/example")112113 buffer.Reset()114 PerformRequest(router, "PUT", "/example")114 PerformRequest(router, http.MethodPut, "/example")115 assert.Contains(t, buffer.String(), "200")116 assert.Contains(t, buffer.String(), "PUT")116 assert.Contains(t, buffer.String(), http.MethodPut)117 assert.Contains(t, buffer.String(), "/example")118119 buffer.Reset()120 PerformRequest(router, "DELETE", "/example")120 PerformRequest(router, http.MethodDelete, "/example")121 assert.Contains(t, buffer.String(), "200")122 assert.Contains(t, buffer.String(), "DELETE")122 assert.Contains(t, buffer.String(), http.MethodDelete)123 assert.Contains(t, buffer.String(), "/example")124125 buffer.Reset()126 PerformRequest(router, "PATCH", "/example")
13 unmodified lines
140 assert.Contains(t, buffer.String(), "OPTIONS")141 assert.Contains(t, buffer.String(), "/example")142143 buffer.Reset()144 PerformRequest(router, "GET", "/notfound")144 PerformRequest(router, http.MethodGet, "/notfound")145 assert.Contains(t, buffer.String(), "404")146 assert.Contains(t, buffer.String(), "GET")146 assert.Contains(t, buffer.String(), http.MethodGet)147 assert.Contains(t, buffer.String(), "/notfound")148}149150func TestLoggerWithFormatter(t *testing.T) {
17 unmodified lines
168 param.ErrorMessage,169 )170 }))171 router.GET("/example", func(c *Context) {})172 PerformRequest(router, "GET", "/example?a=100")172 PerformRequest(router, http.MethodGet, "/example?a=100")173174 // output test175 assert.Contains(t, buffer.String(), "[FORMATTER TEST]")176 assert.Contains(t, buffer.String(), "200")177 assert.Contains(t, buffer.String(), "GET")177 assert.Contains(t, buffer.String(), http.MethodGet)178 assert.Contains(t, buffer.String(), "/example")179 assert.Contains(t, buffer.String(), "a=100")180}181
27 unmodified lines
209 c.Request.Header.Set("X-Forwarded-For", "20.20.20.20")210 gotKeys = c.Keys211 time.Sleep(time.Millisecond)212 })213 PerformRequest(router, "GET", "/example?a=100")213 PerformRequest(router, http.MethodGet, "/example?a=100")214215 // output test216 assert.Contains(t, buffer.String(), "[FORMATTER TEST]")217 assert.Contains(t, buffer.String(), "200")218 assert.Contains(t, buffer.String(), "GET")218 assert.Contains(t, buffer.String(), http.MethodGet)219 assert.Contains(t, buffer.String(), "/example")220 assert.Contains(t, buffer.String(), "a=100")221222 // LogFormatterParams test
1 unmodified line
224 assert.NotEmpty(t, gotParam.TimeStamp)225 assert.Equal(t, 200, gotParam.StatusCode)226 assert.NotEmpty(t, gotParam.Latency)227 assert.Equal(t, "20.20.20.20", gotParam.ClientIP)228 assert.Equal(t, "GET", gotParam.Method)228 assert.Equal(t, http.MethodGet, gotParam.Method)229 assert.Equal(t, "/example?a=100", gotParam.Path)230 assert.Empty(t, gotParam.ErrorMessage)231 assert.Equal(t, gotKeys, gotParam.Keys)232}
5 unmodified lines
238 TimeStamp: timeStamp,239 StatusCode: 200,240 Latency: time.Second * 5,241 ClientIP: "20.20.20.20",242 Method: "GET",242 Method: http.MethodGet,243 Path: "/",244 ErrorMessage: "",245 isTerm: false,246 }
2 unmodified lines
249 TimeStamp: timeStamp,250 StatusCode: 200,251 Latency: time.Second * 5,252 ClientIP: "20.20.20.20",253 Method: "GET",253 Method: http.MethodGet,254 Path: "/",255 ErrorMessage: "",256 isTerm: true,257 }
1 unmodified line
259 TimeStamp: timeStamp,260 StatusCode: 200,261 Latency: time.Millisecond * 9876543210,262 ClientIP: "20.20.20.20",263 Method: "GET",263 Method: http.MethodGet,264 Path: "/",265 ErrorMessage: "",266 isTerm: true,267 }
2 unmodified lines
270 TimeStamp: timeStamp,271 StatusCode: 200,272 Latency: time.Millisecond * 9876543210,273 ClientIP: "20.20.20.20",274 Method: "GET",274 Method: http.MethodGet,275 Path: "/",276 ErrorMessage: "",277 isTerm: false,278 }
12 unmodified lines
291 }292 return p.MethodColor()293 }294295 assert.Equal(t, blue, colorForMethod("GET"), "get should be blue")296 assert.Equal(t, cyan, colorForMethod("POST"), "post should be cyan")297 assert.Equal(t, yellow, colorForMethod("PUT"), "put should be yellow")298 assert.Equal(t, red, colorForMethod("DELETE"), "delete should be red")295 assert.Equal(t, blue, colorForMethod(http.MethodGet), "get should be blue")296 assert.Equal(t, cyan, colorForMethod(http.MethodPost), "post should be cyan")297 assert.Equal(t, yellow, colorForMethod(http.MethodPut), "put should be yellow")298 assert.Equal(t, red, colorForMethod(http.MethodDelete), "delete should be red")299 assert.Equal(t, green, colorForMethod("PATCH"), "patch should be green")300 assert.Equal(t, magenta, colorForMethod("HEAD"), "head should be magenta")301 assert.Equal(t, white, colorForMethod("OPTIONS"), "options should be white")302 assert.Equal(t, reset, colorForMethod("TRACE"), "trace is not defined and should be the reset color")
65 unmodified lines
368 c.Error(errors.New("this is an error")) //nolint: errcheck369 c.String(http.StatusInternalServerError, "hola!")370 })371372 w := PerformRequest(router, "GET", "/error")372 w := PerformRequest(router, http.MethodGet, "/error")373 assert.Equal(t, http.StatusOK, w.Code)374 assert.Equal(t, "{\"error\":\"this is an error\"}", w.Body.String())375376 w = PerformRequest(router, "GET", "/abort")376 w = PerformRequest(router, http.MethodGet, "/abort")377 assert.Equal(t, http.StatusUnauthorized, w.Code)378 assert.Equal(t, "{\"error\":\"no authorized\"}", w.Body.String())379380 w = PerformRequest(router, "GET", "/print")380 w = PerformRequest(router, http.MethodGet, "/print")381 assert.Equal(t, http.StatusInternalServerError, w.Code)382 assert.Equal(t, "hola!{\"error\":\"this is an error\"}", w.Body.String())383}384
3 unmodified lines
388 router.Use(LoggerWithWriter(buffer, "/skipped"))389 router.GET("/logged", func(c *Context) {})390 router.GET("/skipped", func(c *Context) {})391392 PerformRequest(router, "GET", "/logged")392 PerformRequest(router, http.MethodGet, "/logged")393 assert.Contains(t, buffer.String(), "200")394395 buffer.Reset()396 PerformRequest(router, "GET", "/skipped")396 PerformRequest(router, http.MethodGet, "/skipped")397 assert.Contains(t, buffer.String(), "")398}399400func TestLoggerWithConfigSkippingPaths(t *testing.T) {
5 unmodified lines
406 }))407 router.GET("/logged", func(c *Context) {})408 router.GET("/skipped", func(c *Context) {})409410 PerformRequest(router, "GET", "/logged")410 PerformRequest(router, http.MethodGet, "/logged")411 assert.Contains(t, buffer.String(), "200")412413 buffer.Reset()414 PerformRequest(router, "GET", "/skipped")414 PerformRequest(router, http.MethodGet, "/skipped")415 assert.Contains(t, buffer.String(), "")416}417418func TestLoggerWithConfigSkipper(t *testing.T) {
7 unmodified lines
426 }))427 router.GET("/logged", func(c *Context) { c.Status(http.StatusOK) })428 router.GET("/skipped", func(c *Context) { c.Status(http.StatusNoContent) })429430 PerformRequest(router, "GET", "/logged")430 PerformRequest(router, http.MethodGet, "/logged")431 assert.Contains(t, buffer.String(), "200")432433 buffer.Reset()434 PerformRequest(router, "GET", "/skipped")434 PerformRequest(router, http.MethodGet, "/skipped")435 assert.Contains(t, buffer.String(), "")436}437438func TestDisableConsoleColor(t *testing.T) {
18 unmodified lines
modified:middleware_test.go+8 added-8 removed
33 unmodified lines
34 router.NoMethod(func(c *Context) {35 signature += " XX "36 })37 // RUN38 w := PerformRequest(router, "GET", "/")38 w := PerformRequest(router, http.MethodGet, "/")3940 // TEST41 assert.Equal(t, http.StatusOK, w.Code)42 assert.Equal(t, "ACDB", signature)
27 unmodified lines
70 router.NoMethod(func(c *Context) {71 signature += " X "72 })73 // RUN74 w := PerformRequest(router, "GET", "/")74 w := PerformRequest(router, http.MethodGet, "/")7576 // TEST77 assert.Equal(t, http.StatusNotFound, w.Code)78 assert.Equal(t, "ACEGHFDB", signature)
28 unmodified lines
107 router.POST("/", func(c *Context) {108 signature += " XX "109 })110 // RUN111 w := PerformRequest(router, "GET", "/")111 w := PerformRequest(router, http.MethodGet, "/")112113 // TEST114 assert.Equal(t, http.StatusMethodNotAllowed, w.Code)115 assert.Equal(t, "ACEGHFDB", signature)
32 unmodified lines
148 signature += " XX "149 })150151 // RUN152 w := PerformRequest(router, "GET", "/")152 w := PerformRequest(router, http.MethodGet, "/")153154 // TEST155 assert.Equal(t, http.StatusNotFound, w.Code)156 assert.Equal(t, "AC X DB", signature)
17 unmodified lines
174 signature += " XX "175 })176177 // RUN178 w := PerformRequest(router, "GET", "/")178 w := PerformRequest(router, http.MethodGet, "/")179180 // TEST181 assert.Equal(t, http.StatusUnauthorized, w.Code)182 assert.Equal(t, "ACD", signature)
12 unmodified lines
195 signature += "C"196 c.Next()197 })198 // RUN199 w := PerformRequest(router, "GET", "/")199 w := PerformRequest(router, http.MethodGet, "/")200201 // TEST202 assert.Equal(t, http.StatusGone, w.Code)203 assert.Equal(t, "ACB", signature)
14 unmodified lines
218 context.Next()219 signature += "C"220 })221 // RUN222 w := PerformRequest(router, "GET", "/")222 w := PerformRequest(router, http.MethodGet, "/")223224 // TEST225 assert.Equal(t, http.StatusInternalServerError, w.Code)226 assert.Equal(t, "A", signature)
18 unmodified lines
245 Data: "message",246 })247 })248249 w := PerformRequest(router, "GET", "/")249 w := PerformRequest(router, http.MethodGet, "/")250251 assert.Equal(t, http.StatusBadRequest, w.Code)252 assert.Equal(t, strings.Replace("hola\n<map><foo>bar</foo></map>{\"foo\":\"bar\"}{\"foo\":\"bar\"}event:test\ndata:message\n\n", " ", "", -1), strings.Replace(w.Body.String(), " ", "", -1))253}
modified:recovery_test.go+11 added-11 removed
23 unmodified lines
24 c.AbortWithStatus(http.StatusBadRequest)25 panic("Oupps, Houston, we have a problem")26 })27 // RUN28 w := PerformRequest(router, "GET", "/recovery",28 w := PerformRequest(router, http.MethodGet, "/recovery",29 header{30 Key: "Host",31 Value: "www.google.com",32 },
21 unmodified lines
54 router.GET("/recovery", func(_ *Context) {55 panic("Oupps, Houston, we have a problem")56 })57 // RUN58 w := PerformRequest(router, "GET", "/recovery")58 w := PerformRequest(router, http.MethodGet, "/recovery")59 // TEST60 assert.Equal(t, http.StatusInternalServerError, w.Code)61 assert.Contains(t, buffer.String(), "panic recovered")62 assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem")
2 unmodified lines
6566 // Debug mode prints the request67 SetMode(DebugMode)68 // RUN69 w = PerformRequest(router, "GET", "/recovery")69 w = PerformRequest(router, http.MethodGet, "/recovery")70 // TEST71 assert.Equal(t, http.StatusInternalServerError, w.Code)72 assert.Contains(t, buffer.String(), "GET /recovery")73
8 unmodified lines
82 c.AbortWithStatus(http.StatusBadRequest)83 panic("Oupps, Houston, we have a problem")84 })85 // RUN86 w := PerformRequest(router, "GET", "/recovery")86 w := PerformRequest(router, http.MethodGet, "/recovery")87 // TEST88 assert.Equal(t, http.StatusBadRequest, w.Code)89}90
42 unmodified lines
133 e := &net.OpError{Err: &os.SyscallError{Err: errno}}134 panic(e)135 })136 // RUN137 w := PerformRequest(router, "GET", "/recovery")137 w := PerformRequest(router, http.MethodGet, "/recovery")138 // TEST139 assert.Equal(t, expectCode, w.Code)140 assert.Contains(t, strings.ToLower(buf.String()), expectMsg)141 })
12 unmodified lines
154 router.GET("/recovery", func(_ *Context) {155 panic("Oupps, Houston, we have a problem")156 })157 // RUN158 w := PerformRequest(router, "GET", "/recovery")158 w := PerformRequest(router, http.MethodGet, "/recovery")159 // TEST160 assert.Equal(t, http.StatusBadRequest, w.Code)161 assert.Contains(t, buffer.String(), "panic recovered")162 assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem")
2 unmodified lines
165166 // Debug mode prints the request167 SetMode(DebugMode)168 // RUN169 w = PerformRequest(router, "GET", "/recovery")169 w = PerformRequest(router, http.MethodGet, "/recovery")170 // TEST171 assert.Equal(t, http.StatusBadRequest, w.Code)172 assert.Contains(t, buffer.String(), "GET /recovery")173
15 unmodified lines
189 router.GET("/recovery", func(_ *Context) {190 panic("Oupps, Houston, we have a problem")191 })192 // RUN193 w := PerformRequest(router, "GET", "/recovery")193 w := PerformRequest(router, http.MethodGet, "/recovery")194 // TEST195 assert.Equal(t, http.StatusBadRequest, w.Code)196 assert.Contains(t, buffer.String(), "panic recovered")197 assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem")
2 unmodified lines
200201 // Debug mode prints the request202 SetMode(DebugMode)203 // RUN204 w = PerformRequest(router, "GET", "/recovery")204 w = PerformRequest(router, http.MethodGet, "/recovery")205 // TEST206 assert.Equal(t, http.StatusBadRequest, w.Code)207 assert.Contains(t, buffer.String(), "GET /recovery")208
15 unmodified lines
224 router.GET("/recovery", func(_ *Context) {225 panic("Oupps, Houston, we have a problem")226 })227 // RUN228 w := PerformRequest(router, "GET", "/recovery")228 w := PerformRequest(router, http.MethodGet, "/recovery")229 // TEST230 assert.Equal(t, http.StatusBadRequest, w.Code)231 assert.Contains(t, buffer.String(), "panic recovered")232 assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem")
2 unmodified lines
235236 // Debug mode prints the request237 SetMode(DebugMode)238 // RUN239 w = PerformRequest(router, "GET", "/recovery")239 w = PerformRequest(router, http.MethodGet, "/recovery")240 // TEST241 assert.Equal(t, http.StatusBadRequest, w.Code)242 assert.Contains(t, buffer.String(), "GET /recovery")243
4 unmodified lines
modified:routes_test.go+4 added-4 removed
521 unmodified lines
522 router.POST("/path", func(c *Context) {})523 w := PerformRequest(router, http.MethodPut, "/path")524 assert.Equal(t, http.StatusMethodNotAllowed, w.Code)525 allowed := w.Header().Get("Allow")526 assert.Contains(t, allowed, "GET")527 assert.Contains(t, allowed, "POST")526 assert.Contains(t, allowed, http.MethodGet)527 assert.Contains(t, allowed, http.MethodPost)528}529530func TestRouteNotAllowedDisabled(t *testing.T) {531 router := New()
24 unmodified lines
556 {"/../path", http.StatusOK, ""}, // CleanPath557 {"/nope", http.StatusNotFound, ""}, // NotFound558 }559 for _, tr := range testRoutes {560 w := PerformRequest(router, "GET", tr.route)560 w := PerformRequest(router, http.MethodGet, tr.route)561 assert.Equal(t, tr.code, w.Code)562 if w.Code != http.StatusNotFound {563 assert.Equal(t, tr.location, w.Header().Get("Location"))564 }
220 unmodified lines
785786 v1.GET("/orgs/:id", handlerTest1)787 v1.DELETE("/orgs/:id", handlerTest1)788789 w := PerformRequest(r, "GET", "/base/v1/user/groups")789 w := PerformRequest(r, http.MethodGet, "/base/v1/user/groups")790 assert.Equal(t, http.StatusNotFound, w.Code)791}
modified:utils_test.go+6 added-6 removed
27 unmodified lines
28 T *testing.T29}3031func (t *testStruct) ServeHTTP(w http.ResponseWriter, req *http.Request) {32 assert.Equal(t.T, "POST", req.Method)32 assert.Equal(t.T, http.MethodPost, req.Method)33 assert.Equal(t.T, "/path", req.URL.Path)34 w.WriteHeader(http.StatusInternalServerError)35 fmt.Fprint(w, "hello")36}
1 unmodified line
38func TestWrap(t *testing.T) {39 router := New()40 router.POST("/path", WrapH(&testStruct{t}))41 router.GET("/path2", WrapF(func(w http.ResponseWriter, req *http.Request) {42 assert.Equal(t, "GET", req.Method)42 assert.Equal(t, http.MethodGet, req.Method)43 assert.Equal(t, "/path2", req.URL.Path)44 w.WriteHeader(http.StatusBadRequest)45 fmt.Fprint(w, "hola!")46 }))4748 w := PerformRequest(router, "POST", "/path")48 w := PerformRequest(router, http.MethodPost, "/path")49 assert.Equal(t, http.StatusInternalServerError, w.Code)50 assert.Equal(t, "hello", w.Body.String())5152 w = PerformRequest(router, "GET", "/path2")52 w = PerformRequest(router, http.MethodGet, "/path2")53 assert.Equal(t, http.StatusBadRequest, w.Code)54 assert.Equal(t, "hola!", w.Body.String())55}56
61 unmodified lines
118 router.GET("/", Bind(bindTestStruct{}), func(c *Context) {119 called = true120 value = c.MustGet(BindKey).(*bindTestStruct)121 })122 PerformRequest(router, "GET", "/?foo=hola&bar=10")122 PerformRequest(router, http.MethodGet, "/?foo=hola&bar=10")123 assert.True(t, called)124 assert.Equal(t, "hola", value.Foo)125 assert.Equal(t, 10, value.Bar)126127 called = false128 PerformRequest(router, "GET", "/?foo=hola&bar=1")128 PerformRequest(router, http.MethodGet, "/?foo=hola&bar=1")129 assert.False(t, called)130131 assert.Panics(t, func() {132 Bind(&bindTestStruct{})
18 unmodified lines