MCPcopy
hub / github.com/go-chi/chi / TestServeHTTPExistingContext

Function TestServeHTTPExistingContext

mux_test.go:1336–1390  ·  mux_test.go::TestServeHTTPExistingContext

TODO: a Router wrapper test.. type ACLMux struct { *Mux XX string } func NewACLMux() *ACLMux { return &ACLMux{Mux: NewRouter(), XX: "hihi"} } TODO: this should be supported... func TestWoot(t *testing.T) { var r Router = NewRouter() var r2 Router = NewACLMux() //NewRouter() r2.Get("/hi", f

(t *testing.T)

Source from the content-addressed store, hash-verified

1334// }
1335
1336func TestServeHTTPExistingContext(t *testing.T) {
1337 r := NewRouter()
1338 r.Get("/hi", func(w http.ResponseWriter, r *http.Request) {
1339 s, _ := r.Context().Value(ctxKey{"testCtx"}).(string)
1340 w.Write([]byte(s))
1341 })
1342 r.NotFound(func(w http.ResponseWriter, r *http.Request) {
1343 s, _ := r.Context().Value(ctxKey{"testCtx"}).(string)
1344 w.WriteHeader(404)
1345 w.Write([]byte(s))
1346 })
1347
1348 testcases := []struct {
1349 Ctx context.Context
1350 Method string
1351 Path string
1352 ExpectedBody string
1353 ExpectedStatus int
1354 }{
1355 {
1356 Method: "GET",
1357 Path: "/hi",
1358 Ctx: context.WithValue(context.Background(), ctxKey{"testCtx"}, "hi ctx"),
1359 ExpectedStatus: 200,
1360 ExpectedBody: "hi ctx",
1361 },
1362 {
1363 Method: "GET",
1364 Path: "/hello",
1365 Ctx: context.WithValue(context.Background(), ctxKey{"testCtx"}, "nothing here ctx"),
1366 ExpectedStatus: 404,
1367 ExpectedBody: "nothing here ctx",
1368 },
1369 }
1370
1371 for _, tc := range testcases {
1372 resp := httptest.NewRecorder()
1373 req, err := http.NewRequest(tc.Method, tc.Path, nil)
1374 if err != nil {
1375 t.Fatalf("%v", err)
1376 }
1377 req = req.WithContext(tc.Ctx)
1378 r.ServeHTTP(resp, req)
1379 b, err := io.ReadAll(resp.Body)
1380 if err != nil {
1381 t.Fatalf("%v", err)
1382 }
1383 if resp.Code != tc.ExpectedStatus {
1384 t.Fatalf("%v != %v", tc.ExpectedStatus, resp.Code)
1385 }
1386 if string(b) != tc.ExpectedBody {
1387 t.Fatalf("%s != %s", tc.ExpectedBody, b)
1388 }
1389 }
1390}
1391
1392func TestNestedGroups(t *testing.T) {
1393 handlerPrintCounter := func(w http.ResponseWriter, r *http.Request) {

Callers

nothing calls this directly

Calls 7

GetMethod · 0.95
NotFoundMethod · 0.95
NewRouterFunction · 0.85
ValueMethod · 0.80
WriteMethod · 0.65
WriteHeaderMethod · 0.45
ServeHTTPMethod · 0.45

Tested by

no test coverage detected