我正在尝试在有ctx.SetCookie方法的地方测试注销处理程序:
func (a *authController) Logout(ctx *gin.Context) {
refreshToken, err := ctx.Cookie("refresh_token")
...
ctx.SetCookie("access_token", "", -1, "/", "localhost", false, true)
ctx.SetCookie("refresh_token", "", -1, "/", "localhost", false, true)
ctx.SetCookie("logged_in", "", -1, "/", "localhost", false, true)
ctx.JSON(http.StatusOK, gin.H{"status": "success"})
}
测试函数中的代码:
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.SetCookie("logged_in", "truee", 60*60, "/", "localhost", false, false)
req, _ := http.NewRequest("GET", "/logout", nil)
http.SetCookie(recorder, &http.Cookie{Name: "refresh_token", Value: "encodedRefreshToken", MaxAge: 60 * 60, Path: "/", Domain: "localhost", Secure: false, HttpOnly: true}})
http.SetCookie(recorder, &http.Cookie{Name: "access_token", Value: "encodedAccessToken", MaxAge: 60 * 60, Path: "/", Domain: "localhost", Secure: false, HttpOnly: true})
req.Header = http.Header{"Cookie": recorder.Result().Header["Set-Cookie"]}
ctx.Request = req
test.mock()
authController.Logout(ctx)
通话结束后,我正在尝试检查 cookie 是否已被删除:
coockies := recorder.Result().Cookies()
for _, c := range coockies {
if c.Name == "access_token" {
assert.Equal(t, "", c.Value)
}
...
}
而且我遇到这样一个问题,setCookie 不更改 cookie,而是添加新的。也就是调用这个方法后,我有两对cookies和access Token等。
结果,测试没有通过。我不明白我做错了什么,能以某种方式解决吗?还是应该这样?
海绵宝宝撒
相关分类