MCPcopy
hub / github.com/julienschmidt/httprouter / TestRouterNotFound

Function TestRouterNotFound

router_test.go:385–448  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

383}
384
385func TestRouterNotFound(t *testing.T) {
386 handlerFunc := func(_ http.ResponseWriter, _ *http.Request, _ Params) {}
387
388 router := New()
389 router.GET("/path", handlerFunc)
390 router.GET("/dir/", handlerFunc)
391 router.GET("/", handlerFunc)
392
393 testRoutes := []struct {
394 route string
395 code int
396 location string
397 }{
398 {"/path/", 301, "/path"}, // TSR -/
399 {"/dir", 301, "/dir/"}, // TSR +/
400 {"", 301, "/"}, // TSR +/
401 {"/PATH", 301, "/path"}, // Fixed Case
402 {"/DIR/", 301, "/dir/"}, // Fixed Case
403 {"/PATH/", 301, "/path"}, // Fixed Case -/
404 {"/DIR", 301, "/dir/"}, // Fixed Case +/
405 {"/../path", 301, "/path"}, // CleanPath
406 {"/nope", 404, ""}, // NotFound
407 }
408 for _, tr := range testRoutes {
409 r, _ := http.NewRequest(http.MethodGet, tr.route, nil)
410 w := httptest.NewRecorder()
411 router.ServeHTTP(w, r)
412 if !(w.Code == tr.code && (w.Code == 404 || fmt.Sprint(w.Header().Get("Location")) == tr.location)) {
413 t.Errorf("NotFound handling route %s failed: Code=%d, Header=%v", tr.route, w.Code, w.Header().Get("Location"))
414 }
415 }
416
417 // Test custom not found handler
418 var notFound bool
419 router.NotFound = http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
420 rw.WriteHeader(404)
421 notFound = true
422 })
423 r, _ := http.NewRequest(http.MethodGet, "/nope", nil)
424 w := httptest.NewRecorder()
425 router.ServeHTTP(w, r)
426 if !(w.Code == 404 && notFound == true) {
427 t.Errorf("Custom NotFound handler failed: Code=%d, Header=%v", w.Code, w.Header())
428 }
429
430 // Test other method than GET (want 307 instead of 301)
431 router.PATCH("/path", handlerFunc)
432 r, _ = http.NewRequest(http.MethodPatch, "/path/", nil)
433 w = httptest.NewRecorder()
434 router.ServeHTTP(w, r)
435 if !(w.Code == 307 && fmt.Sprint(w.Header()) == "map[Location:[/path]]") {
436 t.Errorf("Custom NotFound handler failed: Code=%d, Header=%v", w.Code, w.Header())
437 }
438
439 // Test special case where no node for the prefix "/" exists
440 router = New()
441 router.GET("/a", handlerFunc)
442 r, _ = http.NewRequest(http.MethodGet, "/", nil)

Callers

nothing calls this directly

Calls 7

NewFunction · 0.85
GETMethod · 0.80
HeaderMethod · 0.80
HandlerFuncMethod · 0.80
WriteHeaderMethod · 0.80
PATCHMethod · 0.80
ServeHTTPMethod · 0.45

Tested by

no test coverage detected