How to use Request method of http Package

Best K6 code snippet using http.Request

players_controller_test.go

Source:players_controller_test.go Github

copy

Full Screen

...17func TestGetAllPlayers(t *testing.T) {18 appcontext.Current.Add(appcontext.Logger, test.InitMockLogger)19 appcontext.Current.Add(appcontext.MongoRepository, test.InitMongoMock)20 e := echo.New()21 req := httptest.NewRequest(http.MethodGet, "/", nil)22 rec := httptest.NewRecorder()23 c := e.NewContext(req, rec)24 c.SetPath("/player")25 // Assertions26 if assert.NoError(t, GetAllPlayers(c)) {27 assert.Equal(t, http.StatusOK, rec.Code)28 }29}30func TestGetOnePlayer(t *testing.T) {31 appcontext.Current.Add(appcontext.Logger, test.InitMockLogger)32 appcontext.Current.Add(appcontext.MongoRepository, test.InitMongoMock)33 e := echo.New()34 req := httptest.NewRequest(http.MethodGet, "/", nil)35 rec := httptest.NewRecorder()36 c := e.NewContext(req, rec)37 c.SetPath("/player/:id")38 c.SetParamNames("id")39 c.SetParamValues("5e70e4c5d2f3f777c16b29f7")40 // Assertions41 if assert.NoError(t, GetOnePlayer(c)) {42 assert.Equal(t, http.StatusOK, rec.Code)43 }44 req1 := httptest.NewRequest(http.MethodGet, "/", nil)45 rec1 := httptest.NewRecorder()46 c1 := e.NewContext(req1, rec1)47 c1.SetPath("/player/:id")48 c1.SetParamNames("id")49 c1.SetParamValues("5e70e4c5d2f3f777c16b29f8")50 if assert.NoError(t, GetOnePlayer(c1)) {51 assert.Equal(t, http.StatusUnprocessableEntity, rec1.Code)52 }53 req2 := httptest.NewRequest(http.MethodGet, "/", nil)54 rec2 := httptest.NewRecorder()55 c2 := e.NewContext(req2, rec2)56 c2.SetPath("/player/:id")57 c2.SetParamNames("id")58 c2.SetParamValues("BLA")59 if assert.NoError(t, GetOnePlayer(c2)) {60 assert.Equal(t, http.StatusBadRequest, rec2.Code)61 }62}63func TestPostPlayer(t *testing.T) {64 appcontext.Current.Add(appcontext.Dice, test.InitDiceMock)65 appcontext.Current.Add(appcontext.Logger, test.InitMockLogger)66 appcontext.Current.Add(appcontext.MongoRepository, test.InitMongoMock)67 e := echo.New()68 example := "{\"key\":\"value\"}"69 requestByte, _ := json.Marshal(example)70 requestReader := bytes.NewReader(requestByte)71 req := httptest.NewRequest(http.MethodPost, "/", requestReader)72 req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)73 rec := httptest.NewRecorder()74 c := e.NewContext(req, rec)75 c.SetPath("/player")76 // Assertions77 if assert.NoError(t, PostPlayer(c)) {78 assert.Equal(t, http.StatusBadRequest, rec.Code)79 }80 // example1 := player.Players{}81 // example1.AdventureID = "BLA"82 // requestByte1, _ := json.Marshal(example1)83 // requestReader1 := bytes.NewReader(requestByte1)84 // req1 := httptest.NewRequest(http.MethodPost, "/", requestReader1)85 // req1.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)86 // rec1 := httptest.NewRecorder()87 // c1 := e.NewContext(req1, rec1)88 // c1.SetPath("/player")89 // // Assertions90 // if assert.NoError(t, PostPlayer(c1)) {91 // assert.Equal(t, http.StatusBadRequest, rec1.Code)92 // }93 // example2 := player.Players{}94 // requestByte2, _ := json.Marshal(example2)95 // requestReader2 := bytes.NewReader(requestByte2)96 // req2 := httptest.NewRequest(http.MethodPost, "/", requestReader2)97 // req2.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)98 // rec2 := httptest.NewRecorder()99 // c2 := e.NewContext(req2, rec2)100 // c2.SetPath("/player")101 // // Assertions102 // if assert.NoError(t, PostPlayer(c2)) {103 // assert.Equal(t, http.StatusBadRequest, rec2.Code)104 // }105 example3 := player.Players{}106 requestByte3, _ := json.Marshal(example3)107 requestReader3 := bytes.NewReader(requestByte3)108 req3 := httptest.NewRequest(http.MethodPost, "/", requestReader3)109 req3.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)110 rec3 := httptest.NewRecorder()111 c3 := e.NewContext(req3, rec3)112 c3.SetPath("/player")113 // Assertions114 if assert.NoError(t, PostPlayer(c3)) {115 assert.Equal(t, http.StatusOK, rec3.Code)116 }117 // example4 := player.Players{}118 // requestByte4, _ := json.Marshal(example4)119 // requestReader4 := bytes.NewReader(requestByte4)120 // req4 := httptest.NewRequest(http.MethodPost, "/", requestReader4)121 // req4.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)122 // rec4 := httptest.NewRecorder()123 // c4 := e.NewContext(req4, rec4)124 // c4.SetPath("/player")125 // // Assertions126 // if assert.NoError(t, PostPlayer(c4)) {127 // assert.Equal(t, http.StatusBadRequest, rec4.Code)128 // }129}130func TestUpdateOnePlayer(t *testing.T) {131 appcontext.Current.Add(appcontext.Logger, test.InitMockLogger)132 appcontext.Current.Add(appcontext.MongoRepository, test.InitMongoMock)133 e := echo.New()134 example := "{\"key\":\"value\"}"135 requestByte, _ := json.Marshal(example)136 requestReader := bytes.NewReader(requestByte)137 req := httptest.NewRequest(http.MethodPut, "/", requestReader)138 req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)139 rec := httptest.NewRecorder()140 c := e.NewContext(req, rec)141 c.SetPath("/player")142 // Assertions143 if assert.NoError(t, UpdateOnePlayer(c)) {144 assert.Equal(t, http.StatusBadRequest, rec.Code)145 }146 // example1 := player.Players{}147 // requestByte1, _ := json.Marshal(example1)148 // requestReader1 := bytes.NewReader(requestByte1)149 // req1 := httptest.NewRequest(http.MethodPut, "/", requestReader1)150 // req1.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)151 // rec1 := httptest.NewRecorder()152 // c1 := e.NewContext(req1, rec1)153 // c1.SetPath("/player")154 // // Assertions155 // if assert.NoError(t, UpdateOnePlayer(c1)) {156 // assert.Equal(t, http.StatusBadRequest, rec1.Code)157 // }158 // example2 := player.Players{}159 // requestByte2, _ := json.Marshal(example2)160 // requestReader2 := bytes.NewReader(requestByte2)161 // req2 := httptest.NewRequest(http.MethodPut, "/", requestReader2)162 // req2.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)163 // rec2 := httptest.NewRecorder()164 // c2 := e.NewContext(req2, rec2)165 // c2.SetPath("/player")166 // // Assertions167 // if assert.NoError(t, UpdateOnePlayer(c2)) {168 // assert.Equal(t, http.StatusBadRequest, rec2.Code)169 // }170 example3 := player.Players{}171 requestByte3, _ := json.Marshal(example3)172 requestReader3 := bytes.NewReader(requestByte3)173 req3 := httptest.NewRequest(http.MethodPut, "/", requestReader3)174 req3.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)175 rec3 := httptest.NewRecorder()176 c3 := e.NewContext(req3, rec3)177 c3.SetPath("/player")178 // Assertions179 if assert.NoError(t, UpdateOnePlayer(c3)) {180 assert.Equal(t, http.StatusOK, rec3.Code)181 }182 config.Values.RuleBuiltin = false183 example4 := player.Players{}184 requestByte4, _ := json.Marshal(example4)185 requestReader4 := bytes.NewReader(requestByte4)186 req4 := httptest.NewRequest(http.MethodPut, "/", requestReader4)187 req4.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)188 rec4 := httptest.NewRecorder()189 c4 := e.NewContext(req4, rec4)190 c4.SetPath("/player")191 // Assertions192 if assert.NoError(t, UpdateOnePlayer(c4)) {193 assert.Equal(t, http.StatusOK, rec4.Code)194 }195}196func TestDeletePlayer(t *testing.T) {197 e := echo.New()198 req := httptest.NewRequest(http.MethodDelete, "/", nil)199 rec := httptest.NewRecorder()200 c := e.NewContext(req, rec)201 c.SetPath("/player/:id")202 c.SetParamNames("id")203 c.SetParamValues("5e70e4c5d2f3f777c16b29f7")204 // Assertions205 if assert.NoError(t, DeletePlayer(c)) {206 assert.Equal(t, http.StatusOK, rec.Code)207 }208 req1 := httptest.NewRequest(http.MethodDelete, "/", nil)209 rec1 := httptest.NewRecorder()210 c1 := e.NewContext(req1, rec1)211 c1.SetPath("/player/:id")212 c1.SetParamNames("id")213 c1.SetParamValues("BLA")214 // Assertions215 if assert.NoError(t, DeletePlayer(c1)) {216 assert.Equal(t, http.StatusBadRequest, rec1.Code)217 }218 //219 req2 := httptest.NewRequest(http.MethodDelete, "/", nil)220 rec2 := httptest.NewRecorder()221 c2 := e.NewContext(req2, rec2)222 c2.SetPath("/player/:id")223 c2.SetParamNames("id")224 c2.SetParamValues("5e70e4c5d2f3f777c16b29f8")225 // Assertions226 if assert.NoError(t, DeletePlayer(c2)) {227 assert.Equal(t, http.StatusBadRequest, rec2.Code)228 }229}230func TestAddCampaignToPlayer(t *testing.T) {231 appcontext.Current.Add(appcontext.Logger, test.InitMockLogger)232 appcontext.Current.Add(appcontext.MongoRepository, test.InitMongoMock)233 e := echo.New()234 example := player.AddCampaign{}235 requestByte, _ := json.Marshal(example)236 requestReader := bytes.NewReader(requestByte)237 req := httptest.NewRequest(http.MethodPost, "/", requestReader)238 req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)239 rec := httptest.NewRecorder()240 c := e.NewContext(req, rec)241 c.SetPath("/player/:id/campaign")242 c.SetParamNames("id")243 c.SetParamValues("BLA")244 // Assertions245 if assert.NoError(t, AddCampaignToPlayer(c)) {246 assert.Equal(t, http.StatusBadRequest, rec.Code)247 }248 example1 := player.AddCampaign{}249 requestByte1, _ := json.Marshal(example1)250 requestReader1 := bytes.NewReader(requestByte1)251 req1 := httptest.NewRequest(http.MethodPost, "/", requestReader1)252 req1.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)253 rec1 := httptest.NewRecorder()254 c1 := e.NewContext(req1, rec1)255 c1.SetPath("/player/:id/campaign")256 c1.SetParamNames("id")257 c1.SetParamValues("5e70e4c5d2f3f777c16b29f8")258 // Assertions259 if assert.NoError(t, AddCampaignToPlayer(c1)) {260 assert.Equal(t, http.StatusBadRequest, rec1.Code)261 }262 example2 := "{\"key\":\"value\"}"263 requestByte2, _ := json.Marshal(example2)264 requestReader2 := bytes.NewReader(requestByte2)265 req2 := httptest.NewRequest(http.MethodPost, "/", requestReader2)266 req2.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)267 rec2 := httptest.NewRecorder()268 c2 := e.NewContext(req2, rec2)269 c2.SetPath("/player/:id/campaign")270 c2.SetParamNames("id")271 c2.SetParamValues("5e70e4c5d2f3f777c16b29f6")272 // Assertions273 if assert.NoError(t, AddCampaignToPlayer(c2)) {274 assert.Equal(t, http.StatusBadRequest, rec2.Code)275 }276 example3 := player.AddCampaign{}277 requestByte3, _ := json.Marshal(example3)278 requestReader3 := bytes.NewReader(requestByte3)279 req3 := httptest.NewRequest(http.MethodPost, "/", requestReader3)280 req3.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)281 rec3 := httptest.NewRecorder()282 c3 := e.NewContext(req3, rec3)283 c3.SetPath("/player/:id/campaign")284 c3.SetParamNames("id")285 c3.SetParamValues("5e70e4c5d2f3f777c16b29f6")286 // Assertions287 if assert.NoError(t, AddCampaignToPlayer(c3)) {288 assert.Equal(t, http.StatusOK, rec3.Code)289 }290}291func TestAddOrRemoveHP(t *testing.T) {292 appcontext.Current.Add(appcontext.Logger, test.InitMockLogger)293 appcontext.Current.Add(appcontext.MongoRepository, test.InitMongoMock)294 e := echo.New()295 req := httptest.NewRequest(http.MethodPut, "/", nil)296 req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)297 rec := httptest.NewRecorder()298 c := e.NewContext(req, rec)299 c.SetPath("/player/:id/hp/:action/:value")300 c.SetParamNames("id", "action", "value")301 c.SetParamValues("BLA", "add", "10")302 // Assertions303 if assert.NoError(t, AddOrRemoveHP(c)) {304 assert.Equal(t, http.StatusBadRequest, rec.Code)305 }306 req1 := httptest.NewRequest(http.MethodPut, "/", nil)307 req1.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)308 rec1 := httptest.NewRecorder()309 c1 := e.NewContext(req1, rec1)310 c1.SetPath("/player/:id/hp/:action/:value")311 c1.SetParamNames("id", "action", "value")312 c1.SetParamValues("5e70e4c5d2f3f777c16b29f8", "add", "10")313 // Assertions314 if assert.NoError(t, AddOrRemoveHP(c1)) {315 assert.Equal(t, http.StatusBadRequest, rec1.Code)316 }317 req2 := httptest.NewRequest(http.MethodPut, "/", nil)318 req2.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)319 rec2 := httptest.NewRecorder()320 c2 := e.NewContext(req2, rec2)321 c2.SetPath("/player/:id/hp/:action/:value")322 c2.SetParamNames("id", "action", "value")323 c2.SetParamValues("5e70e4c5d2f3f777c16b29f6", "delete", "10")324 // Assertions325 if assert.NoError(t, AddOrRemoveHP(c2)) {326 assert.Equal(t, http.StatusBadRequest, rec2.Code)327 }328 req3 := httptest.NewRequest(http.MethodPut, "/", nil)329 req3.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)330 rec3 := httptest.NewRecorder()331 c3 := e.NewContext(req3, rec3)332 c3.SetPath("/player/:id/hp/:action/:value")333 c3.SetParamNames("id", "action", "value")334 c3.SetParamValues("5e70e4c5d2f3f777c16b29f6", "add", "third")335 // Assertions336 if assert.NoError(t, AddOrRemoveHP(c3)) {337 assert.Equal(t, http.StatusBadRequest, rec3.Code)338 }339 req4 := httptest.NewRequest(http.MethodPut, "/", nil)340 req4.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)341 rec4 := httptest.NewRecorder()342 c4 := e.NewContext(req4, rec4)343 c4.SetPath("/player/:id/hp/:action/:value")344 c4.SetParamNames("id", "action", "value")345 c4.SetParamValues("5e70e4c5d2f3f777c16b29f6", "add", "10")346 // Assertions347 if assert.NoError(t, AddOrRemoveHP(c4)) {348 assert.Equal(t, http.StatusOK, rec4.Code)349 }350}351func TestAddPlayerXP(t *testing.T) {352 appcontext.Current.Add(appcontext.Logger, test.InitMockLogger)353 appcontext.Current.Add(appcontext.MongoRepository, test.InitMongoMock)354 e := echo.New()355 req := httptest.NewRequest(http.MethodPut, "/", nil)356 req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)357 rec := httptest.NewRecorder()358 c := e.NewContext(req, rec)359 c.SetPath("/player/:id/xp/:value")360 c.SetParamNames("id", "value")361 c.SetParamValues("BLA", "10")362 // Assertions363 if assert.NoError(t, AddPlayerXP(c)) {364 assert.Equal(t, http.StatusBadRequest, rec.Code)365 }366 req1 := httptest.NewRequest(http.MethodPut, "/", nil)367 req1.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)368 rec1 := httptest.NewRecorder()369 c1 := e.NewContext(req1, rec1)370 c1.SetPath("/player/:id/xp/:value")371 c1.SetParamNames("id", "value")372 c1.SetParamValues("5e70e4c5d2f3f777c16b29f8", "10")373 // Assertions374 if assert.NoError(t, AddPlayerXP(c1)) {375 assert.Equal(t, http.StatusBadRequest, rec1.Code)376 }377 req2 := httptest.NewRequest(http.MethodPut, "/", nil)378 req2.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)379 rec2 := httptest.NewRecorder()380 c2 := e.NewContext(req2, rec2)381 c2.SetPath("/player/:id/xp/:value")382 c2.SetParamNames("id", "value")383 c2.SetParamValues("5e70e4c5d2f3f777c16b29f6", "third")384 // Assertions385 if assert.NoError(t, AddPlayerXP(c2)) {386 assert.Equal(t, http.StatusBadRequest, rec2.Code)387 }388 req3 := httptest.NewRequest(http.MethodPut, "/", nil)389 req3.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)390 rec3 := httptest.NewRecorder()391 c3 := e.NewContext(req3, rec3)392 c3.SetPath("/player/:id/xp/:value")393 c3.SetParamNames("id", "value")394 c3.SetParamValues("5e70e4c5d2f3f777c16b29f6", "100")395 // Assertions396 if assert.NoError(t, AddPlayerXP(c3)) {397 assert.Equal(t, http.StatusOK, rec3.Code)398 }399 // req4 := httptest.NewRequest(http.MethodPut, "/", nil)400 // req4.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)401 // rec4 := httptest.NewRecorder()402 // c4 := e.NewContext(req4, rec4)403 // c4.SetPath("/player/:id/xp/:value")404 // c4.SetParamNames("id", "value")405 // c4.SetParamValues("5e70e4c5d2f3f777c16b29f6", "10")406 // // Assertions407 // if assert.NoError(t, AddPlayerXP(c4)) {408 // assert.Equal(t, http.StatusOK, rec4.Code)409 // }410}411func TestUseSpellByLevel(t *testing.T) {412 //413 appcontext.Current.Add(appcontext.Logger, test.InitMockLogger)414 appcontext.Current.Add(appcontext.MongoRepository, test.InitMongoMock)415 e := echo.New()416 req := httptest.NewRequest(http.MethodPut, "/", nil)417 req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)418 rec := httptest.NewRecorder()419 c := e.NewContext(req, rec)420 c.SetPath("/player/:id/spell/:level/:value")421 c.SetParamNames("id", "level", "value")422 c.SetParamValues("BLA", "1", "1")423 // Assertions424 if assert.NoError(t, UseSpellByLevel(c)) {425 assert.Equal(t, http.StatusBadRequest, rec.Code)426 }427 req1 := httptest.NewRequest(http.MethodPut, "/", nil)428 req1.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)429 rec1 := httptest.NewRecorder()430 c1 := e.NewContext(req1, rec1)431 c1.SetPath("/player/:id/spell/:level/:value")432 c1.SetParamNames("id", "level", "value")433 c1.SetParamValues("5e70e4c5d2f3f777c16b29f8", "1", "1")434 // Assertions435 if assert.NoError(t, UseSpellByLevel(c1)) {436 assert.Equal(t, http.StatusBadRequest, rec1.Code)437 }438 req2 := httptest.NewRequest(http.MethodPut, "/", nil)439 req2.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)440 rec2 := httptest.NewRecorder()441 c2 := e.NewContext(req2, rec2)442 c2.SetPath("/player/:id/spell/:level/:value")443 c2.SetParamNames("id", "level", "value")444 c2.SetParamValues("5e70e4c5d2f3f777c16b29f6", "10", "1")445 // Assertions446 if assert.NoError(t, UseSpellByLevel(c2)) {447 assert.Equal(t, http.StatusBadRequest, rec2.Code)448 }449 req3 := httptest.NewRequest(http.MethodPut, "/", nil)450 req3.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)451 rec3 := httptest.NewRecorder()452 c3 := e.NewContext(req3, rec3)453 c3.SetPath("/player/:id/spell/:level/:value")454 c3.SetParamNames("id", "level", "value")455 c3.SetParamValues("5e70e4c5d2f3f777c16b29f6", "1", "one")456 // Assertions457 if assert.NoError(t, UseSpellByLevel(c3)) {458 assert.Equal(t, http.StatusBadRequest, rec3.Code)459 }460 req4 := httptest.NewRequest(http.MethodPut, "/", nil)461 req4.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)462 rec4 := httptest.NewRecorder()463 c4 := e.NewContext(req4, rec4)464 c4.SetPath("/player/:id/spell/:level/:value")465 c4.SetParamNames("id", "level", "value")466 c4.SetParamValues("5e70e4c5d2f3f777c16b29f6", "1", "1")467 // Assertions468 if assert.NoError(t, UseSpellByLevel(c4)) {469 assert.Equal(t, http.StatusOK, rec4.Code)470 }471}472func TestFullRestPlayer(t *testing.T) {473 appcontext.Current.Add(appcontext.Logger, test.InitMockLogger)474 appcontext.Current.Add(appcontext.MongoRepository, test.InitMongoMock)475 e := echo.New()476 req := httptest.NewRequest(http.MethodPut, "/", nil)477 req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)478 rec := httptest.NewRecorder()479 c := e.NewContext(req, rec)480 c.SetPath("/player/:id/fullrest")481 c.SetParamNames("id")482 c.SetParamValues("BLA")483 // Assertions484 if assert.NoError(t, FullRestPlayer(c)) {485 assert.Equal(t, http.StatusBadRequest, rec.Code)486 }487 req1 := httptest.NewRequest(http.MethodPut, "/", nil)488 req1.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)489 rec1 := httptest.NewRecorder()490 c1 := e.NewContext(req1, rec1)491 c1.SetPath("/player/:id/fullrest")492 c1.SetParamNames("id")493 c1.SetParamValues("5e70e4c5d2f3f777c16b29f8")494 // Assertions495 if assert.NoError(t, FullRestPlayer(c1)) {496 assert.Equal(t, http.StatusBadRequest, rec1.Code)497 }498 req2 := httptest.NewRequest(http.MethodPut, "/", nil)499 req2.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)500 rec2 := httptest.NewRecorder()501 c2 := e.NewContext(req2, rec2)502 c2.SetPath("/player/:id/fullrest")503 c2.SetParamNames("id")504 c2.SetParamValues("5e70e4c5d2f3f777c16b29f6")505 // Assertions506 if assert.NoError(t, FullRestPlayer(c2)) {507 assert.Equal(t, http.StatusOK, rec2.Code)508 }509 // req3 := httptest.NewRequest(http.MethodPut, "/", nil)510 // req3.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)511 // rec3 := httptest.NewRecorder()512 // c3 := e.NewContext(req3, rec3)513 // c3.SetPath("/player/:id/fullrest")514 // c3.SetParamNames("id", "value")515 // c3.SetParamValues("5e70e4c5d2f3f777c16b29f6", "100")516 // // Assertions517 // if assert.NoError(t, FullRestPlayer(c3)) {518 // assert.Equal(t, http.StatusOK, rec3.Code)519 // }520}521func TestChangeCondition(t *testing.T) {522 appcontext.Current.Add(appcontext.Logger, test.InitMockLogger)523 appcontext.Current.Add(appcontext.MongoRepository, test.InitMongoMock)524 e := echo.New()525 // player.Condition526 example := player.Condition{}527 requestByte, _ := json.Marshal(example)528 requestReader := bytes.NewReader(requestByte)529 req := httptest.NewRequest(http.MethodPost, "/", requestReader)530 req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)531 rec := httptest.NewRecorder()532 c := e.NewContext(req, rec)533 c.SetPath("/player/:id/condition")534 c.SetParamNames("id")535 c.SetParamValues("BLA")536 // Assertions537 if assert.NoError(t, ChangeCondition(c)) {538 assert.Equal(t, http.StatusBadRequest, rec.Code)539 }540 example1 := player.Condition{}541 requestByte1, _ := json.Marshal(example1)542 requestReader1 := bytes.NewReader(requestByte1)543 req1 := httptest.NewRequest(http.MethodPost, "/", requestReader1)544 req1.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)545 rec1 := httptest.NewRecorder()546 c1 := e.NewContext(req1, rec1)547 c1.SetPath("/player/:id/condition")548 c1.SetParamNames("id")549 c1.SetParamValues("5e70e4c5d2f3f777c16b29f8")550 // Assertions551 if assert.NoError(t, ChangeCondition(c1)) {552 assert.Equal(t, http.StatusBadRequest, rec1.Code)553 }554 example2 := "{\"key\":\"value\"}"555 requestByte2, _ := json.Marshal(example2)556 requestReader2 := bytes.NewReader(requestByte2)557 req2 := httptest.NewRequest(http.MethodPost, "/", requestReader2)558 req2.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)559 rec2 := httptest.NewRecorder()560 c2 := e.NewContext(req2, rec2)561 c2.SetPath("/player/:id/condition")562 c2.SetParamNames("id")563 c2.SetParamValues("5e70e4c5d2f3f777c16b29f6")564 // Assertions565 if assert.NoError(t, ChangeCondition(c2)) {566 assert.Equal(t, http.StatusBadRequest, rec2.Code)567 }568 example3 := player.Condition{}569 requestByte3, _ := json.Marshal(example3)570 requestReader3 := bytes.NewReader(requestByte3)571 req3 := httptest.NewRequest(http.MethodPost, "/", requestReader3)572 req3.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)573 rec3 := httptest.NewRecorder()574 c3 := e.NewContext(req3, rec3)575 c3.SetPath("/player/:id/condition")576 c3.SetParamNames("id")577 c3.SetParamValues("5e70e4c5d2f3f777c16b29f6")578 // Assertions579 if assert.NoError(t, ChangeCondition(c3)) {580 assert.Equal(t, http.StatusOK, rec3.Code)581 }582}583func TestAddTreasure(t *testing.T) {584 appcontext.Current.Add(appcontext.Logger, test.InitMockLogger)585 appcontext.Current.Add(appcontext.MongoRepository, test.InitMongoMock)586 e := echo.New()587 example := player.Treasure{}588 requestByte, _ := json.Marshal(example)589 requestReader := bytes.NewReader(requestByte)590 req := httptest.NewRequest(http.MethodPost, "/", requestReader)591 req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)592 rec := httptest.NewRecorder()593 c := e.NewContext(req, rec)594 c.SetPath("/player/:id/treasure")595 c.SetParamNames("id")596 c.SetParamValues("BLA")597 // Assertions598 if assert.NoError(t, AddTreasure(c)) {599 assert.Equal(t, http.StatusBadRequest, rec.Code)600 }601 example1 := player.Treasure{}602 requestByte1, _ := json.Marshal(example1)603 requestReader1 := bytes.NewReader(requestByte1)604 req1 := httptest.NewRequest(http.MethodPost, "/", requestReader1)605 req1.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)606 rec1 := httptest.NewRecorder()607 c1 := e.NewContext(req1, rec1)608 c1.SetPath("/player/:id/treasure")609 c1.SetParamNames("id")610 c1.SetParamValues("5e70e4c5d2f3f777c16b29f8")611 // Assertions612 if assert.NoError(t, AddTreasure(c1)) {613 assert.Equal(t, http.StatusBadRequest, rec1.Code)614 }615 example2 := "{\"key\":\"value\"}"616 requestByte2, _ := json.Marshal(example2)617 requestReader2 := bytes.NewReader(requestByte2)618 req2 := httptest.NewRequest(http.MethodPost, "/", requestReader2)619 req2.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)620 rec2 := httptest.NewRecorder()621 c2 := e.NewContext(req2, rec2)622 c2.SetPath("/player/:id/treasure")623 c2.SetParamNames("id")624 c2.SetParamValues("5e70e4c5d2f3f777c16b29f6")625 // Assertions626 if assert.NoError(t, AddTreasure(c2)) {627 assert.Equal(t, http.StatusBadRequest, rec2.Code)628 }629 example3 := player.Treasure{}630 requestByte3, _ := json.Marshal(example3)631 requestReader3 := bytes.NewReader(requestByte3)632 req3 := httptest.NewRequest(http.MethodPost, "/", requestReader3)633 req3.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)634 rec3 := httptest.NewRecorder()635 c3 := e.NewContext(req3, rec3)636 c3.SetPath("/player/:id/treasure")637 c3.SetParamNames("id")638 c3.SetParamValues("5e70e4c5d2f3f777c16b29f9")639 // Assertions640 if assert.NoError(t, AddTreasure(c3)) {641 assert.Equal(t, http.StatusBadRequest, rec3.Code)642 }643 example4 := player.Treasure{}644 requestByte4, _ := json.Marshal(example4)645 requestReader4 := bytes.NewReader(requestByte4)646 req4 := httptest.NewRequest(http.MethodPost, "/", requestReader4)647 req4.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)648 rec4 := httptest.NewRecorder()649 c4 := e.NewContext(req4, rec4)650 c4.SetPath("/player/:id/treasure")651 c4.SetParamNames("id")652 c4.SetParamValues("5e70e4c5d2f3f777c16b29f6")653 // Assertions654 if assert.NoError(t, AddTreasure(c4)) {655 assert.Equal(t, http.StatusOK, rec4.Code)656 }657}658func TestAddOrRemoveOtherItems(t *testing.T) {659 appcontext.Current.Add(appcontext.Logger, test.InitMockLogger)660 appcontext.Current.Add(appcontext.MongoRepository, test.InitMongoMock)661 e := echo.New()662 example := rule.SimpleList{}663 requestByte, _ := json.Marshal(example)664 requestReader := bytes.NewReader(requestByte)665 req := httptest.NewRequest(http.MethodPost, "/", requestReader)666 req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)667 rec := httptest.NewRecorder()668 c := e.NewContext(req, rec)669 c.SetPath("/player/:id/items/:action")670 c.SetParamNames("id", "action")671 c.SetParamValues("BLA", "add")672 // Assertions673 if assert.NoError(t, AddOrRemoveOtherItems(c)) {674 assert.Equal(t, http.StatusBadRequest, rec.Code)675 }676 example1 := rule.SimpleList{}677 requestByte1, _ := json.Marshal(example1)678 requestReader1 := bytes.NewReader(requestByte1)679 req1 := httptest.NewRequest(http.MethodPost, "/", requestReader1)680 req1.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)681 rec1 := httptest.NewRecorder()682 c1 := e.NewContext(req1, rec1)683 c1.SetPath("/player/:id/items/:action")684 c1.SetParamNames("id", "action")685 c1.SetParamValues("5e70e4c5d2f3f777c16b29f8", "add")686 // Assertions687 if assert.NoError(t, AddOrRemoveOtherItems(c1)) {688 assert.Equal(t, http.StatusBadRequest, rec1.Code)689 }690 example2 := "{\"key\":\"value\"}"691 requestByte2, _ := json.Marshal(example2)692 requestReader2 := bytes.NewReader(requestByte2)693 req2 := httptest.NewRequest(http.MethodPost, "/", requestReader2)694 req2.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)695 rec2 := httptest.NewRecorder()696 c2 := e.NewContext(req2, rec2)697 c2.SetPath("/player/:id/items/:action")698 c2.SetParamNames("id", "action")699 c2.SetParamValues("5e70e4c5d2f3f777c16b29f6", "add")700 // Assertions701 if assert.NoError(t, AddOrRemoveOtherItems(c2)) {702 assert.Equal(t, http.StatusBadRequest, rec2.Code)703 }704 example3 := rule.SimpleList{}705 requestByte3, _ := json.Marshal(example3)706 requestReader3 := bytes.NewReader(requestByte3)707 req3 := httptest.NewRequest(http.MethodPost, "/", requestReader3)708 req3.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)709 rec3 := httptest.NewRecorder()710 c3 := e.NewContext(req3, rec3)711 c3.SetPath("/player/:id/items/:action")712 c3.SetParamNames("id", "action")713 c3.SetParamValues("5e70e4c5d2f3f777c16b29f6", "delete")714 // Assertions715 if assert.NoError(t, AddOrRemoveOtherItems(c3)) {716 assert.Equal(t, http.StatusBadRequest, rec3.Code)717 }718 example4 := rule.SimpleList{}719 requestByte4, _ := json.Marshal(example4)720 requestReader4 := bytes.NewReader(requestByte4)721 req4 := httptest.NewRequest(http.MethodPost, "/", requestReader4)722 req4.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)723 rec4 := httptest.NewRecorder()724 c4 := e.NewContext(req4, rec4)725 c4.SetPath("/player/:id/items/:action")726 c4.SetParamNames("id", "action")727 c4.SetParamValues("5e70e4c5d2f3f777c16b29f9", "add")728 // Assertions729 if assert.NoError(t, AddOrRemoveOtherItems(c4)) {730 assert.Equal(t, http.StatusBadRequest, rec4.Code)731 }732 example5 := rule.SimpleList{}733 requestByte5, _ := json.Marshal(example5)734 requestReader5 := bytes.NewReader(requestByte5)735 req5 := httptest.NewRequest(http.MethodPost, "/", requestReader5)736 req5.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)737 rec5 := httptest.NewRecorder()738 c5 := e.NewContext(req5, rec5)739 c5.SetPath("/player/:id/items/:action")740 c5.SetParamNames("id", "action")741 c5.SetParamValues("5e70e4c5d2f3f777c16b29f6", "add")742 // Assertions743 if assert.NoError(t, AddOrRemoveOtherItems(c5)) {744 assert.Equal(t, http.StatusOK, rec5.Code)745 }746}747func TestAddArmorWeaponPlayerByID(t *testing.T) {748 appcontext.Current.Add(appcontext.Logger, test.InitMockLogger)749 appcontext.Current.Add(appcontext.MongoRepository, test.InitMongoMock)750 e := echo.New()751 example := player.Armory{}752 requestByte, _ := json.Marshal(example)753 requestReader := bytes.NewReader(requestByte)754 req := httptest.NewRequest(http.MethodPost, "/", requestReader)755 req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)756 rec := httptest.NewRecorder()757 c := e.NewContext(req, rec)758 c.SetPath("/player/:id/armory")759 c.SetParamNames("id")760 c.SetParamValues("BLA")761 // Assertions762 if assert.NoError(t, AddArmorWeaponPlayerByID(c)) {763 assert.Equal(t, http.StatusBadRequest, rec.Code)764 }765 example1 := player.Armory{}766 requestByte1, _ := json.Marshal(example1)767 requestReader1 := bytes.NewReader(requestByte1)768 req1 := httptest.NewRequest(http.MethodPost, "/", requestReader1)769 req1.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)770 rec1 := httptest.NewRecorder()771 c1 := e.NewContext(req1, rec1)772 c1.SetPath("/player/:id/armory")773 c1.SetParamNames("id")774 c1.SetParamValues("5e70e4c5d2f3f777c16b29f8")775 // Assertions776 if assert.NoError(t, AddArmorWeaponPlayerByID(c1)) {777 assert.Equal(t, http.StatusBadRequest, rec1.Code)778 }779 example2 := "{\"key\":\"value\"}"780 requestByte2, _ := json.Marshal(example2)781 requestReader2 := bytes.NewReader(requestByte2)782 req2 := httptest.NewRequest(http.MethodPost, "/", requestReader2)783 req2.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)784 rec2 := httptest.NewRecorder()785 c2 := e.NewContext(req2, rec2)786 c2.SetPath("/player/:id/armory")787 c2.SetParamNames("id")788 c2.SetParamValues("5e70e4c5d2f3f777c16b29f6")789 // Assertions790 if assert.NoError(t, AddArmorWeaponPlayerByID(c2)) {791 assert.Equal(t, http.StatusBadRequest, rec2.Code)792 }793 example3 := player.Armory{}794 requestByte3, _ := json.Marshal(example3)795 requestReader3 := bytes.NewReader(requestByte3)796 req3 := httptest.NewRequest(http.MethodPost, "/", requestReader3)797 req3.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)798 rec3 := httptest.NewRecorder()799 c3 := e.NewContext(req3, rec3)800 c3.SetPath("/player/:id/armory")801 c3.SetParamNames("id")802 c3.SetParamValues("5e70e4c5d2f3f777c16b29f9")803 // Assertions804 if assert.NoError(t, AddArmorWeaponPlayerByID(c3)) {805 assert.Equal(t, http.StatusBadRequest, rec3.Code)806 }807 example4 := player.Armory{}808 requestByte4, _ := json.Marshal(example4)809 requestReader4 := bytes.NewReader(requestByte4)810 req4 := httptest.NewRequest(http.MethodPost, "/", requestReader4)811 req4.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)812 rec4 := httptest.NewRecorder()813 c4 := e.NewContext(req4, rec4)814 c4.SetPath("/player/:id/armory")815 c4.SetParamNames("id")816 c4.SetParamValues("5e70e4c5d2f3f777c16b29f6")817 // Assertions818 if assert.NoError(t, AddArmorWeaponPlayerByID(c4)) {819 assert.Equal(t, http.StatusOK, rec4.Code)820 }821}822func TestAddOrRemoveMagicItems(t *testing.T) {823 appcontext.Current.Add(appcontext.Logger, test.InitMockLogger)824 appcontext.Current.Add(appcontext.MongoRepository, test.InitMongoMock)825 e := echo.New()826 example := rule.SimpleList{}827 requestByte, _ := json.Marshal(example)828 requestReader := bytes.NewReader(requestByte)829 req := httptest.NewRequest(http.MethodPost, "/", requestReader)830 req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)831 rec := httptest.NewRecorder()832 c := e.NewContext(req, rec)833 c.SetPath("/player/:id/magicitems/:action")834 c.SetParamNames("id", "action")835 c.SetParamValues("BLA", "add")836 // Assertions837 if assert.NoError(t, AddOrRemoveMagicItems(c)) {838 assert.Equal(t, http.StatusBadRequest, rec.Code)839 }840 example1 := rule.SimpleList{}841 requestByte1, _ := json.Marshal(example1)842 requestReader1 := bytes.NewReader(requestByte1)843 req1 := httptest.NewRequest(http.MethodPost, "/", requestReader1)844 req1.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)845 rec1 := httptest.NewRecorder()846 c1 := e.NewContext(req1, rec1)847 c1.SetPath("/player/:id/magicitems/:action")848 c1.SetParamNames("id", "action")849 c1.SetParamValues("5e70e4c5d2f3f777c16b29f8", "add")850 // Assertions851 if assert.NoError(t, AddOrRemoveMagicItems(c1)) {852 assert.Equal(t, http.StatusBadRequest, rec1.Code)853 }854 example2 := "{\"key\":\"value\"}"855 requestByte2, _ := json.Marshal(example2)856 requestReader2 := bytes.NewReader(requestByte2)857 req2 := httptest.NewRequest(http.MethodPost, "/", requestReader2)858 req2.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)859 rec2 := httptest.NewRecorder()860 c2 := e.NewContext(req2, rec2)861 c2.SetPath("/player/:id/magicitems/:action")862 c2.SetParamNames("id", "action")863 c2.SetParamValues("5e70e4c5d2f3f777c16b29f6", "add")864 // Assertions865 if assert.NoError(t, AddOrRemoveMagicItems(c2)) {866 assert.Equal(t, http.StatusBadRequest, rec2.Code)867 }868 example3 := rule.SimpleList{}869 requestByte3, _ := json.Marshal(example3)870 requestReader3 := bytes.NewReader(requestByte3)871 req3 := httptest.NewRequest(http.MethodPost, "/", requestReader3)872 req3.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)873 rec3 := httptest.NewRecorder()874 c3 := e.NewContext(req3, rec3)875 c3.SetPath("/player/:id/magicitems/:action")876 c3.SetParamNames("id", "action")877 c3.SetParamValues("5e70e4c5d2f3f777c16b29f6", "delete")878 // Assertions879 if assert.NoError(t, AddOrRemoveMagicItems(c3)) {880 assert.Equal(t, http.StatusBadRequest, rec3.Code)881 }882 example4 := rule.SimpleList{}883 requestByte4, _ := json.Marshal(example4)884 requestReader4 := bytes.NewReader(requestByte4)885 req4 := httptest.NewRequest(http.MethodPost, "/", requestReader4)886 req4.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)887 rec4 := httptest.NewRecorder()888 c4 := e.NewContext(req4, rec4)889 c4.SetPath("/player/:id/magicitems/:action")890 c4.SetParamNames("id", "action")891 c4.SetParamValues("5e70e4c5d2f3f777c16b29f9", "add")892 // Assertions893 if assert.NoError(t, AddOrRemoveMagicItems(c4)) {894 assert.Equal(t, http.StatusBadRequest, rec4.Code)895 }896 example5 := rule.SimpleList{}897 requestByte5, _ := json.Marshal(example5)898 requestReader5 := bytes.NewReader(requestByte5)899 req5 := httptest.NewRequest(http.MethodPost, "/", requestReader5)900 req5.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)901 rec5 := httptest.NewRecorder()902 c5 := e.NewContext(req5, rec5)903 c5.SetPath("/player/:id/magicitems/:action")904 c5.SetParamNames("id", "action")905 c5.SetParamValues("5e70e4c5d2f3f777c16b29f6", "add")906 // Assertions907 if assert.NoError(t, AddOrRemoveMagicItems(c5)) {908 assert.Equal(t, http.StatusOK, rec5.Code)909 }910}...

Full Screen

Full Screen

request_test.rb

Source:request_test.rb Github

copy

Full Screen

1require 'abstract_unit'2class RequestTest < ActiveSupport::TestCase3 def setup4 ActionController::Base.relative_url_root = nil5 end6 def teardown7 ActionController::Base.relative_url_root = nil8 end9 def test_remote_ip10 request = stub_request 'REMOTE_ADDR' => '1.2.3.4'11 assert_equal '1.2.3.4', request.remote_ip12 request = stub_request 'REMOTE_ADDR' => '1.2.3.4,3.4.5.6'13 assert_equal '1.2.3.4', request.remote_ip14 request = stub_request 'REMOTE_ADDR' => '1.2.3.4',15 'HTTP_X_FORWARDED_FOR' => '3.4.5.6'16 assert_equal '1.2.3.4', request.remote_ip17 request = stub_request 'REMOTE_ADDR' => '127.0.0.1',18 'HTTP_X_FORWARDED_FOR' => '3.4.5.6'19 assert_equal '3.4.5.6', request.remote_ip20 request = stub_request 'HTTP_X_FORWARDED_FOR' => 'unknown,3.4.5.6'21 assert_equal '3.4.5.6', request.remote_ip22 request = stub_request 'HTTP_X_FORWARDED_FOR' => '172.16.0.1,3.4.5.6'23 assert_equal '3.4.5.6', request.remote_ip24 request = stub_request 'HTTP_X_FORWARDED_FOR' => '192.168.0.1,3.4.5.6'25 assert_equal '3.4.5.6', request.remote_ip26 request = stub_request 'HTTP_X_FORWARDED_FOR' => '10.0.0.1,3.4.5.6'27 assert_equal '3.4.5.6', request.remote_ip28 request = stub_request 'HTTP_X_FORWARDED_FOR' => '10.0.0.1, 10.0.0.1, 3.4.5.6'29 assert_equal '3.4.5.6', request.remote_ip30 request = stub_request 'HTTP_X_FORWARDED_FOR' => '127.0.0.1,3.4.5.6'31 assert_equal '3.4.5.6', request.remote_ip32 request = stub_request 'HTTP_X_FORWARDED_FOR' => 'unknown,192.168.0.1'33 assert_equal 'unknown', request.remote_ip34 request = stub_request 'HTTP_X_FORWARDED_FOR' => '9.9.9.9, 3.4.5.6, 10.0.0.1, 172.31.4.4'35 assert_equal '3.4.5.6', request.remote_ip36 request = stub_request 'HTTP_X_FORWARDED_FOR' => '1.1.1.1',37 'HTTP_CLIENT_IP' => '2.2.2.2'38 e = assert_raise(ActionController::ActionControllerError) {39 request.remote_ip40 }41 assert_match /IP spoofing attack/, e.message42 assert_match /HTTP_X_FORWARDED_FOR="1.1.1.1"/, e.message43 assert_match /HTTP_CLIENT_IP="2.2.2.2"/, e.message44 # turn IP Spoofing detection off.45 # This is useful for sites that are aimed at non-IP clients. The typical46 # example is WAP. Since the cellular network is not IP based, it's a47 # leap of faith to assume that their proxies are ever going to set the48 # HTTP_CLIENT_IP/HTTP_X_FORWARDED_FOR headers properly.49 ActionController::Base.ip_spoofing_check = false50 request = stub_request 'HTTP_X_FORWARDED_FOR' => '1.1.1.1',51 'HTTP_CLIENT_IP' => '2.2.2.2'52 assert_equal '2.2.2.2', request.remote_ip53 ActionController::Base.ip_spoofing_check = true54 request = stub_request 'HTTP_X_FORWARDED_FOR' => '8.8.8.8, 9.9.9.9'55 assert_equal '9.9.9.9', request.remote_ip56 end57 def test_domains58 request = stub_request 'HTTP_HOST' => 'www.rubyonrails.org'59 assert_equal "rubyonrails.org", request.domain60 request = stub_request 'HTTP_HOST' => "www.rubyonrails.co.uk"61 assert_equal "rubyonrails.co.uk", request.domain(2)62 request = stub_request 'HTTP_HOST' => "192.168.1.200"63 assert_nil request.domain64 request = stub_request 'HTTP_HOST' => "foo.192.168.1.200"65 assert_nil request.domain66 request = stub_request 'HTTP_HOST' => "192.168.1.200.com"67 assert_equal "200.com", request.domain68 end69 def test_subdomains70 request = stub_request 'HTTP_HOST' => "www.rubyonrails.org"71 assert_equal %w( www ), request.subdomains72 request = stub_request 'HTTP_HOST' => "www.rubyonrails.co.uk"73 assert_equal %w( www ), request.subdomains(2)74 request = stub_request 'HTTP_HOST' => "dev.www.rubyonrails.co.uk"75 assert_equal %w( dev www ), request.subdomains(2)76 request = stub_request 'HTTP_HOST' => "foobar.foobar.com"77 assert_equal %w( foobar ), request.subdomains78 request = stub_request 'HTTP_HOST' => "192.168.1.200"79 assert_equal [], request.subdomains80 request = stub_request 'HTTP_HOST' => "foo.192.168.1.200"81 assert_equal [], request.subdomains82 request = stub_request 'HTTP_HOST' => "192.168.1.200.com"83 assert_equal %w( 192 168 1 ), request.subdomains84 request = stub_request 'HTTP_HOST' => nil85 assert_equal [], request.subdomains86 end87 def test_port_string88 request = stub_request 'HTTP_HOST' => 'www.example.org:80'89 assert_equal "", request.port_string90 request = stub_request 'HTTP_HOST' => 'www.example.org:8080'91 assert_equal ":8080", request.port_string92 end93 def test_request_uri94 request = stub_request 'REQUEST_URI' => "http://www.rubyonrails.org/path/of/some/uri?mapped=1"95 assert_equal "/path/of/some/uri?mapped=1", request.request_uri96 assert_equal "/path/of/some/uri", request.path97 request = stub_request 'REQUEST_URI' => "http://www.rubyonrails.org/path/of/some/uri"98 assert_equal "/path/of/some/uri", request.request_uri99 assert_equal "/path/of/some/uri", request.path100 request = stub_request 'REQUEST_URI' => "/path/of/some/uri"101 assert_equal "/path/of/some/uri", request.request_uri102 assert_equal "/path/of/some/uri", request.path103 request = stub_request 'REQUEST_URI' => "/"104 assert_equal "/", request.request_uri105 assert_equal "/", request.path106 request = stub_request 'REQUEST_URI' => "/?m=b"107 assert_equal "/?m=b", request.request_uri108 assert_equal "/", request.path109 request = stub_request 'REQUEST_URI' => "/", 'SCRIPT_NAME' => '/dispatch.cgi'110 assert_equal "/", request.request_uri111 assert_equal "/", request.path112 ActionController::Base.relative_url_root = "/hieraki"113 request = stub_request 'REQUEST_URI' => "/hieraki/", 'SCRIPT_NAME' => "/hieraki/dispatch.cgi"114 assert_equal "/hieraki/", request.request_uri115 assert_equal "/", request.path116 ActionController::Base.relative_url_root = nil117 ActionController::Base.relative_url_root = "/collaboration/hieraki"118 request = stub_request 'REQUEST_URI' => "/collaboration/hieraki/books/edit/2",119 'SCRIPT_NAME' => "/collaboration/hieraki/dispatch.cgi"120 assert_equal "/collaboration/hieraki/books/edit/2", request.request_uri121 assert_equal "/books/edit/2", request.path122 ActionController::Base.relative_url_root = nil123 # The following tests are for when REQUEST_URI is not supplied (as in IIS)124 request = stub_request 'PATH_INFO' => "/path/of/some/uri?mapped=1",125 'SCRIPT_NAME' => nil,126 'REQUEST_URI' => nil127 assert_equal "/path/of/some/uri?mapped=1", request.request_uri128 assert_equal "/path/of/some/uri", request.path129 ActionController::Base.relative_url_root = '/path'130 request = stub_request 'PATH_INFO' => "/path/of/some/uri?mapped=1",131 'SCRIPT_NAME' => "/path/dispatch.rb",132 'REQUEST_URI' => nil133 assert_equal "/path/of/some/uri?mapped=1", request.request_uri134 assert_equal "/of/some/uri", request.path135 ActionController::Base.relative_url_root = nil136 request = stub_request 'PATH_INFO' => "/path/of/some/uri",137 'SCRIPT_NAME' => nil,138 'REQUEST_URI' => nil139 assert_equal "/path/of/some/uri", request.request_uri140 assert_equal "/path/of/some/uri", request.path141 request = stub_request 'PATH_INFO' => '/', 'REQUEST_URI' => nil142 assert_equal "/", request.request_uri143 assert_equal "/", request.path144 request = stub_request 'PATH_INFO' => '/?m=b', 'REQUEST_URI' => nil145 assert_equal "/?m=b", request.request_uri146 assert_equal "/", request.path147 request = stub_request 'PATH_INFO' => "/",148 'SCRIPT_NAME' => "/dispatch.cgi",149 'REQUEST_URI' => nil150 assert_equal "/", request.request_uri151 assert_equal "/", request.path152 ActionController::Base.relative_url_root = '/hieraki'153 request = stub_request 'PATH_INFO' => "/hieraki/",154 'SCRIPT_NAME' => "/hieraki/dispatch.cgi",155 'REQUEST_URI' => nil156 assert_equal "/hieraki/", request.request_uri157 assert_equal "/", request.path158 ActionController::Base.relative_url_root = nil159 request = stub_request 'REQUEST_URI' => '/hieraki/dispatch.cgi'160 ActionController::Base.relative_url_root = '/hieraki'161 assert_equal "/dispatch.cgi", request.path162 ActionController::Base.relative_url_root = nil163 request = stub_request 'REQUEST_URI' => '/hieraki/dispatch.cgi'164 ActionController::Base.relative_url_root = '/foo'165 assert_equal "/hieraki/dispatch.cgi", request.path166 ActionController::Base.relative_url_root = nil167 # This test ensures that Rails uses REQUEST_URI over PATH_INFO168 ActionController::Base.relative_url_root = nil169 request = stub_request 'REQUEST_URI' => "/some/path",170 'PATH_INFO' => "/another/path",171 'SCRIPT_NAME' => "/dispatch.cgi"172 assert_equal "/some/path", request.request_uri173 assert_equal "/some/path", request.path174 end175 def test_host_with_default_port176 request = stub_request 'HTTP_HOST' => 'rubyonrails.org:80'177 assert_equal "rubyonrails.org", request.host_with_port178 end179 def test_host_with_non_default_port180 request = stub_request 'HTTP_HOST' => 'rubyonrails.org:81'181 assert_equal "rubyonrails.org:81", request.host_with_port182 end183 def test_server_software184 request = stub_request185 assert_equal nil, request.server_software186 request = stub_request 'SERVER_SOFTWARE' => 'Apache3.422'187 assert_equal 'apache', request.server_software188 request = stub_request 'SERVER_SOFTWARE' => 'lighttpd(1.1.4)'189 assert_equal 'lighttpd', request.server_software190 end191 def test_xml_http_request192 request = stub_request193 assert !request.xml_http_request?194 assert !request.xhr?195 request = stub_request 'HTTP_X_REQUESTED_WITH' => 'DefinitelyNotAjax1.0'196 assert !request.xml_http_request?197 assert !request.xhr?198 request = stub_request 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest'199 assert request.xml_http_request?200 assert request.xhr?201 end202 def test_reports_ssl203 request = stub_request204 assert !request.ssl?205 request = stub_request 'HTTPS' => 'on'206 assert request.ssl?207 end208 def test_reports_ssl_when_proxied_via_lighttpd209 request = stub_request210 assert !request.ssl?211 request = stub_request 'HTTP_X_FORWARDED_PROTO' => 'https'212 assert request.ssl?213 end214 def test_symbolized_request_methods215 [:get, :post, :put, :delete].each do |method|216 request = stub_request 'REQUEST_METHOD' => method.to_s.upcase217 assert_equal method, request.method218 end219 end220 def test_invalid_http_method_raises_exception221 assert_raise(ActionController::UnknownHttpMethod) do222 request = stub_request 'REQUEST_METHOD' => 'RANDOM_METHOD'223 request.request_method224 end225 end226 def test_allow_method_hacking_on_post227 [:get, :head, :options, :put, :post, :delete].each do |method|228 request = stub_request 'REQUEST_METHOD' => method.to_s.upcase229 assert_equal(method == :head ? :get : method, request.method)230 end231 end232 def test_restrict_method_hacking233 [:get, :put, :delete].each do |method|234 request = stub_request 'REQUEST_METHOD' => method.to_s.upcase,235 'action_controller.request.request_parameters' => { :_method => 'put' }236 assert_equal method, request.method237 end238 end239 def test_head_masquerading_as_get240 request = stub_request 'REQUEST_METHOD' => 'HEAD'241 assert_equal :get, request.method242 assert request.get?243 assert request.head?244 end245 def test_xml_format246 request = stub_request247 request.expects(:parameters).at_least_once.returns({ :format => 'xml' })248 assert_equal Mime::XML, request.format249 end250 def test_xhtml_format251 request = stub_request252 request.expects(:parameters).at_least_once.returns({ :format => 'xhtml' })253 assert_equal Mime::HTML, request.format254 end255 def test_txt_format256 request = stub_request257 request.expects(:parameters).at_least_once.returns({ :format => 'txt' })258 assert_equal Mime::TEXT, request.format259 end260 def test_xml_http_request261 ActionController::Base.use_accept_header, old =262 false, ActionController::Base.use_accept_header263 request = stub_request 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest'264 request.expects(:parameters).at_least_once.returns({})265 assert request.xhr?266 assert_equal Mime::JS, request.format267 ensure268 ActionController::Base.use_accept_header = old269 end270 def test_content_type271 request = stub_request 'CONTENT_TYPE' => 'text/html'272 assert_equal Mime::HTML, request.content_type273 end274 def test_can_override_format_with_parameter275 request = stub_request276 request.expects(:parameters).at_least_once.returns({ :format => :txt })277 assert !request.format.xml?278 request = stub_request279 request.expects(:parameters).at_least_once.returns({ :format => :xml })280 assert request.format.xml?281 end282 def test_content_no_type283 request = stub_request284 assert_equal nil, request.content_type285 end286 def test_content_type_xml287 request = stub_request 'CONTENT_TYPE' => 'application/xml'288 assert_equal Mime::XML, request.content_type289 end290 def test_content_type_with_charset291 request = stub_request 'CONTENT_TYPE' => 'application/xml; charset=UTF-8'292 assert_equal Mime::XML, request.content_type293 end294 def test_user_agent295 request = stub_request 'HTTP_USER_AGENT' => 'TestAgent'296 assert_equal 'TestAgent', request.user_agent297 end298 def test_parameters299 request = stub_request300 request.stubs(:request_parameters).returns({ "foo" => 1 })301 request.stubs(:query_parameters).returns({ "bar" => 2 })302 assert_equal({"foo" => 1, "bar" => 2}, request.parameters)303 assert_equal({"foo" => 1}, request.request_parameters)304 assert_equal({"bar" => 2}, request.query_parameters)305 end306protected307 def stub_request(env={})308 ActionController::Request.new(env)309 end310end...

Full Screen

Full Screen

request.rb

Source:request.rb Github

copy

Full Screen

...10require 'action_dispatch/http/upload'11require 'action_dispatch/http/url'12require 'active_support/core_ext/array/conversions'13module ActionDispatch14 class Request < Rack::Request15 include ActionDispatch::Http::Cache::Request16 include ActionDispatch::Http::MimeNegotiation17 include ActionDispatch::Http::Parameters18 include ActionDispatch::Http::FilterParameters19 include ActionDispatch::Http::URL20 autoload :Session, 'action_dispatch/request/session'21 autoload :Utils, 'action_dispatch/request/utils'22 LOCALHOST = Regexp.union [/^127\.0\.0\.\d{1,3}$/, /^::1$/, /^0:0:0:0:0:0:0:1(%.*)?$/]23 ENV_METHODS = %w[ AUTH_TYPE GATEWAY_INTERFACE24 PATH_TRANSLATED REMOTE_HOST25 REMOTE_IDENT REMOTE_USER REMOTE_ADDR26 SERVER_NAME SERVER_PROTOCOL27 HTTP_ACCEPT HTTP_ACCEPT_CHARSET HTTP_ACCEPT_ENCODING28 HTTP_ACCEPT_LANGUAGE HTTP_CACHE_CONTROL HTTP_FROM29 HTTP_NEGOTIATE HTTP_PRAGMA ].freeze30 ENV_METHODS.each do |env|31 class_eval <<-METHOD, __FILE__, __LINE__ + 132 def #{env.sub(/^HTTP_/n, '').downcase} # def accept_charset33 @env["#{env}"] # @env["HTTP_ACCEPT_CHARSET"]34 end # end35 METHOD36 end37 def initialize(env)38 super39 @method = nil40 @request_method = nil41 @remote_ip = nil42 @original_fullpath = nil43 @fullpath = nil44 @ip = nil45 @uuid = nil46 end47 def key?(key)48 @env.key?(key)49 end50 # List of HTTP request methods from the following RFCs:51 # Hypertext Transfer Protocol -- HTTP/1.1 (http://www.ietf.org/rfc/rfc2616.txt)52 # HTTP Extensions for Distributed Authoring -- WEBDAV (http://www.ietf.org/rfc/rfc2518.txt)53 # Versioning Extensions to WebDAV (http://www.ietf.org/rfc/rfc3253.txt)54 # Ordered Collections Protocol (WebDAV) (http://www.ietf.org/rfc/rfc3648.txt)55 # Web Distributed Authoring and Versioning (WebDAV) Access Control Protocol (http://www.ietf.org/rfc/rfc3744.txt)56 # Web Distributed Authoring and Versioning (WebDAV) SEARCH (http://www.ietf.org/rfc/rfc5323.txt)57 # PATCH Method for HTTP (http://www.ietf.org/rfc/rfc5789.txt)58 RFC2616 = %w(OPTIONS GET HEAD POST PUT DELETE TRACE CONNECT)59 RFC2518 = %w(PROPFIND PROPPATCH MKCOL COPY MOVE LOCK UNLOCK)60 RFC3253 = %w(VERSION-CONTROL REPORT CHECKOUT CHECKIN UNCHECKOUT MKWORKSPACE UPDATE LABEL MERGE BASELINE-CONTROL MKACTIVITY)61 RFC3648 = %w(ORDERPATCH)62 RFC3744 = %w(ACL)63 RFC5323 = %w(SEARCH)64 RFC5789 = %w(PATCH)65 HTTP_METHODS = RFC2616 + RFC2518 + RFC3253 + RFC3648 + RFC3744 + RFC5323 + RFC578966 HTTP_METHOD_LOOKUP = {}67 # Populate the HTTP method lookup cache68 HTTP_METHODS.each { |method|69 HTTP_METHOD_LOOKUP[method] = method.underscore.to_sym70 }71 # Returns the HTTP \method that the application should see.72 # In the case where the \method was overridden by a middleware73 # (for instance, if a HEAD request was converted to a GET,74 # or if a _method parameter was used to determine the \method75 # the application should use), this \method returns the overridden76 # value, not the original.77 def request_method78 @request_method ||= check_method(env["REQUEST_METHOD"])79 end80 # Returns a symbol form of the #request_method81 def request_method_symbol82 HTTP_METHOD_LOOKUP[request_method]83 end84 # Returns the original value of the environment's REQUEST_METHOD,85 # even if it was overridden by middleware. See #request_method for86 # more information.87 def method88 @method ||= check_method(env["rack.methodoverride.original_method"] || env['REQUEST_METHOD'])89 end90 # Returns a symbol form of the #method91 def method_symbol92 HTTP_METHOD_LOOKUP[method]93 end94 # Is this a GET (or HEAD) request?95 # Equivalent to <tt>request.request_method_symbol == :get</tt>.96 def get?97 HTTP_METHOD_LOOKUP[request_method] == :get98 end99 # Is this a POST request?100 # Equivalent to <tt>request.request_method_symbol == :post</tt>.101 def post?102 HTTP_METHOD_LOOKUP[request_method] == :post103 end104 # Is this a PATCH request?105 # Equivalent to <tt>request.request_method == :patch</tt>.106 def patch?107 HTTP_METHOD_LOOKUP[request_method] == :patch108 end109 # Is this a PUT request?110 # Equivalent to <tt>request.request_method_symbol == :put</tt>.111 def put?112 HTTP_METHOD_LOOKUP[request_method] == :put113 end114 # Is this a DELETE request?115 # Equivalent to <tt>request.request_method_symbol == :delete</tt>.116 def delete?117 HTTP_METHOD_LOOKUP[request_method] == :delete118 end119 # Is this a HEAD request?120 # Equivalent to <tt>request.request_method_symbol == :head</tt>.121 def head?122 HTTP_METHOD_LOOKUP[request_method] == :head123 end124 # Provides access to the request's HTTP headers, for example:125 #126 # request.headers["Content-Type"] # => "text/plain"127 def headers128 Http::Headers.new(@env)129 end130 def original_fullpath131 @original_fullpath ||= (env["ORIGINAL_FULLPATH"] || fullpath)132 end133 # Returns the +String+ full path including params of the last URL requested.134 #135 # # get "/articles"136 # request.fullpath # => "/articles"137 #138 # # get "/articles?page=2"139 # request.fullpath # => "/articles?page=2"140 def fullpath141 @fullpath ||= super142 end143 # Returns the original request URL as a +String+.144 #145 # # get "/articles?page=2"146 # request.original_url # => "http://www.example.com/articles?page=2"147 def original_url148 base_url + original_fullpath149 end150 # The +String+ MIME type of the request.151 #152 # # get "/articles"153 # request.media_type # => "application/x-www-form-urlencoded"154 def media_type155 content_mime_type.to_s156 end157 # Returns the content length of the request as an integer.158 def content_length159 super.to_i160 end161 # Returns true if the "X-Requested-With" header contains "XMLHttpRequest"162 # (case-insensitive). All major JavaScript libraries send this header with163 # every Ajax request.164 def xml_http_request?165 @env['HTTP_X_REQUESTED_WITH'] =~ /XMLHttpRequest/i166 end167 alias :xhr? :xml_http_request?168 def ip169 @ip ||= super170 end171 # Originating IP address, usually set by the RemoteIp middleware.172 def remote_ip173 @remote_ip ||= (@env["action_dispatch.remote_ip"] || ip).to_s174 end175 # Returns the unique request id, which is based off either the X-Request-Id header that can176 # be generated by a firewall, load balancer, or web server or by the RequestId middleware177 # (which sets the action_dispatch.request_id environment variable).178 #179 # This unique ID is useful for tracing a request from end-to-end as part of logging or debugging.180 # This relies on the rack variable set by the ActionDispatch::RequestId middleware.181 def uuid182 @uuid ||= env["action_dispatch.request_id"]183 end184 # Returns the lowercase name of the HTTP server software.185 def server_software186 (@env['SERVER_SOFTWARE'] && /^([a-zA-Z]+)/ =~ @env['SERVER_SOFTWARE']) ? $1.downcase : nil187 end188 # Read the request \body. This is useful for web services that need to189 # work with raw requests directly.190 def raw_post191 unless @env.include? 'RAW_POST_DATA'192 raw_post_body = body193 @env['RAW_POST_DATA'] = raw_post_body.read(content_length)194 raw_post_body.rewind if raw_post_body.respond_to?(:rewind)195 end196 @env['RAW_POST_DATA']197 end198 # The request body is an IO input stream. If the RAW_POST_DATA environment199 # variable is already set, wrap it in a StringIO.200 def body201 if raw_post = @env['RAW_POST_DATA']202 raw_post.force_encoding(Encoding::BINARY)203 StringIO.new(raw_post)204 else205 @env['rack.input']206 end207 end208 def form_data?209 FORM_DATA_MEDIA_TYPES.include?(content_mime_type.to_s)210 end211 def body_stream #:nodoc:212 @env['rack.input']213 end214 # TODO This should be broken apart into AD::Request::Session and probably215 # be included by the session middleware.216 def reset_session217 if session && session.respond_to?(:destroy)218 session.destroy219 else220 self.session = {}221 end222 @env['action_dispatch.request.flash_hash'] = nil223 end224 def session=(session) #:nodoc:225 Session.set @env, session226 end227 def session_options=(options)228 Session::Options.set @env, options229 end230 # Override Rack's GET method to support indifferent access231 def GET232 @env["action_dispatch.request.query_parameters"] ||= Utils.deep_munge((normalize_encode_params(super) || {}))233 rescue TypeError => e234 raise ActionController::BadRequest.new(:query, e)235 end236 alias :query_parameters :GET237 # Override Rack's POST method to support indifferent access238 def POST239 @env["action_dispatch.request.request_parameters"] ||= Utils.deep_munge((normalize_encode_params(super) || {}))240 rescue TypeError => e241 raise ActionController::BadRequest.new(:request, e)242 end243 alias :request_parameters :POST244 # Returns the authorization header regardless of whether it was specified directly or through one of the245 # proxy alternatives.246 def authorization247 @env['HTTP_AUTHORIZATION'] ||248 @env['X-HTTP_AUTHORIZATION'] ||249 @env['X_HTTP_AUTHORIZATION'] ||250 @env['REDIRECT_X_HTTP_AUTHORIZATION']251 end252 # True if the request came from localhost, 127.0.0.1.253 def local?254 LOCALHOST =~ remote_addr && LOCALHOST =~ remote_ip255 end256 # Extracted into ActionDispatch::Request::Utils.deep_munge, but kept here for backwards compatibility.257 def deep_munge(hash)258 ActiveSupport::Deprecation.warn(259 "This method has been extracted into ActionDispatch::Request::Utils.deep_munge. Please start using that instead."260 )261 Utils.deep_munge(hash)262 end263 protected264 def parse_query(qs)265 Utils.deep_munge(super)266 end267 private268 def check_method(name)269 HTTP_METHOD_LOOKUP[name] || raise(ActionController::UnknownHttpMethod, "#{name}, accepted HTTP methods are #{HTTP_METHODS.to_sentence(:locale => :en)}")270 name271 end272 end273end...

Full Screen

Full Screen

test_consumer.rb

Source:test_consumer.rb Github

copy

Full Screen

1require 'test/unit'2require 'oauth/consumer'3# This performs testing against Andy Smith's test server http://term.ie/oauth/example/4# Thanks Andy.5# This also means you have to be online to be able to run these.6class ConsumerTest < Test::Unit::TestCase7 def setup8 @consumer=OAuth::Consumer.new( 9 'consumer_key_86cad9', '5888bf0345e5d237',10 {11 :site=>"http://blabla.bla",12 :request_token_path=>"/oauth/example/request_token.php",13 :access_token_path=>"/oauth/example/access_token.php",14 :authorize_path=>"/oauth/example/authorize.php",15 :scheme=>:header,16 :http_method=>:get17 })18 @token = OAuth::ConsumerToken.new(@consumer,'token_411a7f', '3196ffd991c8ebdb')19 @request_uri = URI.parse('http://example.com/test?key=value')20 @request_parameters = { 'key' => 'value' }21 @nonce = 22557921188119884200598869833467583544622 @timestamp = "1199645624"23 @consumer.http=Net::HTTP.new(@request_uri.host, @request_uri.port)24 end25 26 def test_initializer27 assert_equal "consumer_key_86cad9",@consumer.key28 assert_equal "5888bf0345e5d237",@consumer.secret29 assert_equal "http://blabla.bla",@consumer.site30 assert_equal "/oauth/example/request_token.php",@consumer.request_token_path31 assert_equal "/oauth/example/access_token.php",@consumer.access_token_path32 assert_equal "http://blabla.bla/oauth/example/request_token.php",@consumer.request_token_url33 assert_equal "http://blabla.bla/oauth/example/access_token.php",@consumer.access_token_url34 assert_equal "http://blabla.bla/oauth/example/authorize.php",@consumer.authorize_url35 assert_equal :header,@consumer.scheme36 assert_equal :get,@consumer.http_method37 end38 def test_defaults39 @consumer=OAuth::Consumer.new(40 "key",41 "secret",42 {43 :site=>"http://twitter.com"44 })45 assert_equal "key",@consumer.key46 assert_equal "secret",@consumer.secret47 assert_equal "http://twitter.com",@consumer.site48 assert_equal "/oauth/request_token",@consumer.request_token_path49 assert_equal "/oauth/access_token",@consumer.access_token_path50 assert_equal "http://twitter.com/oauth/request_token",@consumer.request_token_url51 assert_equal "http://twitter.com/oauth/access_token",@consumer.access_token_url52 assert_equal "http://twitter.com/oauth/authorize",@consumer.authorize_url53 assert_equal :header,@consumer.scheme54 assert_equal :post,@consumer.http_method 55 end56 def test_override_paths57 @consumer=OAuth::Consumer.new(58 "key",59 "secret",60 {61 :site=>"http://twitter.com",62 :request_token_url=>"http://oauth.twitter.com/request_token",63 :access_token_url=>"http://oauth.twitter.com/access_token",64 :authorize_url=>"http://site.twitter.com/authorize"65 })66 assert_equal "key",@consumer.key67 assert_equal "secret",@consumer.secret68 assert_equal "http://twitter.com",@consumer.site69 assert_equal "/oauth/request_token",@consumer.request_token_path70 assert_equal "/oauth/access_token",@consumer.access_token_path71 assert_equal "http://oauth.twitter.com/request_token",@consumer.request_token_url72 assert_equal "http://oauth.twitter.com/access_token",@consumer.access_token_url73 assert_equal "http://site.twitter.com/authorize",@consumer.authorize_url74 assert_equal :header,@consumer.scheme75 assert_equal :post,@consumer.http_method 76 end77 def test_that_signing_auth_headers_on_get_requests_works78 request = Net::HTTP::Get.new(@request_uri.path + "?" + request_parameters_to_s)79 @token.sign!(request, {:nonce => @nonce, :timestamp => @timestamp})80 81 assert_equal 'GET', request.method82 assert_equal '/test?key=value', request.path83 assert_equal "OAuth realm=\"\", oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"HMAC-SHA1\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"1oO2izFav1GP4kEH2EskwXkCRFg%3D\", oauth_version=\"1.0\"", request['authorization']84 end85 def test_that_signing_auth_headers_on_post_requests_works86 request = Net::HTTP::Post.new(@request_uri.path)87 request.set_form_data( @request_parameters )88 @token.sign!(request, {:nonce => @nonce, :timestamp => @timestamp})89# assert_equal "",request.oauth_helper.signature_base_string90 assert_equal 'POST', request.method91 assert_equal '/test', request.path92 assert_equal 'key=value', request.body93 assert_equal "OAuth realm=\"\", oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"HMAC-SHA1\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"26g7wHTtNO6ZWJaLltcueppHYiI%3D\", oauth_version=\"1.0\"", request['authorization']94 end95 96 def test_that_signing_post_params_works97 request = Net::HTTP::Post.new(@request_uri.path)98 request.set_form_data( @request_parameters )99 @token.sign!(request, {:scheme => 'body', :nonce => @nonce, :timestamp => @timestamp})100 assert_equal 'POST', request.method101 assert_equal '/test', request.path102 assert_equal "key=value&oauth_consumer_key=consumer_key_86cad9&oauth_nonce=225579211881198842005988698334675835446&oauth_signature=iMZaUTbQof%2fHMFyIde%2bOIkhW5is%3d&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1199645624&oauth_token=token_411a7f&oauth_version=1.0", request.body.split("&").sort.join("&")103 assert_equal nil, request['authorization']104 end105 def test_that_using_auth_headers_on_get_on_create_signed_requests_works106 request=@consumer.create_signed_request(:get,@request_uri.path+ "?" + request_parameters_to_s,@token,{:nonce => @nonce, :timestamp => @timestamp},@request_parameters)107 108 assert_equal 'GET', request.method109 assert_equal '/test?key=value', request.path110 assert_equal "OAuth realm=\"\", oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"HMAC-SHA1\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"1oO2izFav1GP4kEH2EskwXkCRFg%3D\", oauth_version=\"1.0\"", request['authorization']111 end112 def test_that_using_auth_headers_on_post_on_create_signed_requests_works113 request=@consumer.create_signed_request(:post,@request_uri.path,@token,{:nonce => @nonce, :timestamp => @timestamp},@request_parameters,{})114 assert_equal 'POST', request.method115 assert_equal '/test', request.path116 assert_equal 'key=value', request.body117 assert_equal "OAuth realm=\"\", oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"HMAC-SHA1\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"26g7wHTtNO6ZWJaLltcueppHYiI%3D\", oauth_version=\"1.0\"", request['authorization']118 end119 def test_that_signing_post_params_works120 request=@consumer.create_signed_request(:post,@request_uri.path,@token,{:scheme => 'body', :nonce => @nonce, :timestamp => @timestamp},@request_parameters,{})121 assert_equal 'POST', request.method122 assert_equal '/test', request.path123 assert_equal "key=value&oauth_consumer_key=consumer_key_86cad9&oauth_nonce=225579211881198842005988698334675835446&oauth_signature=26g7wHTtNO6ZWJaLltcueppHYiI%3d&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1199645624&oauth_token=token_411a7f&oauth_version=1.0", request.body.split("&").sort.join("&")124 assert_equal nil, request['authorization']125 end126 127 def test_step_by_step_token_request128 @consumer=OAuth::Consumer.new( 129 "key",130 "secret",131 {132 :site=>"http://term.ie",133 :request_token_path=>"/oauth/example/request_token.php",134 :access_token_path=>"/oauth/example/access_token.php",135 :authorize_path=>"/oauth/example/authorize.php",136 :scheme=>:header137 })138 options={:nonce=>'nonce',:timestamp=>Time.now.to_i.to_s}139 140 request = Net::HTTP::Get.new("/oauth/example/request_token.php")141 signature_base_string=@consumer.signature_base_string(request,nil,options)142 assert_equal "GET&http%3A%2F%2Fterm.ie%2Foauth%2Fexample%2Frequest_token.php&oauth_consumer_key%3Dkey%26oauth_nonce%3D#{options[:nonce]}%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D#{options[:timestamp]}%26oauth_token%3D%26oauth_version%3D1.0",signature_base_string143 @consumer.sign!(request, nil,options)144 assert_equal 'GET', request.method145 assert_equal nil, request.body146 response=@consumer.http.request(request)147 assert_equal "200",response.code148 assert_equal "oauth_token=requestkey&oauth_token_secret=requestsecret",response.body149 end150 151 def test_get_token_sequence 152 @consumer=OAuth::Consumer.new( 153 "key",154 "secret",155 {156 :site=>"http://term.ie",157 :request_token_path=>"/oauth/example/request_token.php",158 :access_token_path=>"/oauth/example/access_token.php",159 :authorize_path=>"/oauth/example/authorize.php"160 })161 162 @request_token=@consumer.get_request_token163 assert_not_nil @request_token164 assert_equal "requestkey",@request_token.token165 assert_equal "requestsecret",@request_token.secret166 assert_equal "http://term.ie/oauth/example/authorize.php?oauth_token=requestkey",@request_token.authorize_url167 @access_token=@request_token.get_access_token168 assert_not_nil @access_token169 assert_equal "accesskey",@access_token.token170 assert_equal "accesssecret",@access_token.secret171 172 @response=@access_token.get("/oauth/example/echo_api.php?ok=hello&test=this")173 assert_not_nil @response174 assert_equal "200",@response.code175 assert_equal( "ok=hello&test=this",@response.body)176 177 @response=@access_token.post("/oauth/example/echo_api.php",{'ok'=>'hello','test'=>'this'})178 assert_not_nil @response179 assert_equal "200",@response.code180 assert_equal( "ok=hello&test=this",@response.body) 181 end182 protected183 def request_parameters_to_s184 @request_parameters.map { |k,v| "#{k}=#{v}" }.join("&")185 end186 187end...

Full Screen

Full Screen

test_net_http_client.rb

Source:test_net_http_client.rb Github

copy

Full Screen

1require File.dirname(__FILE__) + '/test_helper.rb'2require 'oauth/client/net_http'3class NetHTTPClientTest < Test::Unit::TestCase4 def setup5 @consumer = OAuth::Consumer.new('consumer_key_86cad9', '5888bf0345e5d237')6 @token = OAuth::Token.new('token_411a7f', '3196ffd991c8ebdb')7 @request_uri = URI.parse('http://example.com/test?key=value')8 @request_parameters = { 'key' => 'value' }9 @nonce = 22557921188119884200598869833467583544610 @timestamp = "1199645624"11 @http = Net::HTTP.new(@request_uri.host, @request_uri.port)12 end13 def test_that_using_auth_headers_on_get_requests_works14 request = Net::HTTP::Get.new(@request_uri.path + "?" + request_parameters_to_s)15 request.oauth!(@http, @consumer, @token, {:nonce => @nonce, :timestamp => @timestamp})16 17 assert_equal 'GET', request.method18 assert_equal '/test?key=value', request.path19 assert_equal "OAuth realm=\"\", oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"HMAC-SHA1\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"1oO2izFav1GP4kEH2EskwXkCRFg%3D\", oauth_version=\"1.0\"", request['authorization']20 end21 def test_that_using_auth_headers_on_post_requests_works22 request = Net::HTTP::Post.new(@request_uri.path)23 request.set_form_data( @request_parameters )24 request.oauth!(@http, @consumer, @token, {:nonce => @nonce, :timestamp => @timestamp})25 assert_equal 'POST', request.method26 assert_equal '/test', request.path27 assert_equal 'key=value', request.body28 assert_equal "OAuth realm=\"\", oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"HMAC-SHA1\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"26g7wHTtNO6ZWJaLltcueppHYiI%3D\", oauth_version=\"1.0\"", request['authorization']29 end30 31 def test_that_using_post_params_works32 request = Net::HTTP::Post.new(@request_uri.path)33 request.set_form_data( @request_parameters )34 request.oauth!(@http, @consumer, @token, {:scheme => 'body', :nonce => @nonce, :timestamp => @timestamp})35 assert_equal 'POST', request.method36 assert_equal '/test', request.path37 assert_equal "key=value&oauth_consumer_key=consumer_key_86cad9&oauth_nonce=225579211881198842005988698334675835446&oauth_signature=26g7wHTtNO6ZWJaLltcueppHYiI%3d&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1199645624&oauth_token=token_411a7f&oauth_version=1.0", request.body.split("&").sort.join("&")38 assert_equal nil, request['authorization']39 end40 def test_that_using_get_params_works41 request = Net::HTTP::Get.new(@request_uri.path + "?" + request_parameters_to_s)42 request.oauth!(@http, @consumer, @token, {:scheme => 'query_string', :nonce => @nonce, :timestamp => @timestamp})43 assert_equal 'GET', request.method44 uri = URI.parse(request.path)45 assert_equal '/test', uri.path46 assert_equal nil, uri.fragment47 assert_equal "key=value&oauth_consumer_key=consumer_key_86cad9&oauth_nonce=225579211881198842005988698334675835446&oauth_signature=1oO2izFav1GP4kEH2EskwXkCRFg=&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1199645624&oauth_token=token_411a7f&oauth_version=1.0", uri.query.split("&").sort.join("&")48 assert_equal nil, request['authorization']49 end50 def test_that_using_get_params_works_with_post_requests51 request = Net::HTTP::Post.new(@request_uri.path + "?" + request_parameters_to_s)52 request.oauth!(@http, @consumer, @token, {:scheme => 'query_string', :nonce => @nonce, :timestamp => @timestamp})53 assert_equal 'POST', request.method54 uri = URI.parse(request.path)55 assert_equal '/test', uri.path56 assert_equal nil, uri.fragment57 assert_equal "key=value&oauth_consumer_key=consumer_key_86cad9&oauth_nonce=225579211881198842005988698334675835446&oauth_signature=26g7wHTtNO6ZWJaLltcueppHYiI=&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1199645624&oauth_token=token_411a7f&oauth_version=1.0", uri.query.split("&").sort.join('&')58 assert_equal nil, request.body59 assert_equal nil, request['authorization']60 end61 def test_that_using_get_params_works_with_post_requests_that_have_post_bodies62 request = Net::HTTP::Post.new(@request_uri.path + "?" + request_parameters_to_s)63 request.set_form_data( { 'key2' => 'value2' } )64 request.oauth!(@http, @consumer, @token, {:scheme => :query_string, :nonce => @nonce, :timestamp => @timestamp})65 assert_equal 'POST', request.method66 uri = URI.parse(request.path)67 assert_equal '/test', uri.path68 assert_equal nil, uri.fragment69 assert_equal "key=value&oauth_consumer_key=consumer_key_86cad9&oauth_nonce=225579211881198842005988698334675835446&oauth_signature=4kSU8Zd1blWo3W6qJH7eaRTMkg0=&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1199645624&oauth_token=token_411a7f&oauth_version=1.0", uri.query.split("&").sort.join('&')70 assert_equal "key2=value2", request.body71 assert_equal nil, request['authorization']72 end73 74 75 def test_example_from_specs76 consumer=OAuth::Consumer.new("dpf43f3p2l4k3l03","kd94hf93k423kf44")77 token = OAuth::Token.new('nnch734d00sl2jdk', 'pfkkdhi9sl3r4s00')78 request_uri = URI.parse('http://photos.example.net/photos?file=vacation.jpg&size=original')79 nonce = 'kllo9940pd9333jh'80 timestamp = "1191242096"81 http = Net::HTTP.new(request_uri.host, request_uri.port)82 request = Net::HTTP::Get.new(request_uri.path + "?" + request_uri.query)83 signature_base_string=request.signature_base_string(http, consumer, token, {:nonce => nonce, :timestamp => timestamp})84 assert_equal 'GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dkllo9940pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1191242096%26oauth_token%3Dnnch734d00sl2jdk%26oauth_version%3D1.0%26size%3Doriginal',signature_base_string85# request = Net::HTTP::Get.new(request_uri.path + "?" + request_uri.query)86 request.oauth!(http, consumer, token, {:nonce => nonce, :timestamp => timestamp,:realm=>"http://photos.example.net/"})87 assert_equal 'GET', request.method88 assert_equal 'OAuth realm="http://photos.example.net/", oauth_nonce="kllo9940pd9333jh", oauth_signature_method="HMAC-SHA1", oauth_token="nnch734d00sl2jdk", oauth_timestamp="1191242096", oauth_consumer_key="dpf43f3p2l4k3l03", oauth_signature="tR3%2BTy81lMeYAr%2FFid0kMTYa%2FWM%3D", oauth_version="1.0"', request['authorization']89 90 end91 92 def test_step_by_step_token_request93 consumer=OAuth::Consumer.new( 94 "key",95 "secret")96 request_uri = URI.parse('http://term.ie/oauth/example/request_token.php')97 nonce = rand(2**128).to_s98 timestamp = Time.now.to_i.to_s99 http = Net::HTTP.new(request_uri.host, request_uri.port)100 101 request = Net::HTTP::Get.new(request_uri.path)102 signature_base_string=request.signature_base_string(http, consumer, nil, {:scheme=>:query_string,:nonce => nonce, :timestamp => timestamp})103 assert_equal "GET&http%3A%2F%2Fterm.ie%2Foauth%2Fexample%2Frequest_token.php&oauth_consumer_key%3Dkey%26oauth_nonce%3D#{nonce}%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D#{timestamp}%26oauth_token%3D%26oauth_version%3D1.0",signature_base_string104 105# request = Net::HTTP::Get.new(request_uri.path)106 request.oauth!(http, consumer, nil, {:scheme=>:query_string,:nonce => nonce, :timestamp => timestamp})107 assert_equal 'GET', request.method108 assert_nil request.body109 assert_nil request['authorization']110# assert_equal 'OAuth oauth_nonce="kllo9940pd9333jh", oauth_signature_method="HMAC-SHA1", oauth_token="", oauth_timestamp="'+timestamp+'", oauth_consumer_key="key", oauth_signature="tR3%2BTy81lMeYAr%2FFid0kMTYa%2FWM%3D", oauth_version="1.0"', request['authorization']111 response=http.request(request)112 assert_equal "200",response.code113# assert_equal request['authorization'],response.body114 assert_equal "oauth_token=requestkey&oauth_token_secret=requestsecret",response.body115 end116 protected117 def request_parameters_to_s118 @request_parameters.map { |k,v| "#{k}=#{v}" }.join("&")119 end120end...

Full Screen

Full Screen

rack_test.rb

Source:rack_test.rb Github

copy

Full Screen

1require 'abstract_unit'2# TODO: Merge these tests into RequestTest3class BaseRackTest < ActiveSupport::TestCase4 def setup5 @env = {6 "HTTP_MAX_FORWARDS" => "10",7 "SERVER_NAME" => "glu.ttono.us",8 "FCGI_ROLE" => "RESPONDER",9 "AUTH_TYPE" => "Basic",10 "HTTP_X_FORWARDED_HOST" => "glu.ttono.us",11 "HTTP_ACCEPT_CHARSET" => "UTF-8",12 "HTTP_ACCEPT_ENCODING" => "gzip, deflate",13 "HTTP_CACHE_CONTROL" => "no-cache, max-age=0",14 "HTTP_PRAGMA" => "no-cache",15 "HTTP_USER_AGENT" => "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en)",16 "PATH_INFO" => "/homepage/",17 "HTTP_ACCEPT_LANGUAGE" => "en",18 "HTTP_NEGOTIATE" => "trans",19 "HTTP_HOST" => "glu.ttono.us:8007",20 "HTTP_REFERER" => "http://www.google.com/search?q=glu.ttono.us",21 "HTTP_FROM" => "googlebot",22 "SERVER_PROTOCOL" => "HTTP/1.1",23 "REDIRECT_URI" => "/dispatch.fcgi",24 "SCRIPT_NAME" => "/dispatch.fcgi",25 "SERVER_ADDR" => "207.7.108.53",26 "REMOTE_ADDR" => "207.7.108.53",27 "REMOTE_HOST" => "google.com",28 "REMOTE_IDENT" => "kevin",29 "REMOTE_USER" => "kevin",30 "SERVER_SOFTWARE" => "lighttpd/1.4.5",31 "HTTP_COOKIE" => "_session_id=c84ace84796670c052c6ceb2451fb0f2; is_admin=yes",32 "HTTP_X_FORWARDED_SERVER" => "glu.ttono.us",33 "REQUEST_URI" => "/admin",34 "DOCUMENT_ROOT" => "/home/kevinc/sites/typo/public",35 "PATH_TRANSLATED" => "/home/kevinc/sites/typo/public/homepage/",36 "SERVER_PORT" => "8007",37 "QUERY_STRING" => "",38 "REMOTE_PORT" => "63137",39 "GATEWAY_INTERFACE" => "CGI/1.1",40 "HTTP_X_FORWARDED_FOR" => "65.88.180.234",41 "HTTP_ACCEPT" => "*/*",42 "SCRIPT_FILENAME" => "/home/kevinc/sites/typo/public/dispatch.fcgi",43 "REDIRECT_STATUS" => "200",44 "REQUEST_METHOD" => "GET"45 }46 @request = ActionDispatch::Request.new(@env)47 # some Nokia phone browsers omit the space after the semicolon separator.48 # some developers have grown accustomed to using comma in cookie values.49 @alt_cookie_fmt_request = ActionDispatch::Request.new(@env.merge({"HTTP_COOKIE"=>"_session_id=c84ace847,96670c052c6ceb2451fb0f2;is_admin=yes"}))50 end51 private52 def set_content_data(data)53 @request.env['REQUEST_METHOD'] = 'POST'54 @request.env['CONTENT_LENGTH'] = data.length55 @request.env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded; charset=utf-8'56 @request.env['rack.input'] = StringIO.new(data)57 end58end59class RackRequestTest < BaseRackTest60 test "proxy request" do61 assert_equal 'glu.ttono.us', @request.host_with_port62 end63 test "http host" do64 @env.delete "HTTP_X_FORWARDED_HOST"65 @env['HTTP_HOST'] = "rubyonrails.org:8080"66 assert_equal "rubyonrails.org", @request.host67 assert_equal "rubyonrails.org:8080", @request.host_with_port68 @env['HTTP_X_FORWARDED_HOST'] = "www.firsthost.org, www.secondhost.org"69 assert_equal "www.secondhost.org", @request.host70 end71 test "http host with default port overrides server port" do72 @env.delete "HTTP_X_FORWARDED_HOST"73 @env['HTTP_HOST'] = "rubyonrails.org"74 assert_equal "rubyonrails.org", @request.host_with_port75 end76 test "host with port defaults to server name if no host headers" do77 @env.delete "HTTP_X_FORWARDED_HOST"78 @env.delete "HTTP_HOST"79 assert_equal "glu.ttono.us:8007", @request.host_with_port80 end81 test "host with port falls back to server addr if necessary" do82 @env.delete "HTTP_X_FORWARDED_HOST"83 @env.delete "HTTP_HOST"84 @env.delete "SERVER_NAME"85 assert_equal "207.7.108.53", @request.host86 assert_equal 8007, @request.port87 assert_equal "207.7.108.53:8007", @request.host_with_port88 end89 test "host with port if http standard port is specified" do90 @env['HTTP_X_FORWARDED_HOST'] = "glu.ttono.us:80"91 assert_equal "glu.ttono.us", @request.host_with_port92 end93 test "host with port if https standard port is specified" do94 @env['HTTP_X_FORWARDED_PROTO'] = "https"95 @env['HTTP_X_FORWARDED_HOST'] = "glu.ttono.us:443"96 assert_equal "glu.ttono.us", @request.host_with_port97 end98 test "host if ipv6 reference" do99 @env.delete "HTTP_X_FORWARDED_HOST"100 @env['HTTP_HOST'] = "[2001:1234:5678:9abc:def0::dead:beef]"101 assert_equal "[2001:1234:5678:9abc:def0::dead:beef]", @request.host102 end103 test "host if ipv6 reference with port" do104 @env.delete "HTTP_X_FORWARDED_HOST"105 @env['HTTP_HOST'] = "[2001:1234:5678:9abc:def0::dead:beef]:8008"106 assert_equal "[2001:1234:5678:9abc:def0::dead:beef]", @request.host107 end108 test "CGI environment variables" do109 assert_equal "Basic", @request.auth_type110 assert_equal 0, @request.content_length111 assert_equal nil, @request.content_mime_type112 assert_equal "CGI/1.1", @request.gateway_interface113 assert_equal "*/*", @request.accept114 assert_equal "UTF-8", @request.accept_charset115 assert_equal "gzip, deflate", @request.accept_encoding116 assert_equal "en", @request.accept_language117 assert_equal "no-cache, max-age=0", @request.cache_control118 assert_equal "googlebot", @request.from119 assert_equal "glu.ttono.us", @request.host120 assert_equal "trans", @request.negotiate121 assert_equal "no-cache", @request.pragma122 assert_equal "http://www.google.com/search?q=glu.ttono.us", @request.referer123 assert_equal "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en)", @request.user_agent124 assert_equal "/homepage/", @request.path_info125 assert_equal "/home/kevinc/sites/typo/public/homepage/", @request.path_translated126 assert_equal "", @request.query_string127 assert_equal "207.7.108.53", @request.remote_addr128 assert_equal "google.com", @request.remote_host129 assert_equal "kevin", @request.remote_ident130 assert_equal "kevin", @request.remote_user131 assert_equal "GET", @request.request_method132 assert_equal "/dispatch.fcgi", @request.script_name133 assert_equal "glu.ttono.us", @request.server_name134 assert_equal 8007, @request.server_port135 assert_equal "HTTP/1.1", @request.server_protocol136 assert_equal "lighttpd", @request.server_software137 end138 test "cookie syntax resilience" do139 cookies = @request.cookies140 assert_equal "c84ace84796670c052c6ceb2451fb0f2", cookies["_session_id"], cookies.inspect141 assert_equal "yes", cookies["is_admin"], cookies.inspect142 alt_cookies = @alt_cookie_fmt_request.cookies143 #assert_equal "c84ace847,96670c052c6ceb2451fb0f2", alt_cookies["_session_id"], alt_cookies.inspect144 assert_equal "yes", alt_cookies["is_admin"], alt_cookies.inspect145 end146end147class RackRequestParamsParsingTest < BaseRackTest148 test "doesnt break when content type has charset" do149 set_content_data 'flamenco=love'150 assert_equal({"flamenco"=> "love"}, @request.request_parameters)151 end152 test "doesnt interpret request uri as query string when missing" do153 @request.env['REQUEST_URI'] = 'foo'154 assert_equal({}, @request.query_parameters)155 end156end157class RackRequestNeedsRewoundTest < BaseRackTest158 test "body should be rewound" do159 data = 'foo'160 @env['rack.input'] = StringIO.new(data)161 @env['CONTENT_LENGTH'] = data.length162 @env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded; charset=utf-8'163 # Read the request body by parsing params.164 request = ActionDispatch::Request.new(@env)165 request.request_parameters166 # Should have rewound the body.167 assert_equal 0, request.body.pos168 end169end...

Full Screen

Full Screen

consumer.rb

Source:consumer.rb Github

copy

Full Screen

...21 # :body - url form encoded in body of POST request ( option 2. in spec)22 # :query_string - via the query part of the url ( option 3. in spec)23 :scheme=>:header, 24 25 # Default http method used for OAuth Token Requests (defaults to :post)26 :http_method=>:post, 27 28 :oauth_version=>"1.0"29 }30 31 attr_accessor :site,:options, :key, :secret,:http32 33 34 # Create a new consumer instance by passing it a configuration hash:35 #36 # @consumer=OAuth::Consumer.new( key,secret,{37 # :site=>"http://term.ie",38 # :scheme=>:header,39 # :http_method=>:post,40 # :request_token_path=>"/oauth/example/request_token.php",41 # :access_token_path=>"/oauth/example/access_token.php",42 # :authorize_path=>"/oauth/example/authorize.php"43 # })44 #45 # Start the process by requesting a token46 #47 # @request_token=@consumer.get_request_token48 # session[:request_token]=@request_token49 # redirect_to @request_token.authorize_url50 #51 # When user returns create an access_token52 #53 # @access_token=@request_token.get_access_token54 # @photos=@access_token.get('/photos.xml')55 #56 #57 58 def initialize(consumer_key,consumer_secret,options={})59 # ensure that keys are symbols60 @options=@@default_options.merge( options.inject({}) do |options, (key, value)|61 options[key.to_sym] = value62 options63 end)64 @key = consumer_key65 @secret = consumer_secret66 end67 68 def http_method69 @http_method||=@options[:http_method]||:post70 end71 72 def http73 @http ||= Net::HTTP.new(uri.host, uri.port)74 end75 76 # will change77 def uri(url=nil)78 @uri||=URI.parse(url||site)79 end80 81 # Get a Request Token82 def get_request_token83 response=token_request(http_method,request_token_path)84 OAuth::RequestToken.new(self,response[:oauth_token],response[:oauth_token_secret])85 end86 87 # Creates, signs and performs an http request.88 # It's recommended to use the Token classes to set this up correctly.89 # The arguments parameters are a hash or string encoded set of parameters if it's a post request as well as optional http headers.90 # 91 # @consumer.request(:get,'/people',@token,{:scheme=>:query_string})92 # @consumer.request(:post,'/people',@token,{},@person.to_xml,{ 'Content-Type' => 'application/xml' })93 #94 def request(http_method,path, token=nil,request_options={},*arguments)95 http.request(create_signed_request(http_method,path,token,request_options,*arguments))96 end97 98 # Creates and signs an http request.99 # It's recommended to use the Token classes to set this up correctly100 def create_signed_request(http_method,path, token=nil,request_options={},*arguments)101 request=create_http_request(http_method,path,*arguments)102 sign!(request,token,request_options)103 request104 end105 106 # Creates a request and parses the result as url_encoded. This is used internally for the RequestToken and AccessToken requests.107 def token_request(http_method,path,token=nil,request_options={},*arguments)108 response=request(http_method,path,token,request_options,*arguments)109 if response.code=="200"110 CGI.parse(response.body).inject({}){|h,(k,v)| h[k.to_sym]=v.first;h}111 else 112 response.error! 113 end114 end115 # Sign the Request object. Use this if you have an externally generated http request object you want to sign.116 def sign!(request,token=nil, request_options = {})117 request.oauth!(http,self,token,{:scheme=>scheme}.merge(request_options))118 end119 120 # Return the signature_base_string121 def signature_base_string(request,token=nil, request_options = {})122 request.signature_base_string(http,self,token,{:scheme=>scheme}.merge(request_options))123 end124 def site125 @options[:site]126 end127 def scheme128 @options[:scheme]129 end...

Full Screen

Full Screen

gifasent-util.rb

Source:gifasent-util.rb Github

copy

Full Screen

1#!/usr/bin/ruby2require 'rubygems'3require 'json'4require 'optparse'5require 'net/http'6require 'openssl'7require 'uri'8def getResponse(uri, params)9 http = Net::HTTP.new(uri.host,uri.port)10 http.use_ssl=false11 http.verify_mode = OpenSSL::SSL::VERIFY_NONE12 #uri.query = URI.encode_www_form(params)13 request = Net::HTTP::Get.new(uri.request_uri)14 request['Content-Type'] = 'application/json'15 request['Accept'] = 'application/json'16 response = http.request(request)17 response['Content-Type'] = 'application/json'18 #if valid_json?(response.body)19 return JSON.parse(response.body)20 #else21 # return response.body22 #end23end24def putResponse(uri, data)25 http = Net::HTTP.new(uri.host,uri.port)26 http.use_ssl=true27 http.verify_mode = OpenSSL::SSL::VERIFY_NONE28 #uri.query = URI.encode_www_form(params)29 request = Net::HTTP::Put.new(uri.request_uri)30 request['Content-Type'] = 'application/json'31 request['Accept'] = 'application/json'32 request.body=data33 response = http.request(request)34 response['Content-Type'] = 'application/json'35 return JSON.parse(response.body)36end37def patchResponse(uri, data)38 http = Net::HTTP.new(uri.host,uri.port)39 http.use_ssl=true40 http.verify_mode = OpenSSL::SSL::VERIFY_NONE41 #uri.query = URI.encode_www_form(params)42 request = Net::HTTP::Patch.new(uri.request_uri)43 request['Content-Type'] = 'application/json'44 request['Accept'] = 'application/json'45 request.body=data46 response = http.request(request)47 response['Content-Type'] = 'application/json'48 return JSON.parse(response.body)49end50def deleteResponse(uri)51 http = Net::HTTP.new(uri.host,uri.port)52 http.use_ssl=true53 http.verify_mode = OpenSSL::SSL::VERIFY_NONE54 #uri.query = URI.encode_www_form(params)55 request = Net::HTTP::Delete.new(uri.request_uri)56 request['Content-Type'] = 'application/json'57 request['Accept'] = 'application/json'58 response = http.request(request)59 response['Content-Type'] = 'application/json'60end...

Full Screen

Full Screen

Request

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 fmt.Println(err)5 } else {6 fmt.Println(resp)7 }8}9import (10func main() {11 if err != nil {12 fmt.Println(err)13 } else {14 defer resp.Body.Close()15 fmt.Println(resp)16 }17}18import (19func main() {20 if err != nil {21 fmt.Println(err)22 } else {23 defer resp.Body.Close()24 fmt.Println(resp.StatusCode)25 }26}27import (28func main() {29 if err != nil {30 fmt.Println(err)31 } else {32 defer resp.Body.Close()33 fmt.Println(resp.Header)34 }35}36import (37func main() {38 if err != nil {39 fmt.Println(err)40 } else {41 defer resp.Body.Close()42 body, err := ioutil.ReadAll(resp.Body)43 if err != nil {44 fmt.Println(err)45 } else {46 fmt.Println(string(body))47 }48 }49}50import (51func main() {52 if err != nil {53 fmt.Println(err)54 } else {55 defer resp.Body.Close()56 body, err := ioutil.ReadAll(resp.Body

Full Screen

Full Screen

Request

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 fmt.Println("Error:", err)5 }6 fmt.Println("Response status:", resp.Status)7}

Full Screen

Full Screen

Request

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 fmt.Println("Error", err)5 }6 fmt.Println("Response status:", resp.Status)7}8import (9func main() {10 if err != nil {11 fmt.Println("Error", err)12 }13 defer resp.Body.Close()14 fmt.Println("Response status:", resp.Status)15}16import (17func main() {18 if err != nil {19 fmt.Println("Error", err)20 }21 defer resp.Body.Close()22 body, err := ioutil.ReadAll(resp.Body)23 if err != nil {24 fmt.Println("Error", err)25 }26 fmt.Println("Response status:", resp.Status)27 fmt.Println("Response body:", string(body))28}

Full Screen

Full Screen

Request

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 fmt.Println("Error", err)5 }6 fmt.Println(resp)7}8&{200 OK 200 HTTP/1.1 1 1 map[Content-Type:[text/html; charset=ISO-8859-1] Date:[Wed, 27 May 2020 15:12:09 GMT] Expires:[-1] P3p:[CP="This is not a P3P policy! See g.co/p3phelp for more info."] Server:[gws] Set-Cookie:[1P_JAR=2020-05-27-15; expires=Fri, 26-Jun-2020 15:12:09 GMT; path=/; domain=.google.com, NID=204=JlHgGz1YgHfDwKZl8kP8JzvNjN1g6F2j6d3qF3nQn0jJ5c5ZbM5fR0PdJjXy6e1U8J7VlYcY4w7Vw1wG8q7q4Q4E4X7V4k4F8; expires=Thu, 26-Nov-2020 15:12:09 GMT; path=/; domain=.google.com; HttpOnly] Alt-Svc:[quic=":443"; ma=2592000; v="46,43"],0xc0000a9a00 0 [] false false map[] 0xc0000a9a80 0xc0000a9aa0}9import (10func main() {11 if err != nil {12 fmt.Println("Error", err)13 }14 fmt.Println(resp)15}16&{200 OK 200 HTTP/1.1 1 1 map[Alt-Svc:[quic=":443"; ma=2592000

Full Screen

Full Screen

Request

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 resp, err := http.Get(url)4 if err != nil {5 fmt.Println(err)6 os.Exit(1)7 }8 defer resp.Body.Close()9 fmt.Println("Response status:", resp.Status)10 body, err := ioutil.ReadAll(resp.Body)11 if err != nil {12 fmt.Println(err)13 os.Exit(1)14 }15 fmt.Println("16 fmt.Println(string(body))17 fmt.Println("18 io.Copy(os.Stdout, resp.Body)19}20import (21func main() {22 req, err := http.NewRequest("GET", url, nil)23 if err != nil {24 fmt.Println(err)25 os.Exit(1)26 }27 client := &http.Client{}28 resp, err := client.Do(req)29 if err != nil {30 fmt.Println(err)31 os.Exit(1)32 }33 defer resp.Body.Close()34 fmt.Println("Response status:", resp.Status)35 body, err := ioutil.ReadAll(resp.Body)36 if err != nil {37 fmt.Println(err)38 os.Exit(1)39 }40 fmt.Println("41 fmt.Println(string(body))42}43import (44func main() {45 req, err := http.NewRequest("GET", url, nil)46 if err != nil {47 fmt.Println(err)48 os.Exit(1)49 }50 req.Header.Set("User-Agent", "Custom User Agent")51 client := &http.Client{}52 resp, err := client.Do(req)53 if err != nil {54 fmt.Println(err)55 os.Exit(1)56 }57 defer resp.Body.Close()58 fmt.Println("Response status:", resp.Status)59 body, err := ioutil.ReadAll(resp.Body)60 if err != nil {

Full Screen

Full Screen

Request

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 fmt.Println("Error:", err)5 }6 fmt.Println(res)7}

Full Screen

Full Screen

Request

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 fmt.Println(err)5 }6 fmt.Println(resp)7}8&{200 OK 200 HTTP/1.1 1 1 map[Cache-Control:[private, max-age=0] Content-Type:[text/html; charset=ISO-8859-1] Date:[Thu, 16 Sep 2021 06:50:48 GMT] Expires:[-1] P3p:[CP="This is not a P3P policy! See g.co/p3phelp for more info."] Server:[gws] Set-Cookie:[1P_JAR=2021-09-16-06; expires=Sat, 16-Oct-2021 06:50:48 GMT; path=/; domain=.google.com, NID=214=OJ8fH1cCmDZz6BpKjX9Y9iL0vP7o6q3Tn1hW6S4w6ZaRl1n4d9s2nU4H6V7Ry0bB6M8Q2r2KvV7fZq3q3V8W9jKvI1n; expires=Fri, 15-Mar-2024 06:50:48 GMT; path=/; domain=.google.com; HttpOnly] Set-Cookie:[1P_JAR=2021-09-16-06; expires=Sat, 16-Oct-2021 06:50:48 GMT; path=/; domain=.google.com, NID=214=OJ8fH1cCmDZz6BpKjX9Y9iL0vP7o6q3Tn1hW6S4w6ZaRl1n4d9s2nU4H6V7Ry0bB6M8Q2r2KvV7fZq3q3V8W9jKvI1n; expires=Fri, 15-Mar-2024 06:50:48 GMT; path=/; domain=.google.com; HttpOnly

Full Screen

Full Screen

Request

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 fmt.Print(err.Error())5 os.Exit(1)6 }7 defer response.Body.Close()8 content, err := ioutil.ReadAll(response.Body)9 if err != nil {10 fmt.Print(err.Error())11 os.Exit(1)12 }13 fmt.Printf("%s", content)14}

Full Screen

Full Screen

Request

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 fmt.Println(err)5 }6 data, err := ioutil.ReadAll(response.Body)7 if err != nil {8 fmt.Println(err)9 }10 fmt.Println(string(data))11}12import (13func main() {14 if err != nil {15 fmt.Println(err)16 }17 client := &http.Client{}18 response, err := client.Do(request)19 if err != nil {20 fmt.Println(err)21 }22 data, err := ioutil.ReadAll(response.Body)23 if err != nil {24 fmt.Println(err)25 }26 fmt.Println(string(data))27}28import (29func main() {30 if err != nil {31 fmt.Println(err)32 }33 data, err := ioutil.ReadAll(response.Body)34 if err != nil {35 fmt.Println(err)36 }37 fmt.Println(string(data))38}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful