echo c.Get(“user”)在测试环境中无法工作。

huangapple go评论93阅读模式
英文:

echo c.Get("user") does not work in testing env

问题

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

有关如何在Echo框架中测试此功能的建议吗?这是一个我不希望发生的行为(在测试中,c.Get("user")的行为与实际环境中不同)。

英文:

I am attempting to test a golang API built on the echo framework/router. I have the following test.....

func TestLogout(t *testing.T) {
loadConfig()
db := stubDBs(t)
Convey(&quot;When you post to /logout&quot;, t, func() {
	Convey(&quot;with a valid token, you should get aa success msg and be logged out&quot;, func() {
		e := echo.New()
		e.Use(middleware.JWTWithConfig(middleware.JWTConfig{
			SigningKey:  []byte(&quot;secret&quot;),
			TokenLookup: &quot;query:user&quot;,
		}))
		req, err := http.NewRequest(echo.POST, &quot;auth/logout&quot;, strings.NewReader(&quot;&quot;))
		if err == nil {
			req.Header.Set(echo.HeaderAuthorization, fmt.Sprintf(&quot;Bearer %v&quot;, Token))
			rec := httptest.NewRecorder()
			c := e.NewContext(req, rec)
			Logout(db, Models.Redis)(c)
			body := GetJsonBody(rec.Body.String())
			error := body.Path(&quot;error&quot;).Data()
			msg := body.Path(&quot;error&quot;).Data().(string)
			pw := body.Path(&quot;data.user.password&quot;).Data().(string)
			token := body.Path(&quot;data.user.token&quot;).Data()
			So(error, ShouldEqual, nil)
			So(msg, ShouldEqual, &quot;Logged Out&quot;)
			So(rec.Code, ShouldEqual, 200)
			So(pw, ShouldEqual, &quot;&quot;)
			So(token, ShouldEqual, nil)
		}

	})
})
}

and in the 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(&quot;user&quot;)) //&lt;-----This Logs NIL only on testing
	    if c.Get(&quot;user&quot;) == nil {
	    	res := createAuthErrorResponse(user, &quot;Invalid Token&quot;)
		    return c.JSON(http.StatusOK, res)
	    }
	    token := c.Get(&quot;user&quot;).(*jwt.Token)
	    err := Models.Redis.Del(token.Raw).Err()
	    if err != nil {
		    handleErr(err)
		    res := createAuthErrorResponse(user, &quot;Token not in storage&quot;)
		    return c.JSON(http.StatusOK, res)
	    }
	    user.Password = &quot;&quot;
	    user.Token = null.StringFrom(&quot;&quot;)
	    res := createAuthSuccessResponse(user, &quot;Logged Out.&quot;)
	    return c.JSON(http.StatusOK, res)
    }
}

Any advice on how I can test this functionality in the cho framework? This is a behavior I would not expect (c.Get("user") does not act the same on testing as in live env).

答案1

得分: 2

通过很多痛苦,我能够找出解决方法。这是可工作的代码。接下来会有解释。

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)
    }
})

我已经正确设置了头部,但没有执行JWT echo中间件,这意味着我的令牌没有经过验证,并且无法使用c.Get()命令访问。

关键在于在不运行服务器的情况下测试echo中间件需要执行中间件函数,然后传入处理程序函数(这是您要测试的函数),然后传入上下文。因此,要测试中间件路由,函数应如下所示。如果是大写字母,您需要将其替换为您的特定情况。

A: middleware.MIDDLEWARE_FUNC(NECESSARY_CONFIGS) // <--- 这将返回echo.MiddlewareFunc

B: (YOUR_HANDLER(req, res)) // <--- echo.MiddlewareFunc接受一个echo.HanlderFunc作为其唯一参数,并传递您要测试的处理程序req,res

(c) // <--- 最后,使用您的测试上下文调用组合函数

A(B())(c)
英文:

Through much pain I was able to figure this out. Here is working code. Explanation to follow.

		Convey(&quot;with a valid token, you should get a success msg and be logged out&quot;, func() {
		e := echo.New()
		req, err := http.NewRequest(echo.POST, &quot;auth/logout&quot;, strings.NewReader(&quot;&quot;))
		if err == nil {
			req.Header.Set(echo.HeaderAuthorization, fmt.Sprintf(&quot;Bearer %v&quot;, Token))
			rec := httptest.NewRecorder()
			c := e.NewContext(req, rec)
			middleware.JWTWithConfig(middleware.JWTConfig{
				SigningKey: []byte(&quot;secret&quot;),
			})(Logout(db, Models.Redis))(c)
			body := GetJsonBody(rec.Body.String())
			error := body.Path(&quot;error&quot;).Data()
			msg := body.Path(&quot;msg&quot;).Data().(string)
			pw := body.Path(&quot;data.user.password&quot;).Data().(string)
			token := body.Path(&quot;data.user.token&quot;).Data()
			So(error, ShouldEqual, nil)
			So(msg, ShouldEqual, &quot;Logged Out&quot;)
			So(rec.Code, ShouldEqual, 200)
			So(pw, ShouldEqual, &quot;&quot;)
			So(token, ShouldEqual, nil)
		}

	})

I had set my Header properly but was not executing the JWT echo middleware which meant that my token was not validated and made accesisible using the c.Get() command.

The key here is that testing echo middlware without running the server requires you to execute the middleware function, which then takes a handler function (this is your function you want to test) and then takes the context. So, the function should look as follows to test your middleware routes. If it is all caps you need to replace it with your specific case.

A: middleware.MIDDLEWARE_FUNC(NECESSARY_CONFIGS) // &lt;--- this returns echo.MiddlewareFunc

B: (YOUR_HANDLER(req, res)) // &lt;---echo.MiddlewareFunc takes an echo.HanlderFunc as its only argument and you pass your handler you test req, res

(c) // &lt;--Finally, you call the resulting compose function with your test context

A(B())(c)

huangapple
  • 本文由 发表于 2017年4月8日 00:46:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/43283311.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定