Best Gauge code snippet using result.AddPreHook
router_test.go
Source:router_test.go
...233 if got != want {234 t.Errorf("Status got %d, want %d", got, want)235 }236}237func TestAddPreHookAppendsToHookList(t *testing.T) {238 want := "prehookhandler"239 callStack := ""240 ph := func(ctx *Context) {241 callStack += "prehook"242 }243 rtr := Router{}244 rtr.routes = newMockRoutes()245 rtr.AddPreHook(ph)246 rtr.Get("/test", func(ctx *Context) {247 callStack += "handler"248 })249 w := httptest.NewRecorder()250 req, _ := http.NewRequest("GET", "/test", nil)251 rtr.ServeHTTP(w, req)252 got := callStack253 if got != want {254 t.Errorf("Status got %q, want %q", got, want)255 }256}257func TestPreHooksCalledInOrder(t *testing.T) {258 want := "prehook1prehook2prehook3handler"259 callStack := ""260 ph1 := func(ctx *Context) {261 callStack += "prehook1"262 }263 ph2 := func(ctx *Context) {264 callStack += "prehook2"265 }266 ph3 := func(ctx *Context) {267 callStack += "prehook3"268 }269 rtr := Router{}270 rtr.routes = newMockRoutes()271 rtr.AddPreHook(ph1)272 rtr.AddPreHook(ph2)273 rtr.AddPreHook(ph3)274 rtr.Get("/test", func(ctx *Context) {275 callStack += "handler"276 })277 w := httptest.NewRecorder()278 req, _ := http.NewRequest("GET", "/test", nil)279 rtr.ServeHTTP(w, req)280 got := callStack281 if got != want {282 t.Errorf("Status got %q, want %q", got, want)283 }284}285func TestAddPostHookAppendsToHookList(t *testing.T) {286 want := "handlerposthook"287 callStack := ""288 ph := func(ctx *Context) {289 callStack += "posthook"290 }291 rtr := Router{}292 rtr.routes = newMockRoutes()293 rtr.AddPostHook(ph)294 rtr.Get("/test", func(ctx *Context) {295 callStack += "handler"296 })297 w := httptest.NewRecorder()298 req, _ := http.NewRequest("GET", "/test", nil)299 rtr.ServeHTTP(w, req)300 got := callStack301 if got != want {302 t.Errorf("Status got %q, want %q", got, want)303 }304}305func TestPostHooksCalledInOrder(t *testing.T) {306 want := "handlerposthook1posthook2posthook3"307 callStack := ""308 ph1 := func(ctx *Context) {309 callStack += "posthook1"310 }311 ph2 := func(ctx *Context) {312 callStack += "posthook2"313 }314 ph3 := func(ctx *Context) {315 callStack += "posthook3"316 }317 rtr := Router{}318 rtr.routes = newMockRoutes()319 rtr.AddPostHook(ph1)320 rtr.AddPostHook(ph2)321 rtr.AddPostHook(ph3)322 rtr.Get("/test", func(ctx *Context) {323 callStack += "handler"324 })325 w := httptest.NewRecorder()326 req, _ := http.NewRequest("GET", "/test", nil)327 rtr.ServeHTTP(w, req)328 got := callStack329 if got != want {330 t.Errorf("Status got %q, want %q", got, want)331 }332}333func TestPostHookResponsesAreIgnored(t *testing.T) {334 ph := func(ctx *Context) {335 ctx.RespondWith("with biscuits").WithStatus(204)336 }337 rtr := Router{}338 rtr.routes = newMockRoutes()339 rtr.AddPostHook(ph)340 rtr.Get("/test", func(ctx *Context) {341 ctx.RespondWith("Mango trees").WithStatus(200)342 })343 w := httptest.NewRecorder()344 req, _ := http.NewRequest("GET", "/test", nil)345 rtr.ServeHTTP(w, req)346 want := 200347 got := w.Code348 if got != want {349 t.Errorf("Status got %d, want %d", got, want)350 }351 wantBody := "Mango trees"352 gotBody := w.Body.String()353 if gotBody != wantBody {354 t.Errorf("Body got %q, want %q", gotBody, wantBody)355 }356}357func TestPreHookWriterResponsesPreventMainHandlerRunning(t *testing.T) {358 ph := func(ctx *Context) {359 ctx.Writer.WriteHeader(204)360 ctx.Writer.Write([]byte("with biscuits"))361 }362 rtr := Router{}363 rtr.routes = newMockRoutes()364 rtr.AddPreHook(ph)365 rtr.Get("/test", func(ctx *Context) {366 ctx.RespondWith("Mango trees").WithStatus(200)367 })368 w := httptest.NewRecorder()369 req, _ := http.NewRequest("GET", "/test", nil)370 rtr.ServeHTTP(w, req)371 want := 204372 got := w.Code373 if got != want {374 t.Errorf("Status got %d, want %d", got, want)375 }376 wantBody := "with biscuits"377 gotBody := w.Body.String()378 if gotBody != wantBody {379 t.Errorf("Body got %q, want %q", gotBody, wantBody)380 }381}382func TestPreHookContextResponsesPreventMainHandlerRunning(t *testing.T) {383 ph := func(ctx *Context) {384 ctx.RespondWith("with biscuits").WithStatus(204)385 }386 rtr := Router{}387 rtr.routes = newMockRoutes()388 rtr.AddPreHook(ph)389 rtr.Get("/test", func(ctx *Context) {390 ctx.RespondWith("Mango trees").WithStatus(200)391 })392 w := httptest.NewRecorder()393 req, _ := http.NewRequest("GET", "/test", nil)394 rtr.ServeHTTP(w, req)395 want := 204396 got := w.Code397 if got != want {398 t.Errorf("Status got %d, want %d", got, want)399 }400 wantBody := "with biscuits"401 gotBody := w.Body.String()402 if gotBody != wantBody {403 t.Errorf("Body got %q, want %q", gotBody, wantBody)404 }405}406func TestPreHookWriterResponsesPreventSubsequentPreHooksRunning(t *testing.T) {407 ph1 := func(ctx *Context) {408 ctx.Writer.WriteHeader(204)409 ctx.Writer.Write([]byte("with biscuits"))410 }411 ph2 := func(ctx *Context) {412 t.Errorf("Subsequent PreHooks not ignored")413 }414 rtr := Router{}415 rtr.routes = newMockRoutes()416 rtr.AddPreHook(ph1)417 rtr.AddPreHook(ph2)418 rtr.Get("/test", func(ctx *Context) {419 ctx.RespondWith("Mango trees").WithStatus(200)420 })421 w := httptest.NewRecorder()422 req, _ := http.NewRequest("GET", "/test", nil)423 rtr.ServeHTTP(w, req)424}425func TestPreHookContextResponsesPreventSubsequentPreHooksRunning(t *testing.T) {426 ph1 := func(ctx *Context) {427 ctx.RespondWith("with biscuits").WithStatus(204)428 }429 ph2 := func(ctx *Context) {430 t.Errorf("Subsequent PreHooks not ignored")431 }432 rtr := Router{}433 rtr.routes = newMockRoutes()434 rtr.AddPreHook(ph1)435 rtr.AddPreHook(ph2)436 rtr.Get("/test", func(ctx *Context) {437 ctx.RespondWith("Mango trees").WithStatus(200)438 })439 w := httptest.NewRecorder()440 req, _ := http.NewRequest("GET", "/test", nil)441 rtr.ServeHTTP(w, req)442}443func TestPreHookContextResponsesCanSerializeModel(t *testing.T) {444 want := "{\"Name\":\"Mango\",\"Size\":34,\"Edible\":true}\n"445 ph := func(ctx *Context) {446 m := struct {447 Name string448 Size int449 Edible bool450 }{451 "Mango", 34, true,452 }453 ctx.RespondWith(m)454 }455 rtr := Router{}456 rtr.routes = newMockRoutes()457 rtr.EncoderEngine = newEncoderEngine()458 rtr.AddPreHook(ph)459 rtr.Get("/test", func(ctx *Context) {460 ctx.RespondWith("Mango trees").WithStatus(200)461 })462 w := httptest.NewRecorder()463 req, _ := http.NewRequest("GET", "/test", nil)464 req.Header.Set("Accept", "application/json")465 rtr.ServeHTTP(w, req)466 got := w.Body.String()467 if got != want {468 t.Errorf("Body got %s, want %s", got, want)469 }470}471func TestGetSimpleTextResponse(t *testing.T) {472 rtr := Router{}473 rtr.routes = newMockRoutes()474 rtr.Get("/test", func(ctx *Context) {475 ctx.RespondWith("We're just two lost souls swimming in a fish bowl")476 })477 w := httptest.NewRecorder()478 req, _ := http.NewRequest("GET", "/test", nil)479 rtr.ServeHTTP(w, req)480 want := "We're just two lost souls swimming in a fish bowl"481 got := w.Body.String()482 if got != want {483 t.Errorf("Response got %q, want %q", got, want)484 }485}486func TestGetResponseStatus(t *testing.T) {487 rtr := Router{}488 rtr.routes = newMockRoutes()489 rtr.Get("/test", func(ctx *Context) {490 ctx.Respond().WithStatus(404)491 })492 w := httptest.NewRecorder()493 req, _ := http.NewRequest("GET", "/test", nil)494 rtr.ServeHTTP(w, req)495 want := 404496 got := w.Code497 if got != want {498 t.Errorf("Status got %d, want %d", got, want)499 }500}501func TestGetEncodedResponse(t *testing.T) {502 rtr := Router{}503 rtr.routes = newMockRoutes()504 rtr.EncoderEngine = &mockEncoderEngine{}505 var model = struct {506 a string507 b string508 c int509 }{510 "mango", "biscuits", 34,511 }512 rtr.Get("/test", func(ctx *Context) {513 ctx.Respond().WithModel(fmt.Sprint(model))514 })515 w := httptest.NewRecorder()516 req, _ := http.NewRequest("GET", "/test", nil)517 req.Header.Set("Accept", "test/test")518 rtr.ServeHTTP(w, req)519 want := fmt.Sprint(model)520 got := w.Body.String()521 if got != want {522 t.Errorf("Response got %q, want %q", got, want)523 }524}525func TestResponseCodeWhenRequestAcceptHeaderIsUnsupported(t *testing.T) {526 rtr := Router{}527 rtr.routes = newMockRoutes()528 rtr.EncoderEngine = &mockEncoderEngine{}529 var model = struct {530 a string531 b string532 c int533 }{534 "mango", "biscuits", 34,535 }536 rtr.Get("/test", func(ctx *Context) {537 ctx.Respond().WithModel(fmt.Sprint(model))538 })539 w := httptest.NewRecorder()540 req, _ := http.NewRequest("GET", "/test", nil)541 req.Header.Set("Accept", "test/mango")542 rtr.ServeHTTP(w, req)543 want := 406544 got := w.Code545 if got != want {546 t.Errorf("Status got %d, want %d", got, want)547 }548}549func TestResponseMessageWhenRequestAcceptHeaderIsUnsupported(t *testing.T) {550 rtr := Router{}551 rtr.routes = newMockRoutes()552 rtr.EncoderEngine = &mockEncoderEngine{}553 var model = struct {554 a string555 b string556 c int557 }{558 "mango", "biscuits", 34,559 }560 rtr.Get("/test", func(ctx *Context) {561 ctx.Respond().WithModel(fmt.Sprint(model))562 })563 w := httptest.NewRecorder()564 req, _ := http.NewRequest("GET", "/test", nil)565 req.Header.Set("Accept", "test/mango")566 rtr.ServeHTTP(w, req)567 want := "Unable to encode to requested acceptable formats: \"test/mango\"\n"568 got := w.Body.String()569 if got != want {570 t.Errorf("Error message got %q, want %q", got, want)571 }572}573func TestResponseCodeWhenErrorEncodingPayload(t *testing.T) {574 rtr := Router{}575 rtr.routes = newMockRoutes()576 rtr.EncoderEngine = &mockEncoderEngine{}577 var model = struct {578 a string579 b string580 c int581 }{582 "mango", "biscuits", 34,583 }584 rtr.Get("/test", func(ctx *Context) {585 ctx.Respond().WithModel(model)586 })587 w := httptest.NewRecorder()588 req, _ := http.NewRequest("GET", "/test", nil)589 req.Header.Set("Accept", "test/test")590 rtr.ServeHTTP(w, req)591 want := 500592 got := w.Code593 if got != want {594 t.Errorf("Status got %d, want %d", got, want)595 }596}597func TestResponseMessageWhenErrorEncodingPayload(t *testing.T) {598 rtr := Router{}599 rtr.routes = newMockRoutes()600 rtr.EncoderEngine = &mockEncoderEngine{}601 var model = struct {602 a string603 b string604 c int605 }{606 "mango", "biscuits", 34,607 }608 rtr.Get("/test", func(ctx *Context) {609 ctx.Respond().WithModel(model)610 })611 w := httptest.NewRecorder()612 req, _ := http.NewRequest("GET", "/test", nil)613 req.Header.Set("Accept", "test/test")614 rtr.ServeHTTP(w, req)615 want := "Internal Server Error\n"616 got := w.Body.String()617 if got != want {618 t.Errorf("Error message got %q, want %q", got, want)619 }620}621func TestGetStaticResponse(t *testing.T) {622 rtr := Router{}623 rtr.routes = newMockRoutes()624 rtr.StaticDir("static")625 w := httptest.NewRecorder()626 req, _ := http.NewRequest("GET", "/test.html", nil)627 rtr.ServeHTTP(w, req)628 want := "<html>Test Static</html>\n"629 got := w.Body.String()630 if got != want {631 t.Errorf("Response got %q, want %q", got, want)632 }633}634func TestGetStaticResponseStatus(t *testing.T) {635 rtr := Router{}636 rtr.routes = newMockRoutes()637 rtr.StaticDir("static")638 w := httptest.NewRecorder()639 req, _ := http.NewRequest("GET", "/test.html", nil)640 rtr.ServeHTTP(w, req)641 want := 200642 got := w.Code643 if got != want {644 t.Errorf("Status got %d, want %d", got, want)645 }646}647func TestGetStaticRedirectsWhenIndexHtml(t *testing.T) {648 rtr := Router{}649 rtr.routes = newMockRoutes()650 rtr.StaticDir("static")651 w := httptest.NewRecorder()652 req, _ := http.NewRequest("GET", "/index.html", nil)653 rtr.ServeHTTP(w, req)654 want := 301655 got := w.Code656 if got != want {657 t.Errorf("Status got %d, want %d", got, want)658 }659}660func TestGetStaticRedirectsToRootWhenIndexHtml(t *testing.T) {661 rtr := Router{}662 rtr.routes = newMockRoutes()663 rtr.StaticDir("static")664 w := httptest.NewRecorder()665 req, _ := http.NewRequest("GET", "/index.html", nil)666 rtr.ServeHTTP(w, req)667 want := "./"668 //fmt.Println(w.HeaderMap)669 got := w.HeaderMap.Get("Location")670 if got != want {671 t.Errorf("Location got %q, want %q", got, want)672 }673}674func TestGetStaticRootReturnsIndexHtml(t *testing.T) {675 rtr := Router{}676 rtr.routes = newMockRoutes()677 rtr.StaticDir("static")678 w := httptest.NewRecorder()679 req, _ := http.NewRequest("GET", "", nil)680 rtr.ServeHTTP(w, req)681 want := "<html>Index Static</html>\n"682 got := w.Body.String()683 if got != want {684 t.Errorf("Response got %q, want %q", got, want)685 }686}687func TestNewRouterSetsValidationHandler(t *testing.T) {688 want := reflect.TypeOf(&elementValidationHandler{}).String()689 r := NewRouter()690 if r.ValidationHandler == nil {691 t.Errorf("ValidationHandler type = \"<nil>\", want %q", want)692 return693 }694 got := reflect.TypeOf(r.ValidationHandler).String()695 if got != want {696 t.Errorf("ValidationHandler got %q, want %q", got, want)697 }698}699func TestNewRouterSetsRoutes(t *testing.T) {700 want := reflect.TypeOf(&tree{}).String()701 r := NewRouter()702 if r.routes == nil {703 t.Errorf("Routes type = \"<nil>\", want %q", want)704 return705 }706 got := reflect.TypeOf(r.routes).String()707 if got != want {708 t.Errorf("Routes type got %q, want %q", got, want)709 }710}711func TestNewRouterSetsRoutesValidationHandler(t *testing.T) {712 want := reflect.TypeOf(&elementValidationHandler{}).String()713 r := NewRouter()714 if r.routes == nil {715 t.Errorf("Routes type = \"<nil>\", want %q", want)716 return717 }718 tr := r.routes.(*tree)719 got := reflect.TypeOf(tr.validators).String()720 if got != want {721 t.Errorf("Routes type got %q, want %q", got, want)722 }723}724func TestNewRouterSetsEncoderEngine(t *testing.T) {725 want := reflect.TypeOf(&encoderEngine{}).String()726 r := NewRouter()727 if r.EncoderEngine == nil {728 t.Errorf("EncoderEngine type = \"<nil>\", want %q", want)729 return730 }731 got := reflect.TypeOf(r.EncoderEngine).String()732 if got != want {733 t.Errorf("EncoderEngine got %q, want %q", got, want)734 }735}736func TestNewRouterInitialisesEncoderEngineWithDefaultMediaType(t *testing.T) {737 want := DefaultMediaType738 r := NewRouter()739 got := r.EncoderEngine.DefaultMediaType()740 if got != want {741 t.Errorf("EncoderEngine.DefaultMediaType got %q, want %q", got, want)742 }743}744func TestNewRouterSetsAutoPopulateOptionsAllowToTrue(t *testing.T) {745 want := true746 r := NewRouter()747 got := r.AutoPopulateOptionsAllow748 if got != want {749 t.Errorf("AutoPopulateOptionsAllow = %t, want %t", got, want)750 }751}752func TestRegisterModulesWithEmptyModuleRegistersNoNewRoutes(t *testing.T) {753 want := 0754 r := Router{}755 r.routes = newMockRoutes()756 r.RegisterModules([]Registerer{757 emptyTestModule{},758 })759 got := len(r.routes.(*mockRoutes).routes)760 if got != want {761 t.Errorf("Route count got %d, want %d", got, want)762 }763}764func TestRegisterModulesWithSingleModuleRegistersRoutes(t *testing.T) {765 want := 1766 r := Router{}767 r.routes = newMockRoutes()768 r.RegisterModules([]Registerer{769 singleRouteTestModule{},770 })771 s, _ := r.routes.GetResource("/single")772 got := len(s.Handlers)773 if got != want {774 t.Errorf("Route count got %d, want %d", got, want)775 }776}777func TestRegisterModulesWithMultipleModulesRegistersRoutes(t *testing.T) {778 want := 3779 r := Router{}780 r.routes = newMockRoutes()781 r.RegisterModules([]Registerer{782 singleRouteTestModule{},783 multiRouteTestModule{},784 })785 s, _ := r.routes.GetResource("/single")786 m, _ := r.routes.GetResource("/multi")787 got := len(s.Handlers) + len(m.Handlers)788 if got != want {789 t.Errorf("Route count got %d, want %d", got, want)790 }791}792func TestRegisterModulesDoesNotAffectExisingRegistrations(t *testing.T) {793 want := 3794 r := Router{}795 r.routes = newMockRoutes()796 r.Get("/single", testFunc)797 r.RegisterModules([]Registerer{798 multiRouteTestModule{},799 })800 s, _ := r.routes.GetResource("/single")801 m, _ := r.routes.GetResource("/multi")802 got := len(s.Handlers) + len(m.Handlers)803 if got != want {804 t.Errorf("Route count got %d, want %d", got, want)805 }806}807func TestRegisterModulesPanicsWhenAttemptingDuplicateRoute(t *testing.T) {808 defer func() {809 if r := recover(); r == nil {810 t.Errorf("The code did not panic")811 }812 }()813 r := Router{}814 r.routes = newMockRoutes()815 r.RegisterModules([]Registerer{816 singleRouteTestModule{},817 duplicateRouteTestModule{},818 })819}820func encFunc(io.Writer) Encoder {821 return nil822}823func decFunc(io.ReadCloser) Decoder {824 return nil825}826func TestRouterAddValidator(t *testing.T) {827 want := true828 r := Router{}829 evh := elementValidationHandler{}830 evh.validators = make(map[string]Validator)831 r.ValidationHandler = &evh832 r.AddValidator(&Int32Validator{})833 _, valid := r.IsValid("123", "int32")834 got := valid835 if got != want {836 t.Errorf("Valid = %t, want %t", got, want)837 }838}839func TestRouterAddValidators(t *testing.T) {840 want := true841 r := Router{}842 evh := elementValidationHandler{}843 evh.validators = make(map[string]Validator)844 r.ValidationHandler = &evh845 r.AddValidators([]Validator{&Int32Validator{}})846 _, valid := r.IsValid("123", "int32")847 got := valid848 if got != want {849 t.Errorf("Valid = %t, want %t", got, want)850 }851}852func TestRouterAddValidatorPanicsIfConstraintConflicts(t *testing.T) {853 defer func() {854 if r := recover(); r != nil {855 want := "conflicting constraint type: int32"856 got := r857 if got != want {858 t.Errorf("Error message got %q, want %q", got, want)859 }860 } else {861 t.Errorf("The code did not panic")862 }863 }()864 r := Router{}865 evh := elementValidationHandler{}866 evh.validators = make(map[string]Validator)867 r.ValidationHandler = &evh868 r.AddValidator(&Int32Validator{})869 r.AddValidator(&dupValidator{})870}871func TestRouterAddValidatorsPanicsIfConstraintConflicts(t *testing.T) {872 defer func() {873 if r := recover(); r != nil {874 want := "conflicting constraint type: int32"875 got := r876 if got != want {877 t.Errorf("Error message got %q, want %q", got, want)878 }879 } else {880 t.Errorf("The code did not panic")881 }882 }()883 r := Router{}884 evh := elementValidationHandler{}885 evh.validators = make(map[string]Validator)886 r.ValidationHandler = &evh887 r.AddValidators([]Validator{888 &Int32Validator{},889 &dupValidator{},890 })891}892func TestRouterRequestLoggingWhenNotFound(t *testing.T) {893 // no routes, so code: 404 and "404 page not found\n" - 19 bytes894 want := "127.0.0.1 - - [11/Oct/2000:13:55:36 -0700] \"GET /spaceweasel/mango/stone.png HTTP/1.1\" 404 19"895 location := time.FixedZone("test", -25200)896 start := time.Date(2000, 10, 11, 13, 55, 36, 0, location)897 nowUTC = func() time.Time {898 return start899 }900 req, _ := http.NewRequest("GET", "https://github.com/spaceweasel/mango/stone.png", nil)901 req.RemoteAddr = "127.0.0.1"902 w := httptest.NewRecorder()903 got := ""904 r := Router{}905 r.RequestLogger = func(l *RequestLog) {906 got = l.CommonFormat()907 if got != want {908 t.Errorf("Log got %q, want %q", got, want)909 }910 }911 r.routes = newMockRoutes()912 r.ServeHTTP(w, req)913}914func TestRouterRequestLoggingWithUserHandler(t *testing.T) {915 want := "127.0.0.1 - - [11/Oct/2000:13:55:36 -0700] \"GET /mango HTTP/1.1\" 200 19"916 location := time.FixedZone("test", -25200)917 start := time.Date(2000, 10, 11, 13, 55, 36, 0, location)918 nowUTC = func() time.Time {919 return start920 }921 req, _ := http.NewRequest("GET", "https://somewhere.com/mango", nil)922 req.RemoteAddr = "127.0.0.1"923 w := httptest.NewRecorder()924 got := ""925 r := Router{}926 r.RequestLogger = func(l *RequestLog) {927 got = l.CommonFormat()928 if got != want {929 t.Errorf("Log got %q, want %q", got, want)930 }931 }932 r.routes = newMockRoutes()933 r.routes.AddHandlerFunc("/mango", "GET", func(c *Context) {934 c.RespondWith("A mango in the hand")935 })936 r.ServeHTTP(w, req)937}938func TestRouterRequestLoggingWithNoContentResponse(t *testing.T) {939 want := "127.0.0.1 - - [11/Oct/2000:13:55:36 -0700] \"GET /mango HTTP/1.1\" 204 0"940 location := time.FixedZone("test", -25200)941 start := time.Date(2000, 10, 11, 13, 55, 36, 0, location)942 nowUTC = func() time.Time {943 return start944 }945 req, _ := http.NewRequest("GET", "https://somewhere.com/mango", nil)946 req.RemoteAddr = "127.0.0.1"947 w := httptest.NewRecorder()948 got := ""949 r := Router{}950 r.RequestLogger = func(l *RequestLog) {951 got = l.CommonFormat()952 if got != want {953 t.Errorf("Log got %q, want %q", got, want)954 }955 }956 r.routes = newMockRoutes()957 r.routes.AddHandlerFunc("/mango", "GET", func(c *Context) {958 c.RespondWith(204)959 })960 r.ServeHTTP(w, req)961}962func TestRouterRequestLoggingWhenUnRecoveredPanic(t *testing.T) {963 msg := "Internal Server Error\n"964 bCount := strconv.Itoa(len(msg))965 want := "127.0.0.1 - - [11/Oct/2000:13:55:36 -0700] \"GET /mango HTTP/1.1\" 500 " + bCount966 location := time.FixedZone("test", -25200)967 start := time.Date(2000, 10, 11, 13, 55, 36, 0, location)968 nowUTC = func() time.Time {969 return start970 }971 req, _ := http.NewRequest("GET", "https://somewhere.com/mango", nil)972 req.RemoteAddr = "127.0.0.1"973 w := httptest.NewRecorder()974 r := Router{}975 ch := make(chan string)976 r.RequestLogger = func(l *RequestLog) {977 ch <- l.CommonFormat()978 }979 r.routes = newMockRoutes()980 r.routes.AddHandlerFunc("/mango", "GET", func(c *Context) {981 panic("what no mangoes!")982 })983 r.ServeHTTP(w, req)984 select {985 case got := <-ch:986 if got != want {987 t.Errorf("Log got %q, want %q", got, want)988 }989 case <-time.After(time.Second * 3):990 t.Errorf("Timed out")991 }992}993func TestRouterRequestLoggerIsUpdatedWhenAuthenticated(t *testing.T) {994 want := "Mungo"995 ch := make(chan string)996 req, _ := http.NewRequest("GET", "https://somewhere.com/mango", nil)997 req.RemoteAddr = "127.0.0.1"998 w := httptest.NewRecorder()999 r := Router{}1000 r.RequestLogger = func(l *RequestLog) {1001 ch <- l.UserID1002 }1003 r.routes = newMockRoutes()1004 r.routes.AddHandlerFunc("/mango", "GET", func(c *Context) {1005 //c.RespondWith("A mango in the hand")1006 })1007 r.AddPreHook(func(c *Context) {1008 c.Identity = BasicIdentity{Username: "Mungo"}1009 })1010 r.ServeHTTP(w, req)1011 got := <-ch1012 if got != want {1013 t.Errorf("UserID got %q, want %q", got, want)1014 }1015}1016func TestRouterRequestLoggerIsUpdatedWithContextX(t *testing.T) {1017 want := 421018 ch := make(chan interface{})1019 req, _ := http.NewRequest("GET", "https://somewhere.com/mango", nil)1020 req.RemoteAddr = "127.0.0.1"1021 w := httptest.NewRecorder()1022 r := Router{}1023 r.RequestLogger = func(l *RequestLog) {1024 ch <- l.Context()1025 }1026 r.routes = newMockRoutes()1027 r.routes.AddHandlerFunc("/mango", "GET", func(c *Context) {1028 //c.RespondWith("A mango in the hand")1029 })1030 r.AddPreHook(func(c *Context) {1031 c.X = 421032 })1033 r.ServeHTTP(w, req)1034 x := <-ch1035 got := x1036 if got != want {1037 t.Errorf("Context X got %v, want %v", got, want)1038 }1039}1040func TestRouterRequestLoggerIsUpdatedWithContextIdentity(t *testing.T) {1041 want := "Jeff"1042 ch := make(chan Identity)1043 req, _ := http.NewRequest("GET", "https://somewhere.com/mango", nil)1044 req.RemoteAddr = "127.0.0.1"1045 w := httptest.NewRecorder()1046 r := Router{}1047 r.RequestLogger = func(l *RequestLog) {1048 ch <- l.Identity()1049 }1050 r.routes = newMockRoutes()1051 r.routes.AddHandlerFunc("/mango", "GET", func(c *Context) {1052 //c.RespondWith("A mango in the hand")1053 })1054 r.AddPreHook(func(c *Context) {1055 c.Identity = BasicIdentity{Username: "Jeff"}1056 })1057 r.ServeHTTP(w, req)1058 identity := <-ch1059 if identity == nil {1060 t.Errorf("Identity is nil")1061 return1062 }1063 got := identity.UserID()1064 if got != want {1065 t.Errorf("UserID got %q, want %q", got, want)1066 }1067}1068func TestRouterErrorLoggingMsgHasSummaryAsFirstLineWhenUnRecoveredPanic(t *testing.T) {...
result.go
Source:result.go
...9type Result interface {10 GetPreHook() []*gauge_messages.ProtoHookFailure11 GetPostHook() []*gauge_messages.ProtoHookFailure12 GetFailed() bool13 AddPreHook(...*gauge_messages.ProtoHookFailure)14 AddPostHook(...*gauge_messages.ProtoHookFailure)15 SetFailure()16 Item() interface{}17 ExecTime() int6418}19// ExecTimeTracker is an interface for tracking execution time20type ExecTimeTracker interface {21 AddExecTime(int64)22}23// GetProtoHookFailure returns the failure result of hook execution24func GetProtoHookFailure(executionResult *gauge_messages.ProtoExecutionResult) *(gauge_messages.ProtoHookFailure) {25 return &gauge_messages.ProtoHookFailure{26 StackTrace: executionResult.StackTrace,27 ErrorMessage: executionResult.ErrorMessage,28 FailureScreenshotFile: executionResult.FailureScreenshotFile,29 TableRowIndex: -1,30 }31}32// AddPreHook adds the before hook execution result to the actual result object33func AddPreHook(result Result, executionResult *gauge_messages.ProtoExecutionResult) {34 if executionResult.GetFailed() {35 result.AddPreHook(GetProtoHookFailure(executionResult))36 result.SetFailure()37 }38}39// AddPostHook adds the after hook execution result to the actual result object40func AddPostHook(result Result, executionResult *gauge_messages.ProtoExecutionResult) {41 if executionResult.GetFailed() {42 result.AddPostHook(GetProtoHookFailure(executionResult))43 result.SetFailure()44 }45}...
example.go
Source:example.go
...31 lifecycle := glc.NewLifecycle()32 lifecycle.AddTask(task1Name, incrementTask)33 lifecycle.AddTask(task2Name, incrementTask)34 lifecycle.AddTask(lastTaskName, printOut)35 lifecycle.AddPreHook(task2Name, task3Name, incrementTask)36 lifecycle.Execute(&c)37}
AddPreHook
Using AI Code Generation
1import (2func main() {3 xlsx, err := excelize.OpenFile("Book1.xlsx")4 if err != nil {5 fmt.Println(err)6 }7 cell, err := xlsx.GetCellValue("Sheet1", "B2")8 if err != nil {9 fmt.Println(err)10 }11 fmt.Println(cell)12 index := xlsx.GetSheetIndex("Sheet1")13 xlsx.SetCellValue("Sheet1", "B2", "Hello world.")14 xlsx.SetCellValue("Sheet1", "A2", 100)15 xlsx.SetCellValue("Sheet1", "A3", 200)16 xlsx.SetCellValue("Sheet1", "A4", 300)17 xlsx.SetCellValue("Sheet1", "A5", 400)18 xlsx.SetCellValue("Sheet1", "A6", 500)19 xlsx.SetCellValue("Sheet1", "A7", 600)20 xlsx.SetCellValue("Sheet1", "A8", 700)21 xlsx.SetCellValue("Sheet1", "A9", 800)22 xlsx.SetCellValue("Sheet1", "A10", 900)23 xlsx.SetCellValue("Sheet1", "A11", 1000)24 xlsx.SetCellValue("Sheet1", "A12", 1100)25 xlsx.SetCellValue("Sheet1", "A13", 1200)26 xlsx.SetCellValue("Sheet1", "A14", 1300)27 xlsx.SetCellValue("Sheet1", "A15", 1400)28 xlsx.SetCellValue("Sheet1", "A16", 1500)29 xlsx.SetCellValue("Sheet1", "A17", 1600)30 xlsx.SetCellValue("Sheet1", "A18", 1700)31 xlsx.SetCellValue("Sheet1", "A19", 1800)32 xlsx.SetCellValue("Sheet1", "A20", 1900)33 xlsx.SetCellValue("Sheet1", "A21", 2000)34 xlsx.SetCellValue("Sheet1", "A22", 2100)35 xlsx.SetCellValue("Sheet1", "A23", 2200)36 xlsx.SetCellValue("Sheet1",
AddPreHook
Using AI Code Generation
1result := NewResult()2result.AddPreHook(func() {3 fmt.Println("Pre hook called")4})5result := NewResult()6result.AddPostHook(func() {7 fmt.Println("Post hook called")8})9result := NewResult()10result.AddHook(func() {11 fmt.Println("Hook called")12})13result := NewResult()14result.AddPreHook(func() {15 fmt.Println("Pre hook called")16})17result.AddPostHook(func() {18 fmt.Println("Post hook called")19})20result.AddHook(func() {21 fmt.Println("Hook called")22})23result := NewResult()24result.AddPreHook(func() {25 fmt.Println("Pre hook called")26})27result.AddPostHook(func() {28 fmt.Println("Post hook called")29})30result.AddHook(func() {31 fmt.Println("Hook called")32})33result.Pre()34result := NewResult()35result.AddPreHook(func() {36 fmt.Println("Pre hook called")37})38result.AddPostHook(func() {39 fmt.Println("Post hook called")40})41result.AddHook(func() {42 fmt.Println("Hook called")43})44result.Post()45result := NewResult()46result.AddPreHook(func() {47 fmt.Println("Pre hook called")48})49result.AddPostHook(func() {50 fmt.Println("Post hook called")51})52result.AddHook(func() {53 fmt.Println("Hook called")54})
AddPreHook
Using AI Code Generation
1import "fmt"2type result struct {3 preHook func()4}5func (r *result) AddPreHook(f func()) {6}7func (r *result) pre() {8 if r.preHook != nil {9 r.preHook()10 }11}12func main() {13 r := &result{}14 r.AddPreHook(func() {15 fmt.Println("pre hook called")16 })17 r.pre()18}19import "fmt"20type result struct {21 postHook func()22}23func (r *result) AddPostHook(f func()) {24}25func (r *result) post() {26 if r.postHook != nil {27 r.postHook()28 }29}30func main() {31 r := &result{}32 r.AddPostHook(func() {33 fmt.Println("post hook called")34 })35 r.post()36}37import "fmt"38type result struct {39 preHook func()40 postHook func()41}42func (r *result) AddPreHook(f func()) {43}44func (r *result) AddPostHook(f func()) {45}46func (r *result) pre() {47 if r.preHook != nil {48 r.preHook()49 }50}51func (r *result) post() {52 if r.postHook != nil {53 r.postHook()54 }55}56func main() {57 r := &result{}58 r.AddPreHook(func() {59 fmt.Println("pre hook called")60 })61 r.AddPostHook(func() {62 fmt.Println("post hook called")63 })64 r.pre()65 r.post()66}67import "fmt"68type result struct {
AddPreHook
Using AI Code Generation
1func main() {2 result := gexec.NewResult()3 result.AddPreHook(func(result *gexec.Result) {4 fmt.Println("Pre hook called")5 })6 result.AddPostHook(func(result *gexec.Result) {7 fmt.Println("Post hook called")8 })9 result.Start()10 result.Wait()11 result.Stop()12}13func main() {14 result := gexec.NewResult()15 result.AddPreHook(func(result *gexec.Result) {16 fmt.Println("Pre hook called")17 })18 result.AddPostHook(func(result *gexec.Result) {19 fmt.Println("Post hook called")20 })21 result.Start()22 result.Wait()23 result.Stop()24}25func main() {26 result := gexec.NewResult()27 result.AddPreHook(func(result *gexec.Result) {28 fmt.Println("Pre hook called")29 })30 result.AddPostHook(func(result *gexec.Result) {31 fmt.Println("Post hook called")32 })33 result.Start()34 result.Wait()35 result.Stop()36}37func main() {38 result := gexec.NewResult()39 result.AddPreHook(func(result *gexec.Result) {40 fmt.Println("Pre hook called")41 })42 result.AddPostHook(func(result *gexec.Result) {43 fmt.Println("Post hook called")44 })45 result.Start()46 result.Wait()47 result.Stop()48}49func main() {50 result := gexec.NewResult()51 result.AddPreHook(func(result *gexec.Result) {52 fmt.Println("Pre hook called")53 })54 result.AddPostHook(func(result *gexec.Result) {55 fmt.Println("Post hook called")56 })57 result.Start()58 result.Wait()59 result.Stop()60}
AddPreHook
Using AI Code Generation
1result.AddPreHook(func (r *Result) error {2})3result.AddPostHook(func (r *Result) error {4})5result.AddPreHook(func (r *Result) error {6})7result.AddPostHook(func (r *Result) error {8})9result.AddPreHook(func (r *Result) error {10})11result.AddPostHook(func (r *Result) error {12})13result.AddPreHook(func (r *Result) error {14})15result.AddPostHook(func (r *Result) error {16})17result.AddPreHook(func (r *Result) error {18})19result.AddPostHook(func (r *Result) error {20})21result.AddPreHook(func (r *Result) error {22})
AddPreHook
Using AI Code Generation
1result := client.AddPreHook("test", "test", "test", "test", "test", "test", "test", "test")2if result.Error() != nil {3 fmt.Println(result.Error())4} else {5 fmt.Println("AddPreHook: ", result)6}7result := client.AddPostHook("test", "test", "test", "test", "test", "test", "test", "test")8if result.Error() != nil {9 fmt.Println(result.Error())10} else {11 fmt.Println("AddPostHook: ", result)12}13result := client.DeletePreHook("test", "test", "test", "test", "test", "test", "test", "test")14if result.Error() != nil {15 fmt.Println(result.Error())16} else {17 fmt.Println("DeletePreHook: ", result)18}19result := client.DeletePostHook("test", "test", "test", "test", "test", "test", "test", "test")20if result.Error() != nil {21 fmt.Println(result.Error())22} else {23 fmt.Println("DeletePostHook: ", result)24}
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!