~samwhited/mux

38d297f60d45169f4fe37ce07022aabb2482759b — Sam Whited 1 year, 1 month ago 38594d6
mux: add test for request canonicalization
1 files changed, 39 insertions(+), 0 deletions(-)

M handlers_test.go
M handlers_test.go => handlers_test.go +39 -0
@@ 30,6 30,12 @@ func successHandler(writeCode, writeBody bool) http.HandlerFunc {
	}
}

func panicHandler() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		panic("called panic handler with route: " + r.URL.String())
	}
}

var handlerTests = [...]struct {
	opts     func(t *testing.T) []mux.Option
	method   string


@@ 262,3 268,36 @@ func TestHandlers(t *testing.T) {
		})
	}
}

func TestCanonicalization(t *testing.T) {
	m := mux.New(
		mux.Handle(http.MethodConnect, "/profile/{username string}/", http.NotFoundHandler()),
		mux.Handle(http.MethodGet, "/users/{username string}/", panicHandler()),
	)

	// We expect GET methods to be canonicalized (eg. if there is no '/' at the
	// beginning, the path will be rooted in a redirect).
	t.Run(http.MethodGet, func(t *testing.T) {
		req := httptest.NewRequest(http.MethodGet, "/users/me/", nil)
		req.URL.Path = req.URL.Path[1:]
		h, req := m.Handler(req)
		w := httptest.NewRecorder()
		h.ServeHTTP(w, req)
		if w.Code != http.StatusPermanentRedirect {
			t.Errorf("Wrong code: want=%d, got=%d", http.StatusPermanentRedirect, w.Code)
		}
	})

	// We do not expect CONNECT methods to be canonicalized (eg. if there is no
	// '/' at the beginning, the request is used as is)
	t.Run(http.MethodConnect, func(t *testing.T) {
		req := httptest.NewRequest(http.MethodConnect, "/profile/me/", nil)
		req.URL.Path = req.URL.Path[1:]
		h, req := m.Handler(req)
		w := httptest.NewRecorder()
		h.ServeHTTP(w, req)
		if w.Code != http.StatusNotFound {
			t.Errorf("Wrong code: want=%d, got=%d", http.StatusNotFound, w.Code)
		}
	})
}