我正在尝试测试在echo框架/路由器上构建的golang API。我有以下测试.....
func TestLogout(t *testing.T) {
loadConfig()
db := stubDBs(t)
Convey("When you post to /logout", t, func() {
Convey("with a valid token, you should get aa success msg and be logged out", func() {
e := echo.New()
e.Use(middleware.JWTWithConfig(middleware.JWTConfig{
SigningKey: []byte("secret"),
TokenLookup: "query:user",
}))
req, err := http.NewRequest(echo.POST, "auth/logout", strings.NewReader(""))
if err == nil {
req.Header.Set(echo.HeaderAuthorization, fmt.Sprintf("Bearer %v", Token))
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
Logout(db, Models.Redis)(c)
body := GetJsonBody(rec.Body.String())
error := body.Path("error").Data()
msg := body.Path("error").Data().(string)
pw := body.Path("data.user.password").Data().(string)
token := body.Path("data.user.token").Data()
So(error, ShouldEqual, nil)
So(msg, ShouldEqual, "Logged Out")
So(rec.Code, ShouldEqual, 200)
So(pw, ShouldEqual, "")
So(token, ShouldEqual, nil)
}
})
})
}
并在控制器......
//Logout ...
func Logout(db *sqlx.DB, r *redis.Client) echo.HandlerFunc {
return func(c echo.Context) error {
var user Models.User
log.Println(c.Get("user")) //<-----This Logs NIL only on testing
if c.Get("user") == nil {
res := createAuthErrorResponse(user, "Invalid Token")
return c.JSON(http.StatusOK, res)
}
token := c.Get("user").(*jwt.Token)
err := Models.Redis.Del(token.Raw).Err()
if err != nil {
handleErr(err)
res := createAuthErrorResponse(user, "Token not in storage")
return c.JSON(http.StatusOK, res)
}
user.Password = ""
user.Token = null.StringFrom("")
res := createAuthSuccessResponse(user, "Logged Out.")
return c.JSON(http.StatusOK, res)
}
}
关于如何在cho框架中测试此功能的任何建议?这是我不希望的行为(c.Get(“user”)在测试中的行为与在实时环境中的行为不同)。
答案 0 :(得分:1)
通过很多痛苦,我能够弄清楚这一点。这是工作代码。说明如下。
Convey("with a valid token, you should get a success msg and be logged out", func() {
e := echo.New()
req, err := http.NewRequest(echo.POST, "auth/logout", strings.NewReader(""))
if err == nil {
req.Header.Set(echo.HeaderAuthorization, fmt.Sprintf("Bearer %v", Token))
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
middleware.JWTWithConfig(middleware.JWTConfig{
SigningKey: []byte("secret"),
})(Logout(db, Models.Redis))(c)
body := GetJsonBody(rec.Body.String())
error := body.Path("error").Data()
msg := body.Path("msg").Data().(string)
pw := body.Path("data.user.password").Data().(string)
token := body.Path("data.user.token").Data()
So(error, ShouldEqual, nil)
So(msg, ShouldEqual, "Logged Out")
So(rec.Code, ShouldEqual, 200)
So(pw, ShouldEqual, "")
So(token, ShouldEqual, nil)
}
})
我已正确设置了Header但未执行JWT echo中间件,这意味着我的令牌未经过验证,并且使用c.Get()命令可以进行扩展。
这里的关键是测试echo middlware而不运行服务器需要你执行中间件函数,然后它接受一个处理函数(这是你要测试的函数),然后获取上下文。因此,该函数应如下所示来测试您的中间件路由。如果是全部大写,则需要将其替换为特定情况。
A: middleware.MIDDLEWARE_FUNC(NECESSARY_CONFIGS) // <--- this returns echo.MiddlewareFunc
B: (YOUR_HANDLER(req, res)) // <---echo.MiddlewareFunc takes an echo.HanlderFunc as its only argument and you pass your handler you test req, res
(c) // <--Finally, you call the resulting compose function with your test context
A(B())(c)