我正在尝试测试基于 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") 在测试中的行为与在实时环境中的行为不同)。