Finish gorillize()

Co-authored-by: Roberto Abdelkader Martínez Pérez <robertomartinezp@gmail.com>
This commit is contained in:
pancho horrillo
2019-10-09 13:06:08 +02:00
parent 7d1f0bf97c
commit 401644b65e
2 changed files with 66 additions and 4 deletions
+2 -2
View File
@@ -7,11 +7,11 @@ import (
"github.com/gorilla/mux"
)
func gorillize(rs []model.Route, buildHandler func(*model.Route) http.Handler) *mux.Router {
func gorillize(rs []model.Route, buildHandler func(model.Route) http.Handler) *mux.Router {
m := mux.NewRouter()
for _, r := range rs {
m.Handle(r.Pattern, buildHandler(nil)).Methods(r.Method)
m.Handle(r.Pattern, buildHandler(r)).Methods(r.Method)
}
return m
+64 -2
View File
@@ -1,6 +1,8 @@
package mux
import (
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"reflect"
@@ -10,12 +12,18 @@ import (
"github.com/gorilla/mux"
)
func handlerStatusOK(h *model.Route) http.Handler {
func handlerStatusOK(route model.Route) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
}
func handleRouteIDToBody(route model.Route) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.WriteString(w, route.ID)
})
}
func TestGorillizeReturnsAnEmptyMuxWhenAnEmptyRouteList(t *testing.T) {
m := gorillize([]model.Route{}, handlerStatusOK)
@@ -103,4 +111,58 @@ func TestGorillizeReturnsAMuxThatMatchesByMethod(t *testing.T) {
}
}
// TODO: TestGorillizeReturnsAMuxThatRespectsRouteOrder
func TestGorillizeReturnsAMuxThatRespectsRouteOrderAB(t *testing.T) {
var rs []model.Route
rs = append(rs,
model.Route{
ID: "routeA",
Pattern: "/foo",
Method: "GET",
},
model.Route{
ID: "routeB",
Pattern: "/foo",
Method: "GET",
},
)
m := *gorillize(rs, handleRouteIDToBody)
req := httptest.NewRequest("GET", "/foo", nil)
w := httptest.NewRecorder()
m.ServeHTTP(w, req)
res := w.Result()
if body, _ := ioutil.ReadAll(res.Body); string(body) != "routeA" {
t.Errorf("Mux did not respect route order %q", body)
}
}
func TestGorillizeReturnsAMuxThatRespectsRouteOrderBA(t *testing.T) {
var rs []model.Route
rs = append(rs,
model.Route{
ID: "routeB",
Pattern: "/foo",
Method: "GET",
},
model.Route{
ID: "routeA",
Pattern: "/foo",
Method: "GET",
},
)
m := *gorillize(rs, handleRouteIDToBody)
req := httptest.NewRequest("GET", "/foo", nil)
w := httptest.NewRecorder()
m.ServeHTTP(w, req)
res := w.Result()
if body, _ := ioutil.ReadAll(res.Body); string(body) != "routeB" {
t.Errorf("Mux did not respect route order %q", body)
}
}