我目前正在开发一个设计为在 Docker 容器中运行的服务器。
这是我的测试设置方法:
func TestMain(m *testing.M) {
schedulerName := "scheduler1"
IP, err := container.StartNewScheduler(schedulerName)
if err != nil {
log.Println("Could not create container.")
log.Fatal(err)
}
serverIP = IP
code := m.Run()
cleanupContainer(schedulerName)
os.Exit(code)
}
该行container.StartNewScheduler(schedulername)启动了一个名为“scheduler1”的新 docker 容器,并告诉它在其中运行服务器。
接下来我使用在后台运行的容器运行我的测试,现在我只有一个测试。
func TestNewScheduler(t *testing.T) {
testCodeInput := "THIS IS A TEST"
requestBody, err := json.Marshal(map[string]string{
"Code": fmt.Sprintf("print(\"%s\")", testCodeInput),
})
if err != nil {
t.Fatal(err)
}
url := fmt.Sprintf("http://%s:%d/execute/python", serverIP, 3000)
contentType := "application/json"
body := bytes.NewBuffer(requestBody)
response := post(url, contentType, body, t)
actual := parseOutput(response.Body, t)
response.Body.Close()
expected := fmt.Sprintf("{\"Stdout\":\"%s\\n\"}", testCodeInput)
if actual != expected {
t.Fatalf("Expected %s, but got %s", expected, actual)
}
}
我遇到的问题是有时我的连接被拒绝,有时我没有。
server_container_test.go:51: Post http://172.20.0.2:3000/execute/python: dial tcp 172.20.0.2:3000: connect: connection refused
我注意到,每当我尝试调试问题时,一切似乎都运行良好。我的运行理论是因为当我单步执行代码时,容器有更多时间启动并让服务器在其中运行。
为了测试我的假设,我在我的 post 方法中添加了第二个 post 调用,并在调用它之前设置了一个计时器。
还有其他人对可能导致我这个问题的原因有任何猜测吗?
如果我的假设是正确的,这是解决此问题的最佳方法吗?在测试中添加 time.Sleep 是不是一个坏主意?
海绵宝宝撒
哔哔one
相关分类