github.com/roblesoft/oak@v0.0.0-20230306162712-e6c5c487469e/router_test.go (about) 1 package oak 2 3 import ( 4 "fmt" 5 "log" 6 "net/http" 7 "net/http/httptest" 8 "os" 9 "reflect" 10 "testing" 11 ) 12 13 func TestNew(t *testing.T) { 14 oak := &Router{trees: nil} 15 want := &Router{} 16 17 if reflect.TypeOf(oak) != reflect.TypeOf(want) { 18 t.Errorf("Is no returns an oak") 19 } 20 } 21 22 func TestGet(t *testing.T) { 23 oak := &Router{ 24 trees: nil, 25 logger: log.New(os.Stdout, "Api: ", log.LstdFlags), 26 } 27 28 oak.GET("/test", func(w http.ResponseWriter, r *http.Request) { 29 return 30 }) 31 32 t.Run("Get add route", func(t *testing.T) { 33 if len(oak.trees) == 0 { 34 t.Errorf("Is no adding routes") 35 } 36 37 }) 38 } 39 40 func TestServeHTTP(t *testing.T) { 41 oak := &Router{ 42 trees: nil, 43 logger: log.New(os.Stdout, "Api: ", log.LstdFlags), 44 } 45 46 type testMethodsCases struct { 47 description string 48 req *http.Request 49 res *httptest.ResponseRecorder 50 want int 51 } 52 53 for _, scenario := range []testMethodsCases{ 54 { 55 description: "Return status code 200", 56 req: httptest.NewRequest(http.MethodGet, "/test", nil), 57 res: httptest.NewRecorder(), 58 want: 200, 59 }, 60 { 61 description: "Return status code 404", 62 req: httptest.NewRequest(http.MethodPost, "/test", nil), 63 res: httptest.NewRecorder(), 64 want: 404, 65 }, 66 } { 67 t.Run(scenario.description, func(t *testing.T) { 68 oak.GET("/test", func(w http.ResponseWriter, r *http.Request) { 69 fmt.Fprintf(w, "Hello, World") 70 }) 71 72 if oak.ServeHTTP(scenario.res, scenario.req); scenario.res.Result().StatusCode != scenario.want { 73 t.Errorf("not got status %d", scenario.want) 74 } 75 }) 76 } 77 } 78 79 func BenchmarkGet(b *testing.B) { 80 oak := &Router{ 81 trees: nil, 82 logger: log.New(os.Stdout, "Api: ", log.LstdFlags), 83 } 84 85 oak.GET("/test", func(w http.ResponseWriter, r *http.Request) { 86 return 87 }) 88 89 oak.GET("/test2", func(w http.ResponseWriter, r *http.Request) { 90 return 91 }) 92 93 oak.GET("/test3", func(w http.ResponseWriter, r *http.Request) { 94 return 95 }) 96 } 97 98 func BenchmarkServeHTTP(b *testing.B) { 99 oak := &Router{ 100 trees: nil, 101 logger: log.New(os.Stdout, "Api: ", log.LstdFlags), 102 } 103 104 oak.GET("/test", func(w http.ResponseWriter, r *http.Request) { 105 fmt.Fprintf(w, "Hello, World") 106 }) 107 108 req := httptest.NewRequest(http.MethodGet, "/test", nil) 109 res := httptest.NewRecorder() 110 111 oak.ServeHTTP(res, req) 112 }