为了账号安全,请及时绑定邮箱和手机立即绑定

为什么 gin SetCookie 添加新的 cookie 但不更改旧的?

为什么 gin SetCookie 添加新的 cookie 但不更改旧的?

Go
ibeautiful 2023-02-14 17:47:55
我正在尝试在有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 = reqtest.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等。结果,测试没有通过。我不明白我做错了什么,能以某种方式解决吗?还是应该这样?
查看完整描述

1 回答

?
海绵宝宝撒

TA贡献1809条经验 获得超8个赞

用于AddCookie为 设置 cookie recorder。


我认为你应该Logout像这样测试处理程序:


package ${your_package}


import (

    "encoding/json"

    "net/http"

    "net/http/httptest"

    "testing"


    "github.com/gin-gonic/gin"

    "github.com/stretchr/testify/assert"

)


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

}


func setupRouter() *gin.Engine {

    r := gin.Default()

    r.GET("/logout", Logout)

    return r

}


func TestLogout(t *testing.T) {

    w := httptest.NewRecorder()

    r := setupRouter()

    req, err := http.NewRequest("GET", "/logout", nil)

    assert.Nil(t, err)

    req.AddCookie(&http.Cookie{Name: "refresh_token", Value: "encodedRefreshToken", MaxAge: 60 * 60, Path: "/", Domain: "localhost", Secure: false, HttpOnly: true})

    req.AddCookie(&http.Cookie{Name: "access_token", Value: "encodedAccessToken", MaxAge: 60 * 60, Path: "/", Domain: "localhost", Secure: false, HttpOnly: true})

    r.ServeHTTP(w, req)


    for _, v := range w.Result().Cookies() {

        if v.Name == "access_token" {

            assert.Equal(t, "", v.Value)

        }

    }

    assert.Equal(t, http.StatusOK, w.Code)

    respBody := &gin.H{}

    err = json.Unmarshal(w.Body.Bytes(), respBody)

    assert.Nil(t, err)

    assert.Equal(t, gin.H{"status": "success"}, *respBody)

}

=== RUN   TestLogout

[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.


[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.

 - using env:   export GIN_MODE=release

 - using code:  gin.SetMode(gin.ReleaseMode)


[GIN-debug] GET    /logout                   --> app.Logout (3 handlers)

[GIN] 2022/09/19 - 10:46:00 | 200 |          81µs |                 | GET      "/logout"

--- PASS: TestLogout (0.00s)

PASS

参考: https: //gin-gonic.com/docs/testing/


查看完整回答
反对 回复 2023-02-14
  • 1 回答
  • 0 关注
  • 118 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号