返回顶部
首页 > 资讯 > 后端开发 > GO >httptest ResponseRecorder 保留旧值
  • 739
分享到

httptest ResponseRecorder 保留旧值

2024-04-04 23:04:22 739人浏览 薄情痞子
摘要

哈喽!今天心血来潮给大家带来了《Httptest ResponseRecorder 保留旧值》,想必大家应该对golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习G

哈喽!今天心血来潮给大家带来了《Httptest ResponseRecorder 保留旧值》,想必大家应该对golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习Golang,千万别错过这篇文章~希望能帮助到你!

问题内容

我有一个需要测试handlerauthentication 函数:

func handlerauthentication(c *gin.context) {
    session := session.getsession(c)
    var login login
    err := c.bindJSON(&login)
    if err != nil {
        c.abortwithstatusjson(http.statusbadrequest, gin.h{"error": err.error()})
        return
    }
    client, err := initclient(c, login)
    fmt.println("error: ",err)
    if err != nil {
        fmt.println("there's an error !")
        c.json(http.statusunauthorized, gin.h{"error": errorwronglogin})
        return
    }
    err = (*client).logout(c)
    if err != nil {
        return
    }

    session.set("username", login.username)
    session.set("passWord", login.password)
    err = session.save()
    if err != nil {
        c.json(http.statusinternalservererror, gin.h{"error": "an error occurred during the save of the session:" + err.error()})
        return
    }
    c.json(http.statusok, "connected")
}

为此,我做了这个:

func testhandlerauthentication(t *testing.t) {
    urlodoo = "https://isi.nc"
    resp := httptest.newrecorder()
    gin.setmode(gin.testmode)
    c, r := gin.createtestcontext(resp)

    r.post("/test", func(c *gin.context) {
        handlerauthentication(c)
    })

    ctrl := gomock.newcontroller(t)
    defer ctrl.finish()

    odoo = odoorpc{createmockodooclient}
    client = mock_odoorpc.newmockodooclient(ctrl)
    client.expect().authenticate(gomock.any(), gomock.any(), invalidusername, invalidpassword).anytimes().return(fmt.errorf("invalid login"))
    client.expect().authenticate(gomock.any(), gomock.any(), validusername, validpassword).anytimes().return(nil)
    client.expect().logout(gomock.any()).anytimes().return(nil)

    session = mock_session.newmocksession(ctrl)
    session = sessiongetter{createmocksession}
    session.expect().set("username", validusername).anytimes().return()
    session.expect().set("password", validpassword).anytimes().return()
    session.expect().save().anytimes().return(nil)

    for name, test := range map[string]struct {
        input   login
        want    int
    }{
        "valid login": {
            input: login{
                username: validusername,
                password: validpassword,
            },
            want: 200,
        },
        "invalid login": {
            input: login{
                username: invalidusername,
                password: invalidpassword,
            },
            want: 401,
        },
    } {
        t.run(name, func(t *testing.t) {
            body, _ := json.marshal(test.input)
            c.request, _ = http.newrequest(http.methodpost, "/test", strings.newreader(string(body)))
            r.servehttp(resp, c.request)
            assert.equal(t, test.want, resp.code)
            resp.flush()
        })
    }
}

我面临的问题是,如果我通过(valid logininvalid login)进行一项测试,它们都会通过,但是当我同时进行两个测试时,第二个测试会失败。 下面是同时执行两个测试的示例:

=== RUN   TestHandlerAuthentication
=== RUN   TestHandlerAuthentication/valid_login
Error:  <nil> //No error, so resp.Code should be equal to 200
=== RUN   TestHandlerAuthentication/invalid_login
Error:  invalid login //Error, so resp.Code should be equal to 401
There's an error !
    main_test.go:394: 
            Error Trace:    main_test.go:394
            Error:          Not equal: 
                            expected: 401
                            actual  : 200
            Test:           TestHandlerAuthentication/invalid_login
--- FAIL: TestHandlerAuthentication (0.00s)
    --- PASS: TestHandlerAuthentication/valid_login (0.00s)
    --- FAIL: TestHandlerAuthentication/invalid_login (0.00s)


Expected :401
Actual   :200

果然,登录无效时出现错误,但resp.code仍然是200。 如果我先进行 invalid login 测试,则 resp.code 仍将是 401。

发生这种情况是因为测试是并行的,而 httptest responserecorder 无法并行工作吗?

感谢您的帮助。


正确答案


谢谢leaf bebop

我需要为每个测试初始化​​一个新的 httptest.responserecorder 。 为此,我将初始化移至 t.run(name,func(t *testing.t) 函数:

func TestHandlerAuthentication(t *testing.T) {
    UrlOdoo = "https://isi.nc"

    ctrl := gomock.NewController(t)
    defer ctrl.Finish()

    Odoo = OdooRPC{createMockOdooClient}
    client = mock_odoorpc.NewMockOdooClient(ctrl)
    client.EXPECT().Authenticate(gomock.Any(), gomock.Any(), invalidUsername, invalidPassword).AnyTimes().Return(fmt.Errorf("invalid login"))
    client.EXPECT().Authenticate(gomock.Any(), gomock.Any(), validUsername, validPassword).AnyTimes().Return(nil)
    client.EXPECT().Logout(gomock.Any()).AnyTimes().Return(nil)

    session = mock_session.NewMockSession(ctrl)
    Session = SessionGetter{createMockSession}
    session.EXPECT().Set("username", validUsername).AnyTimes().Return()
    session.EXPECT().Set("password", validPassword).AnyTimes().Return()
    session.EXPECT().Save().AnyTimes().Return(nil)

    for name, test := range map[string]struct {
        input Login
        want  int
    }{
        "valid login": {
            input: Login{
                Username: validUsername,
                Password: validPassword,
            },
            want: 200,
        },
        "invalid login": {
            input: Login{
                Username: invalidUsername,
                Password: invalidPassword,
            },
            want: 401,
        },
    } {
        t.Run(name, func(t *testing.T) {
            resp := httptest.NewRecorder()
            gin.SetMode(gin.TestMode)
            c, r := gin.CreateTestContext(resp)

            r.POST("/test", func(c *gin.Context) {
                handlerAuthentication(c)
            })

            body, _ := json.Marshal(test.input)
            c.Request, _ = http.NewRequest(http.MethodPost, "/test", strings.NewReader(string(body)))
            r.ServeHTTP(resp, c.Request)
            assert.Equal(t, test.want, resp.Code)
        })
    }
}

今天关于《httptest ResponseRecorder 保留旧值》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注编程网公众号!

您可能感兴趣的文档:

--结束END--

本文标题: httptest ResponseRecorder 保留旧值

本文链接: https://lsjlt.com/news/596258.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作