Open platform to collect and prioritize feedback
refactor middleware tests
goenningdf8127c5baa9
diff --git a/app/handlers/identity_test.go b/app/handlers/identity_test.goindex e230072b6..7bdbfcc47 100644--- a/app/handlers/identity_test.go+++ b/app/handlers/identity_test.go@@ -26,10 +26,10 @@ func TestLoginHandler(t *testing.T) {RegisterTestingT(t)server := mock.NewServer()- code, response := server.ExecuteRaw(oauthHandlers.Login(oauth.FacebookProvider))+ code, response := server.Execute(oauthHandlers.Login(oauth.FacebookProvider))Expect(code).To(Equal(http.StatusTemporaryRedirect))- Expect(response.Header.Get("Location")).To(Equal("http://orange.test.canherayou.com/oauth/token?provider=facebook&redirect="))+ Expect(response.Header().Get("Location")).To(Equal("http://orange.test.canherayou.com/oauth/token?provider=facebook&redirect="))}func TestCallbackHandler_InvalidState(t *testing.T) {@@ -37,7 +37,7 @@ func TestCallbackHandler_InvalidState(t *testing.T) {server := mock.NewServer()server.Context.Request().URL, _ = url.Parse("http://login.test.canherayou.com/oauth/callback?state=abc")- code, _ := server.ExecuteRaw(oauthHandlers.Callback(oauth.FacebookProvider))+ code, _ := server.Execute(oauthHandlers.Callback(oauth.FacebookProvider))Expect(code).To(Equal(http.StatusInternalServerError))}@@ -47,10 +47,10 @@ func TestCallbackHandler_InvalidCode(t *testing.T) {server := mock.NewServer()server.Context.Request().URL, _ = url.Parse("http://login.test.canherayou.com/oauth/callback?state=http://orange.test.canhearyou.com")- code, response := server.ExecuteRaw(oauthHandlers.Callback(oauth.FacebookProvider))+ code, response := server.Execute(oauthHandlers.Callback(oauth.FacebookProvider))Expect(code).To(Equal(http.StatusTemporaryRedirect))- Expect(response.Header.Get("Location")).To(Equal("http://orange.test.canhearyou.com"))+ Expect(response.Header().Get("Location")).To(Equal("http://orange.test.canhearyou.com"))}func TestCallbackHandler_ExistingUserAndProvider(t *testing.T) {@@ -71,10 +71,10 @@ func TestCallbackHandler_ExistingUserAndProvider(t *testing.T) {server := mock.NewServer()server.Context.Request().URL, _ = url.Parse("http://demo.test.canherayou.com/oauth/callback?state=http://demo.test.canhearyou.com&code=123")- code, response := server.ExecuteRaw(oauthHandlers.Callback(oauth.FacebookProvider))+ code, response := server.Execute(oauthHandlers.Callback(oauth.FacebookProvider))Expect(code).To(Equal(http.StatusTemporaryRedirect))- Expect(response.Header.Get("Location")).To(Equal("http://demo.test.canhearyou.com?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyL2lkIjozMDAsInVzZXIvbmFtZSI6IkpvbiBTbm93IiwidXNlci9lbWFpbCI6Impvbi5zbm93QGdvdC5jb20ifQ.6_dLZrulH37ymBtqy-l7bhCti9hBv0lgEhH8tLm07CI"))+ Expect(response.Header().Get("Location")).To(Equal("http://demo.test.canhearyou.com?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyL2lkIjozMDAsInVzZXIvbmFtZSI6IkpvbiBTbm93IiwidXNlci9lbWFpbCI6Impvbi5zbm93QGdvdC5jb20ifQ.6_dLZrulH37ymBtqy-l7bhCti9hBv0lgEhH8tLm07CI"))}func TestCallbackHandler_NewUser(t *testing.T) {@@ -84,14 +84,14 @@ func TestCallbackHandler_NewUser(t *testing.T) {server := mock.NewServer()server.Context.Request().URL, _ = url.Parse("http://login.test.canherayou.com/oauth/callback?state=http://orange.test.canhearyou.com&code=456")- code, response := server.ExecuteRaw(oauthHandlers.Callback(oauth.FacebookProvider))+ code, response := server.Execute(oauthHandlers.Callback(oauth.FacebookProvider))user, err := users.GetByEmail(tenant.ID, "[email protected]")Expect(err).To(BeNil())Expect(user.Name).To(Equal("Some Facebook Guy"))Expect(code).To(Equal(http.StatusTemporaryRedirect))- Expect(response.Header.Get("Location")).To(Equal("http://orange.test.canhearyou.com?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyL2lkIjoxLCJ1c2VyL25hbWUiOiJTb21lIEZhY2Vib29rIEd1eSIsInVzZXIvZW1haWwiOiJzb21lLmd1eUBmYWNlYm9vay5jb20ifQ.PGavs5a6HRotRozfXfNP39JPb0vSus_8LL9MAOeLGDs"))+ Expect(response.Header().Get("Location")).To(Equal("http://orange.test.canhearyou.com?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyL2lkIjoxLCJ1c2VyL25hbWUiOiJTb21lIEZhY2Vib29rIEd1eSIsInVzZXIvZW1haWwiOiJzb21lLmd1eUBmYWNlYm9vay5jb20ifQ.PGavs5a6HRotRozfXfNP39JPb0vSus_8LL9MAOeLGDs"))}func TestCallbackHandler_ExistingUser_NewProvider(t *testing.T) {@@ -99,7 +99,7 @@ func TestCallbackHandler_ExistingUser_NewProvider(t *testing.T) {server := mock.NewServer()server.Context.Request().URL, _ = url.Parse("http://login.test.canherayou.com/oauth/callback?state=http://demo.test.canhearyou.com&code=123")- code, response := server.ExecuteRaw(oauthHandlers.Callback(oauth.GoogleProvider))+ code, response := server.Execute(oauthHandlers.Callback(oauth.GoogleProvider))tenant, _ := tenants.GetByDomain("demo")user, err := users.GetByEmail(tenant.ID, "[email protected]")@@ -107,5 +107,5 @@ func TestCallbackHandler_ExistingUser_NewProvider(t *testing.T) {Expect(len(user.Providers)).To(Equal(2))Expect(code).To(Equal(http.StatusTemporaryRedirect))- Expect(response.Header.Get("Location")).To(Equal("http://demo.test.canhearyou.com?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyL2lkIjozMDAsInVzZXIvbmFtZSI6IkpvbiBTbm93IiwidXNlci9lbWFpbCI6Impvbi5zbm93QGdvdC5jb20ifQ.6_dLZrulH37ymBtqy-l7bhCti9hBv0lgEhH8tLm07CI"))+ Expect(response.Header().Get("Location")).To(Equal("http://demo.test.canhearyou.com?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyL2lkIjozMDAsInVzZXIvbmFtZSI6IkpvbiBTbm93IiwidXNlci9lbWFpbCI6Impvbi5zbm93QGdvdC5jb20ifQ.6_dLZrulH37ymBtqy-l7bhCti9hBv0lgEhH8tLm07CI"))}diff --git a/app/handlers/status_test.go b/app/handlers/status_test.goindex 8a3d01ae3..abfb517b2 100644--- a/app/handlers/status_test.go+++ b/app/handlers/status_test.go@@ -17,7 +17,7 @@ func TestStatusHandler(t *testing.T) {}server := mock.NewServer()- status, query := server.Execute(handlers.Status(settings))+ status, query := server.ExecuteAsJSON(handlers.Status(settings))Expect(query.String("build")).To(Equal("today"))Expect(status).To(Equal(200))diff --git a/app/middlewares/auth_test.go b/app/middlewares/auth_test.goindex a5cbdbfb6..13bc5b07f 100644--- a/app/middlewares/auth_test.go+++ b/app/middlewares/auth_test.go@@ -2,14 +2,12 @@ package middlewares_testimport ("net/http"- "net/http/httptest""testing""github.com/WeCanHearYou/wechy/app/middlewares""github.com/WeCanHearYou/wechy/app/mock""github.com/WeCanHearYou/wechy/app/models""github.com/WeCanHearYou/wechy/app/pkg/web"- "github.com/labstack/echo". "github.com/onsi/gomega")@@ -17,73 +15,61 @@ func TestIsAuthorized_WithAllowedRole(t *testing.T) {RegisterTestingT(t)server := mock.NewServer()- req, _ := http.NewRequest(echo.GET, "/", nil)- rec := httptest.NewRecorder()- c := server.NewContext(req, rec)- c.SetUser(&models.User{+ server.Context.SetUser(&models.User{ID: 1,Role: models.RoleMember,})- mw := middlewares.IsAuthorized(models.RoleAdministrator, models.RoleMember)- mw(func(c web.Context) error {+ server.Use(middlewares.IsAuthorized(models.RoleAdministrator, models.RoleMember))+ status, _ := server.Execute(func(c web.Context) error {return c.NoContent(http.StatusOK)- })(c)+ })- Expect(rec.Code).To(Equal(http.StatusOK))+ Expect(status).To(Equal(http.StatusOK))}func TestIsAuthorized_WithForbiddenRole(t *testing.T) {RegisterTestingT(t)server := mock.NewServer()- req, _ := http.NewRequest(echo.GET, "/", nil)- rec := httptest.NewRecorder()- c := server.NewContext(req, rec)- c.SetUser(&models.User{+ server.Context.SetUser(&models.User{ID: 1,Role: models.RoleVisitor,})- mw := middlewares.IsAuthorized(models.RoleAdministrator, models.RoleMember)- mw(func(c web.Context) error {+ server.Use(middlewares.IsAuthorized(models.RoleAdministrator, models.RoleMember))+ status, _ := server.Execute(func(c web.Context) error {return c.NoContent(http.StatusOK)- })(c)+ })- Expect(rec.Code).To(Equal(http.StatusForbidden))+ Expect(status).To(Equal(http.StatusForbidden))}func TestIsAuthenticated_WithUser(t *testing.T) {RegisterTestingT(t)server := mock.NewServer()- req, _ := http.NewRequest(echo.GET, "/", nil)- rec := httptest.NewRecorder()- c := server.NewContext(req, rec)- c.SetUser(&models.User{+ server.Context.SetUser(&models.User{ID: 1,})- mw := middlewares.IsAuthenticated()- mw(func(c web.Context) error {+ server.Use(middlewares.IsAuthenticated())+ status, _ := server.Execute(func(c web.Context) error {return c.NoContent(http.StatusOK)- })(c)+ })- Expect(rec.Code).To(Equal(http.StatusOK))+ Expect(status).To(Equal(http.StatusOK))}func TestIsAuthenticated_WithoutUser(t *testing.T) {RegisterTestingT(t)server := mock.NewServer()- req, _ := http.NewRequest(echo.GET, "/", nil)- rec := httptest.NewRecorder()- c := server.NewContext(req, rec)+ server.Use(middlewares.IsAuthenticated())- mw := middlewares.IsAuthenticated()- mw(func(c web.Context) error {+ status, _ := server.Execute(func(c web.Context) error {return c.NoContent(http.StatusOK)- })(c)+ })- Expect(rec.Code).To(Equal(http.StatusForbidden))+ Expect(status).To(Equal(http.StatusForbidden))}diff --git a/app/middlewares/cache_test.go b/app/middlewares/cache_test.goindex dd3156a7e..90faddff9 100644--- a/app/middlewares/cache_test.go+++ b/app/middlewares/cache_test.go@@ -5,7 +5,7 @@ import ("testing""github.com/WeCanHearYou/wechy/app/middlewares"- "github.com/WeCanHearYou/wechy/app/mock2"+ "github.com/WeCanHearYou/wechy/app/mock""github.com/WeCanHearYou/wechy/app/pkg/web". "github.com/onsi/gomega")@@ -13,7 +13,7 @@ import (func TestCache(t *testing.T) {RegisterTestingT(t)- server := mock2.NewServer()+ server := mock.NewServer()server.Use(middlewares.OneYearCache())handler := func(c web.Context) error {return c.NoContent(http.StatusOK)diff --git a/app/middlewares/domain_test.go b/app/middlewares/domain_test.goindex bfeb02f68..57d6979bd 100644--- a/app/middlewares/domain_test.go+++ b/app/middlewares/domain_test.go@@ -5,7 +5,7 @@ import ("testing""github.com/WeCanHearYou/wechy/app/middlewares"- "github.com/WeCanHearYou/wechy/app/mock2"+ "github.com/WeCanHearYou/wechy/app/mock""github.com/WeCanHearYou/wechy/app/models""github.com/WeCanHearYou/wechy/app/pkg/web""github.com/WeCanHearYou/wechy/app/storage/inmemory"@@ -43,7 +43,7 @@ func TestMultiTenant(t *testing.T) {for _, testCase := range testCases {for _, host := range testCase.hosts {- server := mock2.NewServer()+ server := mock.NewServer()server.Context.Request().Host = hostserver.Use(middlewares.MultiTenant(tenants))@@ -61,7 +61,7 @@ func TestMultiTenant_AuthDomain(t *testing.T) {RegisterTestingT(t)tenants := &inmemory.TenantStorage{}- server := mock2.NewServer()+ server := mock.NewServer()server.Context.Request().Host = "login.test.canhearyou.com"server.Use(middlewares.MultiTenant(tenants))@@ -79,7 +79,7 @@ func TestMultiTenant_UnknownDomain(t *testing.T) {RegisterTestingT(t)tenants := &inmemory.TenantStorage{}- server := mock2.NewServer()+ server := mock.NewServer()server.Context.Request().Host = "somedomain.com"server.Use(middlewares.MultiTenant(tenants))@@ -94,7 +94,7 @@ func TestSingleTenant(t *testing.T) {RegisterTestingT(t)tenants := &inmemory.TenantStorage{}- server := mock2.NewServer()+ server := mock.NewServer()server.Context.Request().Host = "somedomain.com"server.Use(middlewares.SingleTenant(tenants))@@ -114,7 +114,7 @@ func TestSingleTenant(t *testing.T) {func TestHostChecker(t *testing.T) {RegisterTestingT(t)- server := mock2.NewServer()+ server := mock.NewServer()server.Context.Request().Host = "login.test.canhearyou.com"server.Use(middlewares.HostChecker("login.test.canhearyou.com"))@@ -128,7 +128,7 @@ func TestHostChecker(t *testing.T) {func TestHostChecker_DifferentHost(t *testing.T) {RegisterTestingT(t)- server := mock2.NewServer()+ server := mock.NewServer()server.Context.Request().Host = "orange.test.canhearyou.com"server.Use(middlewares.HostChecker("login.test.canhearyou.com"))status, _ := server.Execute(func(c web.Context) error {diff --git a/app/middlewares/jwt_test.go b/app/middlewares/jwt_test.goindex d35971af5..08a24d4e9 100644--- a/app/middlewares/jwt_test.go+++ b/app/middlewares/jwt_test.go@@ -2,16 +2,16 @@ package middlewares_testimport ("net/http"- "net/http/httptest""testing"+ "net/url"+"github.com/WeCanHearYou/wechy/app/middlewares""github.com/WeCanHearYou/wechy/app/mock""github.com/WeCanHearYou/wechy/app/models""github.com/WeCanHearYou/wechy/app/pkg/jwt""github.com/WeCanHearYou/wechy/app/pkg/web""github.com/WeCanHearYou/wechy/app/storage/inmemory"- "github.com/labstack/echo". "github.com/onsi/gomega")@@ -19,20 +19,16 @@ func TestJwtGetter_NoCookie(t *testing.T) {RegisterTestingT(t)server := mock.NewServer()- req, _ := http.NewRequest(echo.GET, "/", nil)- rec := httptest.NewRecorder()- c := server.NewContext(req, rec)-- mw := middlewares.JwtGetter(nil)- mw(func(c web.Context) error {+ server.Use(middlewares.JwtGetter(nil))+ status, _ := server.Execute(func(c web.Context) error {if c.IsAuthenticated() {return c.NoContent(http.StatusOK)} else {return c.NoContent(http.StatusNoContent)}- })(c)+ })- Expect(rec.Code).To(Equal(http.StatusNoContent))+ Expect(status).To(Equal(http.StatusNoContent))}func TestJwtGetter_WithCookie(t *testing.T) {@@ -52,22 +48,19 @@ func TestJwtGetter_WithCookie(t *testing.T) {users := &inmemory.UserStorage{}users.Register(user)server := mock.NewServer()- req, _ := http.NewRequest(echo.GET, "/", nil)- rec := httptest.NewRecorder()- c := server.NewContext(req, rec)- c.SetTenant(tenant)- c.Request().AddCookie(&http.Cookie{+ server.Context.SetTenant(tenant)+ server.Context.Request().AddCookie(&http.Cookie{Name: "auth",Value: token,})- mw := middlewares.JwtGetter(users)- mw(func(c web.Context) error {+ server.Use(middlewares.JwtGetter(users))+ status, response := server.Execute(func(c web.Context) error {return c.String(http.StatusOK, c.User().Name)- })(c)+ })- Expect(rec.Code).To(Equal(http.StatusOK))- Expect(rec.Body.String()).To(Equal("Jon Snow"))+ Expect(status).To(Equal(http.StatusOK))+ Expect(response.Body.String()).To(Equal("Jon Snow"))}func TestJwtGetter_WithCookie_DifferentTenant(t *testing.T) {@@ -80,41 +73,36 @@ func TestJwtGetter_WithCookie_DifferentTenant(t *testing.T) {users := &inmemory.UserStorage{}server := mock.NewServer()- req, _ := http.NewRequest(echo.GET, "/", nil)- rec := httptest.NewRecorder()- c := server.NewContext(req, rec)- c.SetTenant(&models.Tenant{ID: 400})- c.Request().AddCookie(&http.Cookie{+ server.Context.SetTenant(&models.Tenant{ID: 400})+ server.Context.Request().AddCookie(&http.Cookie{Name: "auth",Value: token,})- mw := middlewares.JwtGetter(users)- mw(func(c web.Context) error {+ server.Use(middlewares.JwtGetter(users))+ status, _ := server.Execute(func(c web.Context) error {if c.User() == nil {return c.NoContent(http.StatusNoContent)}return c.NoContent(http.StatusOK)- })(c)+ })- Expect(rec.Code).To(Equal(http.StatusNoContent))+ Expect(status).To(Equal(http.StatusNoContent))}func TestJwtSetter_WithoutJwt(t *testing.T) {RegisterTestingT(t)server := mock.NewServer()- req, _ := http.NewRequest(echo.GET, "/abc", nil)- rec := httptest.NewRecorder()- c := server.NewContext(req, rec)- c.Request().Host = "orange.test.canhearyou.com"+ server.Context.Request().Host = "orange.test.canhearyou.com"+ server.Context.Request().RequestURI = "/abc"- mw := middlewares.JwtSetter()- mw(func(c web.Context) error {+ server.Use(middlewares.JwtSetter())+ status, _ := server.Execute(func(c web.Context) error {return c.NoContent(http.StatusOK)- })(c)+ })- Expect(rec.Code).To(Equal(http.StatusOK))+ Expect(status).To(Equal(http.StatusOK))}func TestJwtSetter_WithJwt_WithoutParameter(t *testing.T) {@@ -125,18 +113,16 @@ func TestJwtSetter_WithJwt_WithoutParameter(t *testing.T) {})server := mock.NewServer()- req, _ := http.NewRequest(echo.GET, "/abc?jwt="+token, nil)- rec := httptest.NewRecorder()- c := server.NewContext(req, rec)- c.Request().Host = "orange.test.canhearyou.com"+ server.Context.Request().Host = "orange.test.canhearyou.com"+ server.Context.Request().URL, _ = url.Parse("/abc?jwt=" + token)- mw := middlewares.JwtSetter()- mw(func(c web.Context) error {+ server.Use(middlewares.JwtSetter())+ status, response := server.Execute(func(c web.Context) error {return c.NoContent(http.StatusOK)- })(c)+ })- Expect(rec.Code).To(Equal(http.StatusTemporaryRedirect))- Expect(rec.Header().Get("Location")).To(Equal("http://orange.test.canhearyou.com/abc"))+ Expect(status).To(Equal(http.StatusTemporaryRedirect))+ Expect(response.Header().Get("Location")).To(Equal("http://orange.test.canhearyou.com/abc"))}func TestJwtSetter_WithJwt_WithParameter(t *testing.T) {@@ -147,16 +133,14 @@ func TestJwtSetter_WithJwt_WithParameter(t *testing.T) {})server := mock.NewServer()- req, _ := http.NewRequest(echo.GET, "/abc?jwt="+token+"&foo=bar", nil)- rec := httptest.NewRecorder()- c := server.NewContext(req, rec)- c.Request().Host = "orange.test.canhearyou.com"+ server.Context.Request().Host = "orange.test.canhearyou.com"+ server.Context.Request().URL, _ = url.Parse("/abc?jwt=" + token + "&foo=bar")- mw := middlewares.JwtSetter()- mw(func(c web.Context) error {+ server.Use(middlewares.JwtSetter())+ status, response := server.Execute(func(c web.Context) error {return c.NoContent(http.StatusOK)- })(c)+ })- Expect(rec.Code).To(Equal(http.StatusTemporaryRedirect))- Expect(rec.Header().Get("Location")).To(Equal("http://orange.test.canhearyou.com/abc?foo=bar"))+ Expect(status).To(Equal(http.StatusTemporaryRedirect))+ Expect(response.Header().Get("Location")).To(Equal("http://orange.test.canhearyou.com/abc?foo=bar"))}diff --git a/app/mock/server.go b/app/mock/server.goindex b784058eb..0da137872 100644--- a/app/mock/server.go+++ b/app/mock/server.go@@ -4,9 +4,9 @@ import ("encoding/json""net/http""net/http/httptest"-"strings"+ "github.com/WeCanHearYou/wechy/app/middlewares""github.com/WeCanHearYou/wechy/app/models""github.com/WeCanHearYou/wechy/app/pkg/web""github.com/jmoiron/jsonq"@@ -15,10 +15,11 @@ import (// Server is a HTTP server wrapper for testing purposetype Server struct {- engine *web.Engine- handler echo.HandlerFunc- Context web.Context- recorder *httptest.ResponseRecorder+ engine *web.Engine+ handler echo.HandlerFunc+ Context web.Context+ recorder *httptest.ResponseRecorder+ middleware web.MiddlewareFunc}// NewServer creates a new test server@@ -31,39 +32,47 @@ func NewServer() *Server {context := engine.NewContext(request, recorder)return &Server{- engine: engine,- recorder: recorder,- Context: web.Context{Context: context},+ engine: engine,+ recorder: recorder,+ Context: web.Context{Context: context},+ middleware: middlewares.Noop(),}}-// NewContext creates a new HTTP context-func (s *Server) NewContext(req *http.Request, w http.ResponseWriter) web.Context {- return s.engine.NewContext(req, w)+// Use adds a new middleware to pipeline+func (s *Server) Use(middleware web.MiddlewareFunc) {+ s.middleware = middleware}-// Execute given handler and return response as JSON-func (s *Server) Execute(handler web.HandlerFunc) (int, *jsonq.JsonQuery) {- ctx := web.Context{Context: s.Context}- if err := handler(ctx); err != nil {- s.engine.HandleError(err, ctx)+// Execute given handler and return response+func (s *Server) Execute(handler web.HandlerFunc) (int, *httptest.ResponseRecorder) {+ if err := s.middleware(handler)(s.Context); err != nil {+ s.engine.HandleError(err, s.Context)}- return parseJSONBody(s)+ return s.recorder.Code, s.recorder}-// ExecutePost executes given handler with posted JSON-func (s *Server) ExecutePost(handler web.HandlerFunc, body string) (int, *jsonq.JsonQuery) {- ctx := web.Context{Context: s.Context}+// ExecuteAsJSON given handler and return json response+func (s *Server) ExecuteAsJSON(handler web.HandlerFunc) (int, *jsonq.JsonQuery) {+ if err := s.middleware(handler)(s.Context); err != nil {+ s.engine.HandleError(err, s.Context)+ }++ return parseJSONBody(s)+}+// ExecutePost executes given handler as POST and return response+func (s *Server) ExecutePost(handler web.HandlerFunc, body string) (int, *httptest.ResponseRecorder) {req, _ := http.NewRequest("POST", "/", strings.NewReader(body))req.Header.Add(echo.HeaderContentType, echo.MIMEApplicationJSON)- ctx.SetRequest(req)+ s.Context.SetRequest(req)- if err := handler(ctx); err != nil {- s.engine.HandleError(err, ctx)+ if err := s.middleware(handler)(s.Context); err != nil {+ s.engine.HandleError(err, s.Context)}- return parseJSONBody(s)++ return s.recorder.Code, s.recorder}func parseJSONBody(s *Server) (int, *jsonq.JsonQuery) {@@ -79,15 +88,6 @@ func parseJSONBody(s *Server) (int, *jsonq.JsonQuery) {return s.recorder.Code, nil}-// ExecuteRaw executes given handler and return raw response-func (s *Server) ExecuteRaw(handler web.HandlerFunc) (int, *http.Response) {- if err := handler(s.Context); err != nil {- s.engine.HandleError(err, s.Context)- }-- return s.recorder.Code, s.recorder.Result()-}-func hasJSON(r *httptest.ResponseRecorder) bool {isJSONContentType := strings.Contains(r.Result().Header.Get("Content-Type"), "application/json")diff --git a/app/mock2/server.go b/app/mock2/server.godeleted file mode 100644index 3a585fd2e..000000000--- a/app/mock2/server.go+++ /dev/null@@ -1,51 +0,0 @@-package mock2--import (- "net/http"- "net/http/httptest"-- "github.com/WeCanHearYou/wechy/app/middlewares"- "github.com/WeCanHearYou/wechy/app/models"- "github.com/WeCanHearYou/wechy/app/pkg/web"- "github.com/labstack/echo"-)--// Server is a HTTP server wrapper for testing purpose-type Server struct {- engine *web.Engine- handler echo.HandlerFunc- Context web.Context- recorder *httptest.ResponseRecorder- middleware web.MiddlewareFunc-}--// NewServer creates a new test server-func NewServer() *Server {- settings := &models.AppSettings{}- engine := web.New(settings)-- request, _ := http.NewRequest(echo.GET, "/", nil)- recorder := httptest.NewRecorder()- context := engine.NewContext(request, recorder)-- return &Server{- engine: engine,- recorder: recorder,- Context: web.Context{Context: context},- middleware: middlewares.Noop(),- }-}--// Use adds a new middleware to pipeline-func (s *Server) Use(middleware web.MiddlewareFunc) {- s.middleware = middleware-}--// Execute given handler and return response-func (s *Server) Execute(handler web.HandlerFunc) (int, *httptest.ResponseRecorder) {- if err := s.middleware(handler)(s.Context); err != nil {- s.engine.HandleError(err, s.Context)- }-- return s.recorder.Code, s.recorder-}diff --git a/app/pkg/web/context.go b/app/pkg/web/context.goindex 4f4fb2428..3e1f6a598 100644--- a/app/pkg/web/context.go+++ b/app/pkg/web/context.go@@ -100,9 +100,3 @@ func (ctx *Context) ParamAsInt(name string) (int, error) {}return int(val), nil}--//HandlerFunc represents an HTTP handler-type HandlerFunc func(Context) error--//MiddlewareFunc represents an HTTP middleware-type MiddlewareFunc func(HandlerFunc) HandlerFuncdiff --git a/app/pkg/web/engine.go b/app/pkg/web/engine.goindex 6c983f6d6..f8a0d0f70 100644--- a/app/pkg/web/engine.go+++ b/app/pkg/web/engine.go@@ -13,6 +13,12 @@ import ("github.com/labstack/gommon/log")+//HandlerFunc represents an HTTP handler+type HandlerFunc func(Context) error++//MiddlewareFunc represents an HTTP middleware+type MiddlewareFunc func(HandlerFunc) HandlerFunc+//Engine is our web engine wrappertype Engine struct {router *echo.Echo@@ -55,11 +61,6 @@ func (e *Engine) HandleError(err error, ctx Context) {e.router.HTTPErrorHandler(err, ctx)}-//Use add middleware to routes within the main Engine-func (e *Engine) Use(middleware MiddlewareFunc) {- e.router.Use(wrapMiddleware(middleware))-}-//Use add middleware to sub-routes within the Groupfunc (g *Group) Use(middleware MiddlewareFunc) {g.group.Use(wrapMiddleware(middleware))