steinfletcher / apitest

A simple and extensible behavioural testing library for Go. You can use api test to simplify REST API, HTTP handler and e2e tests.
https://apitest.dev
MIT License
778 stars 55 forks source link

[Question] Support for Fiber v2 #124

Closed gaby closed 1 year ago

gaby commented 1 year ago

I just found your library while researching about Fiber. I noticed that even though it says it supports Fiber, the example server/test files are using Fiber v1. Do you know if this library supports Fiber v2 ?

Thanks!

steinfletcher commented 1 year ago

Hi @gaby. I haven't used fiber before. The fiber example was added by @enrico5b1b4. Do you have any insights here Enrico?

enrico5b1b4 commented 1 year ago

Hi @gaby yes, apitest should work with fiberv2 too.

You'll have to copy the FiberToHandlerFunc function to your test file, and wrap your fiber app with it to use it with apitest

func FiberToHandlerFunc(app *fiber.App) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        resp, err := app.Test(r)
        if err != nil {
            panic(err)
        }

        // copy headers
        for k, vv := range resp.Header {
            for _, v := range vv {
                w.Header().Add(k, v)
            }
        }
        w.WriteHeader(resp.StatusCode)

        // copy body
        if _, err := io.Copy(w, resp.Body); err != nil {
            panic(err)
        }
        defer resp.Body.Close()
    }
}
apitest.New().
        HandlerFunc(FiberToHandlerFunc(yourFiberApp)).
        Get("/user/1234").
        Expect(t).
        Cookies(apitest.NewCookie("CookieForAndy").Value("Andy")).
        Status(http.StatusOK).
        End()

I have pushed a fiberv2 example to this branch too https://github.com/enrico5b1b4/apitest/tree/fiberv2-example/examples/fiber

Please reach out if you have any issues!

gaby commented 1 year ago

@enrico5b1b4 Thank you, I will give it a try. May be worth merging that example into apitest since v1 is not used anymore.

steinfletcher commented 1 year ago

Thanks for your help @enrico5b1b4.

gaby commented 1 year ago

@steinfletcher Can you merge @enrico5b1b4 fiber v2 branch?