github.com/abemedia/go-don@v0.2.2-0.20240329015135-be88e32bb73b/internal/test/router.go (about) 1 package test 2 3 import ( 4 "net/http" 5 "strings" 6 "testing" 7 8 "github.com/abemedia/go-don" 9 "github.com/abemedia/go-don/pkg/httptest" 10 "github.com/abemedia/httprouter" 11 "github.com/valyala/fasthttp" 12 ) 13 14 func Router(t *testing.T, r don.Router, handler fasthttp.RequestHandler, basePath string) { 15 t.Helper() 16 17 tests := []struct { 18 desc string 19 method string 20 fn func(path string, handle httprouter.Handle) 21 }{ 22 {"Get", fasthttp.MethodGet, r.Get}, 23 {"Post", fasthttp.MethodPost, r.Post}, 24 {"Put", fasthttp.MethodPut, r.Put}, 25 {"Patch", fasthttp.MethodPatch, r.Patch}, 26 {"Delete", fasthttp.MethodDelete, r.Delete}, 27 {"Handle", fasthttp.MethodGet, func(path string, handle httprouter.Handle) { 28 r.Handle(fasthttp.MethodGet, path, handle) 29 }}, 30 {"Handler", fasthttp.MethodGet, func(path string, handle httprouter.Handle) { 31 r.Handler(fasthttp.MethodGet, path, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 32 _, _ = w.Write([]byte("Handler")) 33 })) 34 }}, 35 {"HandleFunc", fasthttp.MethodGet, func(path string, handle httprouter.Handle) { 36 r.HandleFunc(fasthttp.MethodGet, path, func(w http.ResponseWriter, r *http.Request) { 37 _, _ = w.Write([]byte("HandleFunc")) 38 }) 39 }}, 40 } 41 42 for _, test := range tests { 43 path := "/" + strings.ToLower(test.desc) 44 45 test.fn(path, func(ctx *fasthttp.RequestCtx, p httprouter.Params) { 46 _, _ = ctx.WriteString(test.desc) 47 }) 48 49 ctx := httptest.NewRequest(test.method, basePath+path, "", nil) 50 handler(ctx) 51 52 if code := ctx.Response.StatusCode(); code != fasthttp.StatusOK { 53 t.Errorf("%s request should return success status: %s", test.desc, fasthttp.StatusMessage(code)) 54 } 55 56 if string(ctx.Response.Body()) != test.desc { 57 t.Errorf("%s request should reach handler", test.desc) 58 } 59 } 60 }