rs / xmux

xmux is a httprouter fork on top of xhandler (net/context aware)
Other
98 stars 11 forks source link

Setting URL parameters from test code #7

Closed achiku closed 8 years ago

achiku commented 8 years ago

I was wondering what is the cleanest way to set url params when we test handlers, and thought it might be useful to make xmux.newParamContext public, or create another xmux.TestNewParamContext just for testing. I'll describe the concrete example below, and would appreciate if you can give me some feedback.

Suppose we have the following handler and server.

func helloWithParam(ctx context.Context, w http.ResponseWriter, r *http.Request) {
    n := xmux.Param(ctx, "name")
    fmt.Fprintf(w, "Hello, %s!", n)
    return
}

func main() {
    m := xmux.New()
    m.GET("/hello/:name", xhandler.HandlerFuncC(helloWithParam))
    if err := http.ListenAndServe(":8888", xhandler.New(context.Background(), m)); err != nil {
        log.Fatal(err)
    }
}

I want to test like the below so that I can test only a simple function, keeping routing/middleware aside.

func TestHelloWithParam(t *testing.T) {
    n := "dummyName"
    ps := xmux.ParamHolder{xmux.Parameter{Name: "name", Value: n}}
    ctx := xmux.NewParamContext(context.TODO(), ps) // This line could be xmux.TestNewParamContext()
    req, _ := http.NewRequest("GET", "/hello/"+n, nil)
    w := httptest.NewRecorder()
    helloWithParam(ctx, w, req)
    t.Log(w.Body)
}

The idea of test helper public API is borrowed from this slide.

rs commented 8 years ago

I like the idea. Could you please send a PR with this TestNewParamContext method?

achiku commented 8 years ago

Thanks!