drus39136 2016-06-08 15:05
浏览 37
已采纳

尝试测试Golang HTTP Server时Travis CI失败

I'm very new to travis and Go. I have a test for a https server and it runs fine with I run go test -v ./... on my local machine but it will fail most of the time on Travis due to a getsocketopt: connection refused error when trying to connect to the server. It should be listening on https://localhost:8081. Is there something in my .travis.yml I can do to prevent this from happening?

Here is my .travis.yml

language: go
go:
 - 1.6
 - tip
matrix:
  allow_failures:
 - go: tip
before_install:
 - go get -v github.com/golang/lint/golint
install:
 - go get -v -d -t ./...

Here's my server creation code:

func (webserver *WebServer) Start(keyLocation string, certLocation string) <-chan error {
    errors := make(chan error, 1)
    go func() {
        defer close(errors)
        errors <- http.ListenAndServeTLS(fmt.Sprintf(":%v", webserver.config.WebServerPort), certLocation, keyLocation, nil)
    }()
    return errors
}

And the client code:

func createHTTPClient(t *testing.T) *http.Client {
    t.Log("Creating a test client...")
    tr := &http.Transport {
        TLSClientConfig: &tls.Config {InsecureSkipVerify: true},
    }

    t.Log("Created a test client")
    return &http.Client {Transport: tr}
}

Sample request with client

request, _ := http.NewRequest(httpmethod, fmt.Sprintf("https://localhost:%d/token", port), nil)
client.Do(request)

Sample starting the server in a test

errors := server.Start(testKeyLocation, testCertLocation)
//Handle errors from server
go func() {
    select {
        case err := <-errors:
            if err != nil {
                t.Fatalf("Error with server: %s", err.Error())
            }
    }
}()
  • 写回答

1条回答 默认 最新

  • douping7105 2016-06-08 16:50
    关注

    You have no synchronization between starting the server and trying to connect. Adding a time.Sleep after starting the server should highlight the issue.

    One way to reduce the window where the server isn't ready is to create the net.Listener synchronously, and then add the open listener to the http.Server config before starting the server. The httptest.Server can do this for you, as well as bind to random ports to prevent conflicts during tests, and using local test TLS certificates.

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

报告相同问题?

悬赏问题

  • ¥15 vue3加ant-design-vue无法渲染出页面
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序