doucuo4413 2018-09-11 13:40
浏览 43
已采纳

web.Request结构的字段状态未在Golang中正确克隆

In trying to set up two different web.Request states for use in some test cases, one without any headers and one with, I run into issue:

Setup

I create fakeRequest,fakeRequestNoHeaders thus:

// create fake request
fakeRequest := new(web.Request)
fakeRequest.Request = httptest.NewRequest("GET",
    fakeServer.URL,
    nil)

fakeRequestNoHeaders := new(web.Request)
fakeRequestNoHeaders.Request = fakeRequest.Request

// give fakeRequest some headers
fakeRequest.Header.Add("Authorization", "Bearer ksjaf;oipyu7")
fakeRequest.Header.Add("Scope", "test")

Sanity Test

I expect, of course, that fakeRequest.Header != fakeRequestNoHeaders.Header. I write that test:

t.Run("HeadersSanityTest", func(t *testing.T) {


    assert.NotEqualf(t,
        fakeRequest.Header,
        fakeRequestNoHeaders.Header,
        "fakeRequest,fakeRequestNoHeaders share the same header state")

Result of test

It fails.

Why is this and how can I achieve what I'm trying?

UPDATE: I found the culprit:

the underlying http.Request, returned by httptest.NewRequest, is actually a pointer. Header simply belongs to that Request. The problem now reduces down to "How to deep-copy that Request."

  • 写回答

1条回答 默认 最新

  • dongwei5740 2018-09-11 16:23
    关注

    The issue was, indeed, not with the Header field, but instead the Request field, which was a pointer. (Oh no! I accidentally shallow-copied)

    The Solution

    I recalled, in one of my earlier tests, a method that I wrote specifically to get around this:

    func makeBasicRequest() *web.Request {
        baseReq := httptest.NewRequest(http.MethodPost,
            "[some url here]",
            nil)
        req := new(web.Request)
        req.Request = baseReq
        return req
    }
    

    I basically just brought it into this test, and used it, hitting it once per fake request that I needed.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)