Hi, thanks for the awesomeness that is echo!
So I'm making some basic middleware but don't know how to test it. Even after looking at the included middleware tests I'm left confused with how to check something as simple as the response headers.
Here's an example using a very barebones CORS middleware:
package middleware
import (
"github.com/labstack/echo"
)
// CORS middleware
func CORS() echo.MiddlewareFunc {
return func(h echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
c.Response().Header().Set("Access-Control-Allow-Origin", "*")
return h(c)
}
}
}
Here's my super hacky test that while it works, I believe there's a better way:
package middleware
import (
"net/http"
"testing"
"time"
"github.com/labstack/echo"
)
func test(c *echo.Context) error {
return c.String(http.StatusOK, "test123")
}
func TestCORS(t *testing.T) {
e := echo.New()
e.Debug()
e.Use(CORS())
e.Get("/", test)
go e.Run(":63246")
time.Sleep(1 * time.Second)
res, err := http.Get("http://127.0.0.1:63246")
if err != nil {
t.Fatal(err)
}
if res.StatusCode != 200 {
t.Fatal("Wrong status code")
}
if res.Header.Get("Access-Control-Allow-Origin") != "*" {
t.Fatal("Access-Control-Allow-Origin header != *")
}
}
You can use httptest.ResponseRecorder, https://github.com/labstack/echo/blob/master/middleware/logger_test.go#L53.
Thanks, I saw the same thing in the middleware tests, I guess this is causing me the confusion:
c := echo.NewContext(req, echo.NewResponse(rec, e), e)
I don't understand how to test the middleware without sending an actual request. My middleware doesn't really deal with context, it just adds a header.
@montanaflynn Since we have upgraded to v2, example below is based on that but you can easily modify it for v1.
cors.go
package main
import (
"github.com/labstack/echo"
)
// CORS middleware
func CORS() echo.MiddlewareFunc {
return func(h echo.Handler) echo.Handler {
return echo.HandlerFunc(func(c echo.Context) error {
c.Response().Header().Set("Access-Control-Allow-Origin", "*")
return h.Handle(c)
})
}
}
cors_test.go
package main
import (
"net/http"
"testing"
"github.com/labstack/echo"
"github.com/labstack/echo/test"
"github.com/stretchr/testify/assert"
)
func TestCORS(t *testing.T) {
e := echo.New()
req := test.NewRequest(echo.GET, "/", nil)
res := test.NewResponseRecorder()
c := echo.NewContext(req, res, e)
cors := CORS()
h := cors.Handle(echo.HandlerFunc(func(c echo.Context) error {
return c.NoContent(http.StatusOK)
}))
h.Handle(c)
assert.Equal(t, "*", res.Header().Get("Access-Control-Allow-Origin"))
}
Most helpful comment
@montanaflynn Since we have upgraded to v2, example below is based on that but you can easily modify it for v1.
cors.gocors_test.go