diff --git a/internal/middleware/middleware_internal_test.go b/internal/middleware/middleware_internal_test.go index 404d4eb..0e17a05 100644 --- a/internal/middleware/middleware_internal_test.go +++ b/internal/middleware/middleware_internal_test.go @@ -227,10 +227,12 @@ func TestMetricsRecordsServedRequest(t *testing.T) { // each request with the pattern of the route that answers it, never with its // path: two paths one route answers share that route's pattern, and requests // no route answers, a 404 or a 405, share "unmatched", among them requests for -// the path the subrouter is mounted at, /v1 and /v1/. With a label per path, -// any client could add series to the registry without limit. The middleware -// registers with a registry of its own here, as another test in this package -// registers with Prometheus' default registry, which can be done only once. +// the path the subrouter is mounted at, /v1 and /v1/. A request with an empty +// path is answered by the / route, as chi routes it as /, and is labelled /. +// With a label per path, any client could add series to the registry without +// limit. The middleware registers with a registry of its own here, as another +// test in this package registers with Prometheus' default registry, which can +// be done only once. func TestMetricsLabelsRequestsByRoute(t *testing.T) { t.Parallel() @@ -244,6 +246,9 @@ func TestMetricsLabelsRequestsByRoute(t *testing.T) { // The image route is in a subrouter, as in pixa's router. router := chi.NewRouter() router.Use(mw.Metrics()) + router.Get("/", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + }) router.Route("/v1", func(r chi.Router) { r.Get("/image/*", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) @@ -258,15 +263,21 @@ func TestMetricsLabelsRequestsByRoute(t *testing.T) { {http.MethodGet, "/v1"}, {http.MethodGet, "/v1/"}, {http.MethodPost, "/v1/image/a.example.com/one.jpg/1x1.png"}, + // The request line GET http://pixa.example HTTP/1.1 leaves both + // r.URL.Path and r.URL.RawPath empty. + {http.MethodGet, "http://pixa.example"}, } { - router.ServeHTTP(httptest.NewRecorder(), httptest.NewRequestWithContext( - t.Context(), req.method, req.path, nil)) + r := httptest.NewRequestWithContext( + t.Context(), req.method, req.path, nil) + t.Logf("%s %s: r.URL.Path %q, r.URL.RawPath %q", + req.method, req.path, r.URL.Path, r.URL.RawPath) + router.ServeHTTP(httptest.NewRecorder(), r) } got := requestCountsByHandler(t, registry) t.Logf("requests counted by handler label: %v", got) - want := map[string]uint64{"/v1/image/*": 2, "unmatched": 5} + want := map[string]uint64{"/": 1, "/v1/image/*": 2, "unmatched": 5} if !maps.Equal(got, want) { t.Errorf("requests counted by handler label = %v, want %v", got, want) }