登录
首页 >  Golang >  Go问答

在片状单元测试中解决HTTP服务器连接被拒错误

来源:stackoverflow

时间:2024-03-24 17:45:42 176浏览 收藏

在片状单元测试中,当 HTTP 服务器连接被拒绝时,会遇到错误。该错误发生在 `net.DialTimeout` 函数之后,表明连接被拒绝。这可能是由于 goroutine 中的代码在 `dial` 之前执行不一致导致的。使用 `require.Eventually` 函数并定期重试 `DialTimeout` 可以缓解测试的不稳定性。此外,`httptest` 包提供了替代方案,它使用内部 goroutine 来启动服务器,确保在进行 `dial` 之前服务器已准备好。

问题内容

我正在尝试调试一个类似于以下内容的片状单元测试:

package main

import (
    "net"
    "net/http"
    "testing"
    "time"

    "github.com/stretchr/testify/require"
)

func testflaky(t *testing.t) {
    // mock an api
    http.handlefunc("/foo/bar", func(w http.responsewriter, r *http.request) {
        _, err := w.write([]byte("foobar"))
        require.noerror(t, err)
    })
    go func() {
        require.noerror(t, http.listenandserve("localhost:7777", nil))
    }()

    // wait (up to 1 second) for the mocked api to be available
    conn, err := net.dialtimeout("tcp", "localhost:7777", time.second)
    require.noerror(t, err)
    require.noerror(t, conn.close())
}

但是,从 dialtimeout 错误之后的 require.noerror() 行,我收到以下错误(仅在 ci 环境中):

--- fail: testflaky (0.00s)
         main_test.go:24: 
                error trace:    main_test.go:24
                error:          received unexpected error:
                                dial tcp [::1]:7777: connect: connection refused
                test:           testflaky

由于测试立即失败,我猜测这不是调整超时的问题。我应该如何使这个测试不不稳定?我正在考虑用 require 替换最后三行。最终 类似于以下内容:

    var conn net.Conn
    require.Eventually(t, func() bool {
        var err error
        conn, err = net.DialTimeout("tcp", "localhost:7777", time.Second)
        if err != nil {
            t.Logf("DialTimeout error: %v. Retrying...", err)
            return false
        }
        return true
    }, time.Second, 100*time.Millisecond)
    require.NoError(t, conn.Close())

这足以消除测试不稳定吗?


正确答案


goroutine 内部的代码不保证在 dial 之前执行。 (如果你在 goroutine 之后放置一个睡眠,它应该可以工作,但这是一个丑陋的解决方案)。

另外,请注意,“超时拨号”在建立连接时正在等待 tcp 数据包,但被拒绝的连接实际上是 rst 数据包。

提示:看看 httptest 包是如何工作的。

编辑:httptest 的工作原理如下:https://cs.opensource.google/go/go/+/refs/tags/go1.16.6:src/net/http/httptest/server.go;l=304

func (s *Server) goServe() {
    s.wg.Add(1)
    go func() {
        defer s.wg.Done()
        s.Config.Serve(s.Listener)
    }()
}

好了,本文到此结束,带大家了解了《在片状单元测试中解决HTTP服务器连接被拒错误》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>