duandui5648 2018-07-24 04:03
浏览 141
已采纳

单元测试TLS客户端

I have a function that makes an https request to a TLS server. I want to write unit tests to test the client function. I came across httptest.NewTLSServer that can be used to mock the server. But, how can I incorporate the certificates that the client uses instead of the default ones used in NewTLSServer?

Following is the client function that makes the request:

func MakeDownloadRequest(url string) (*http.Response, error) {

    caCert, err := ioutil.ReadFile("client/tlscerts/cert.pem")
    if err != nil {
        return nil, err
    }
    caCertPool := x509.NewCertPool()
    caCertPool.AppendCertsFromPEM(caCert)

    cert, err := tls.LoadX509KeyPair("client/tlscerts/cert.pem","client/tlscerts/key.pem")
    if err != nil {
        return nil, err
    }

    client := &http.Client{
        Transport: &http.Transport{
            TLSClientConfig: &tls.Config{
                RootCAs:      caCertPool,
                Certificates: []tls.Certificate{cert},
            },
        },
    }

    resp, err := client.Get(url)
    if err != nil {
        return nil, err
    }
    return resp, nil
}

Server stub:

server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        io.WriteString(w, "Hello")
    }))

Using the server.URL to make requests gives me "bad certificate" error. How can I make both the client and server use the same certificate?

  • 写回答

1条回答 默认 最新

  • dsigh7478 2018-07-24 07:54
    关注

    Instead of using NewTLSServer() you want to:

    • Create your test server via httptest.NewUnstartedServer()
    • Create a *tls.Config much like you did in the code that sets up your http.Client in your MakeDownloadRequest()
    • Set the test server's TLS field to the *tls.Config created in the previous step
    • Start the test server using its StartTLS() method

    Then your program should be able to call into your test server using those certificates.

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

报告相同问题?

悬赏问题

  • ¥15 用verilog实现tanh函数和softplus函数
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题