-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Closed
Description
What version of Go are you running? go version go1.10.2 darwin/amd64
What version of gorilla/mux are you at? 5e55a4a
Describe your problem (and what you have tried so far)
I'm trying to test a route with a path variable but the handler sees an empty map when called from a unit test. It works fine with cURL against a running instance.
Paste a minimal, runnable, reproduction of your issue below (use backticks to format it)
I have slightly altered the example from the README.
package main
import (
"fmt"
"github.com/gorilla/mux"
"log"
"net/http"
)
func main() {
r := mux.NewRouter()
r.HandleFunc("/metrics/{type}", MetricsHandler)
log.Fatal(http.ListenAndServe("localhost:8080", r))
}
func MetricsHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
vars := mux.Vars(r)
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Type: %v", vars["type"])
}
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
)
func TestMetricsHandler(t *testing.T) {
tt := []struct {
routeVariable string
shouldPass bool
}{
{"goroutines", true},
{"heap", true},
{"counters", true},
{"queries", true},
{"adhadaeqm3k", false},
}
for _, tc := range tt {
path := fmt.Sprintf("/metrics/%s", tc.routeVariable)
req, err := http.NewRequest("GET", path, nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
handler := http.HandlerFunc(MetricsHandler)
handler.ServeHTTP(rr, req)
expected := fmt.Sprintf("Type: %v", tc.routeVariable)
if rr.Body.String() != expected {
t.Errorf("handler should have failed on routeVariable %s: got %v want %v",
tc.routeVariable, rr.Body.String(), expected)
}
}
}
sean~/go/src/gitlab.com/swalberg/muxtest$ go test *
--- FAIL: TestMetricsHandler (0.00s)
endpoints_test.go:36: handler should have failed on routeVariable goroutines: got Type: want Type: goroutines
endpoints_test.go:36: handler should have failed on routeVariable heap: got Type: want Type: heap
endpoints_test.go:36: handler should have failed on routeVariable counters: got Type: want Type: counters
endpoints_test.go:36: handler should have failed on routeVariable queries: got Type: want Type: queries
endpoints_test.go:36: handler should have failed on routeVariable adhadaeqm3k: got Type: want Type: adhadaeqm3k
FAIL
FAIL command-line-arguments 0.014s
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels