1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| func TestFuncTest(t *testing.T) { fn1 := func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) { fmt.Println("fn1 before") _, _ = rw.Write([]byte("fn1b ")) next(rw, r) _, _ = rw.Write([]byte("fn1a ")) fmt.Println("fn1 after")
} fn2 := func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) { fmt.Println("fn2 before") _, _ = rw.Write([]byte("fn2b ")) next(rw, r) _, _ = rw.Write([]byte("fn2a ")) fmt.Println("fn2 after") } fn3 := func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) { fmt.Println("fn3 before") _, _ = rw.Write([]byte("fn3b ")) next(rw, r) _, _ = rw.Write([]byte("fn3a ")) fmt.Println("fn3 after") }
fnBuzz := func(rw http.ResponseWriter, r *http.Request) { _, _ = rw.Write([]byte("buzz ")) fmt.Println("buzz logic") }
tableTests := []struct { name string expectedStr string handlers []Handler }{ { name: "normal test", expectedStr: "fn1b fn2b fn3b fn3a fn2a fn1a ", handlers: []Handler{HandlerFunc(fn1), HandlerFunc(fn2), HandlerFunc(fn3)}, }, { name: "empty test", expectedStr: "", handlers: nil, }, { name: "with buzz", expectedStr: "fn1b fn2b buzz fn2a fn1a ", handlers: []Handler{HandlerFunc(fn1), HandlerFunc(fn2), Wrap(fnBuzz)}, }, }
for _, tt := range tableTests { hmw := New(tt.handlers...) ts := httptest.NewServer(hmw) defer ts.Close() res, err := http.Get(ts.URL) if err != nil { t.Fatal(err) } resArr, _ := ioutil.ReadAll(res.Body) str := string(resArr) defer res.Body.Close() if str != tt.expectedStr { t.Errorf("name: %s , expected %s, but got %s", tt.name, tt.expectedStr, str) } } }
|