How to test my handlers with middleware
Description
Sorry for all the questions, but I'm very new to Echo. Right now I'm writing a test that validates my handler.
The test is passing, but it does not invoke middleware. This is an issue in my scenario because my middleware authenticates that user and store the user in the context.
I'm using the way described in the docs. I've also tried using httptest.NewServer, but echo is not a valid http.Handler (ServeHTTP has wrong type of arguments).
Any ideas on how to do this?
If anyone wants to do this I figured it out:
//Get from server
func Get(app *api.App, url string) (int, string) {
return doRequest(app, "GET", url, auth)
}
func doRequest(app *api.App, method, url string) (int, string) {
app.Engine.SetHandler(app.Echo)
ts := httptest.NewServer(app.Engine.(*standard.Server))
defer ts.Close()
req, err := http.NewRequest("GET", fmt.Sprintf("%s%s", ts.URL, url), nil)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
client := &http.Client{}
res, err := client.Do(req)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
if res != nil {
defer res.Body.Close()
}
b, err := ioutil.ReadAll(res.Body)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
return res.StatusCode, string(b)
}
App is a struct I have that has both the Engine I'm running Echo on, as well as the Echo struct.
It's worth noting that this approach only works if you are using the standard engine. But IMHO it's good enough for tests.
Using it is as simple as:
status, body := Get(app, "/experiments", "[email protected]")
Expect(status).To(Equal(http.StatusOK))
Expect(body).NotTo(BeEmpty())
I simplified the assertions just to show how it's used. Ideally you would assert the contents of the body (JSON in my scenario).
As this can be easily accomplished I'm closing this issue. I do believe that having a stronger testing infrastructure would benefit echo, though.
@heynemann where do you add your middleware? Is it already added to the Echo struct before you use it in doRequest?
I'm facing a similar problem with my middleware that wraps request handling in a DB transaction.
I add my engine to echo.Echo. Not sure what you mean, but you can see it in use in my repo at https://github.com/topfreegames/khan
Hope it helps!
@heynemann sorry for necroposting, but I found more correct way, I guess:
func TestReset(t *testing.T) {
// Setup
e := echo.New()
req := httptest.NewRequest(echo.POST, v1+"/reset", nil)
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
req.Header.Set(echo.HeaderAuthorization, defaultUUID)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
// Middlewares chaining (it goes from inside to outside
c.SetHandler(
ContextExtender(testDB, testConfig)(
Authorization(
// Your method here
Reset,
),
),
)
// Here you call it and test, magic!
if assert.NoError(t, c.Handler()(c)) {
assert.Equal(t, http.StatusOK, rec.Code)
}
}
Hope my example will help others.
As I stumbled about this on how to test middleware, here's an example of using echo.ServerHTTP, which will end up triggering the router logic along with all middleware you have setup.
sample.go
package sample
import (
"net/http"
"github.com/labstack/echo"
)
func ServerHeader(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
c.Response().Header().Set(echo.HeaderServer, "Echo/3.0")
return next(c)
}
}
func initEcho() *echo.Echo {
e := echo.New()
e.Use(ServerHeader)
e.GET("/", rootUrl)
return e
}
func rootUrl(c echo.Context) error {
return c.HTML(http.StatusOK, "body output")
}
sample_test.go
package sample
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/labstack/echo"
"github.com/stretchr/testify/assert"
)
func TestMiddleware(t *testing.T) {
e := initEcho()
req := httptest.NewRequest(echo.GET, "/", nil)
rec := httptest.NewRecorder()
// Using the ServerHTTP on echo will trigger the router and middleware
e.ServeHTTP(rec, req)
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, rec.Body.String(), "body output")
assert.Equal(t, rec.Header().Get(echo.HeaderServer), "Echo/3.0")
}
@jwendel thx. beautiful code. expected and actual were swapped in assert.Equal.
sample_test.go
func TestMiddleware(t *testing.T) { ... assert.Equal(t, rec.Body.String(), "body output") assert.Equal(t, rec.Header().Get(echo.HeaderServer), "Echo/3.0")
func TestMiddleware(t *testing.T) {
...
assert.Equal(t, "body output", rec.Body.String())
assert.Equal(t, "Echo/3.0", rec.Header().Get(echo.HeaderServer))
How to test a handler protected with echojwt (github.com/labstack/echo-jwt/v4) middleware?
I'm testing like this
// authHandler_test.go
func initEcho() *echo.Echo {
e := echo.New()
e.Debug = config.EnvDebug()
//e.Renderer = hs.GetTemplateMap()
e.Validator = &bootstrap.CustomValidator{}
e.Use(
middleware.BodyLimit("30M"),
)
return e
}
func TestAuthUser(t *testing.T) { // --> test to fetch authenticated user, this is a protected route
e := initEcho()
doSignup := func() (token string, user model.User) {
input := struct {
Name string `json:"name"`
Email string `json:"email"`
Pass string `json:"password"`
}{
Name: "Test User for " + t.Name(),
Email: "[email protected]",
Pass: "1234...",
}
// prepare input as string
p, er := jsonutil.EncodeString(input)
if er != nil {
th.Fatalf(t, "Failed to encode json: %s", er)
}
// attach payload to request
req := httptest.NewRequest(http.MethodPost, "/v1/auth/sign-up", strings.NewReader(p))
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
// create response writer & context
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
_ = SignUp(c) // handler func
if rec.Code != http.StatusCreated {
th.Fatalf(t, "Failed to signup")
}
// decode login response
type loginResponse struct {
Data struct {
Token string `json:"token"`
User model.User `json:"user"`
} `json:"d"`
}
res := new(loginResponse)
if err := json.Unmarshal(rec.Body.Bytes(), res); err != nil {
th.Fatal(t, "Failed to decode login response:", err)
}
if res.Data.Token == "" {
th.Fatal(t, "Login response missing token")
}
return res.Data.Token, res.Data.User
}
// login
authToken, user := doSignup() // --> this is working fine
// at last delete the user
t.Cleanup(func() {
err := database.DB.Delete(&model.User{}, user.ID).Error
if err != nil {
th.Fatal(t, "Failed to delete created user:", err)
}
})
// get auth user
tests := []struct {
name string
token string
wantResCode int
}{
{
name: "success with valid token",
token: authToken,
wantResCode: http.StatusOK,
},
{
name: "fail with invalid token",
token: "authToken",
wantResCode: http.StatusUnauthorized,
},
}
// --> is these necessary here? these middlewares are applied in the router for "/v1/auth/me" router.
e.Use(
middleware2.JwtAuth(),
middleware2.Acl,
)
for _, tt := range tests {
// request with token
req := httptest.NewRequest(http.MethodGet, "/v1/auth/me", nil)
req.Header.Set(echo.HeaderAuthorization, "Bearer "+tt.token)
// create response writer & context
rec := httptest.NewRecorder()
//c := e.NewContext(req, rec)
t.Run(tt.name, func(t *testing.T) {
//_ = AuthUser(c) // --> Case1: this doesn't triggers the middleware
e.ServeHTTP(rec, req) // --> Case2: this triggers but only those I've registered here
// --> Case1: this always fails with (rec.Code is) 401 (with `AuthUser(c)` (as the controller is checking if the user having all the necessary permissions to do this action. When `echojwt` is unable to get the user, this error happens)
// --> Case2: this always fails with (rec.Code is) 404 (with `e.ServeHTTP` (so I guess something is wrong)
if rec.Code != tt.wantResCode {
th.Errorf(t, "Response Code %d want %d for user '%s'", rec.Code, tt.wantResCode, user.Email)
}
})
}
}
Almost all routes/handlers are protected with this 2 (middleware2.JwtAuth(), middleware2.Acl) middleware. For this reason, I can't test those handlers.
I've not found any solution to this in the docs & google. Please help.