Testing fasthttp with httptest

3.4k Views Asked by At

I am wondering how I can test an application that's written with fasthttp using the httptest package in the base library of Go.

I found this guide which explains the testing pretty well, but the issue is that httptest does not satisfy the http.Handler interface so I have no idea how to do the http.HandlerFunc since fasthttp uses it's own fasthttp.ListenAndServe that's incompatible.

Any ideas on how to create a wrapper, or how to otherwise test a fasthttp written library end to end?

2

There are 2 best solutions below

3
On BEST ANSWER

There are two possible approaches. Unit testing a handler isn't really viable as you would need to create a RequestCtx and stub/mock all necessary fields.

Instead, I would unit test the code that your fasthttp handlers call out to. I would do e2e testing of the actual handlers themselves.

There is an in memory listener implementation that you could use to avoid actually listening on a TCP port or Unix socket. You would initialise the server but serve on this listener instead of on a network connection.

You would then create a HTTP client and call the relevant methods as normal but use this listener as the transport.

If you stub/fake anything that your handlers interact with then you could make this in-memory only with no external dependencies, i.e. like a unit test but it will actually doing a full system test.

0
On
func TestFasthttpServer(t *testing.T) {
    fSv := fasthttp.Server{}
    fSv.Handler = func(ctx *fasthttp.RequestCtx) {
        if string(ctx.Path()) == "/test" && string(ctx.Method()) == "GET" {
            ctx.WriteString("OK")
        }
    }

    ln := fasthttputil.NewInmemoryListener()

    go fSv.Serve(ln)

    client := http.Client{Transport: &http.Transport{
        DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
            return ln.Dial()
        },
    }}

    resp, _ := client.Get("http://localhost/test")
    respBody, _ := io.ReadAll(resp.Body)
    assert.Equal(t, string(respBody), "OK")
}

Credits

Valuable examples also could be found here.