testing - echo c.Get ("user") 在测试环境中不起作用

标签 testing go goconvey go-echo

我正在尝试测试基于 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)
        }

    })
})
}

在 Controller 中....

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

最佳答案

我经历了很多痛苦才弄明白了这一点。这是工作代码。解释如下。

        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 中间件,这意味着我的 token 没有经过验证并且无法使用 c.Get() 命令访问。

这里的关键是,在不运行服务器的情况下测试 echo 中间件需要您执行中间件函数,然后它会获取一个处理函数(这是您要测试的函数),然后获取上下文。因此,该函数应如下所示来测试您的中间件路由。如果全部是大写字母,您需要将其替换为您的特定大小写。

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)

关于testing - echo c.Get ("user") 在测试环境中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43283311/

相关文章:

java - 添加 @after 钩子(Hook)会影响包中的所有测试

java - 如何获取 div 中子项的计数甚至文本列表

testing - 持续改进 : Is it possible to specify the tests in advance?

go - 如何从 golang 中的处理程序服务器文件

GoConvey 自定义断言未按预期工作

unit-testing - Rx-Kotlin awaitTerminalEvent 永远不会 onComplete

google-app-engine - 在 app.yaml 上指定的环境变量,但未在 main.go 上获取

Go: slice 变量/参数的命名约定?

go - 在端点 REST API 的 GoConvey 测试期间跳过某些包含静态内容的文件夹