69 lines
1.9 KiB
Go
69 lines
1.9 KiB
Go
package docker
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
dockerclient "github.com/docker/docker/client"
|
|
)
|
|
|
|
func TestWaitForHealthyReturnsErrorOnTimeout(t *testing.T) {
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if !strings.HasSuffix(r.URL.Path, "/containers/test-container/json") {
|
|
t.Fatalf("unexpected Docker API path: %s", r.URL.Path)
|
|
}
|
|
_ = json.NewEncoder(w).Encode(map[string]any{
|
|
"State": map[string]any{
|
|
"Running": true,
|
|
"Health": map[string]any{
|
|
"Status": "starting",
|
|
},
|
|
},
|
|
})
|
|
}))
|
|
defer server.Close()
|
|
|
|
cli, err := dockerclient.NewClientWithOpts(dockerclient.WithHost(server.URL), dockerclient.WithVersion("1.43"))
|
|
if err != nil {
|
|
t.Fatalf("NewClientWithOpts() error: %v", err)
|
|
}
|
|
client := &Client{cli: cli}
|
|
|
|
err = client.WaitForHealthy(context.Background(), "test-container", time.Millisecond)
|
|
if err == nil {
|
|
t.Fatal("WaitForHealthy() error = nil, want timeout error")
|
|
}
|
|
if !strings.Contains(err.Error(), "超时") {
|
|
t.Fatalf("WaitForHealthy() error = %v, want timeout error", err)
|
|
}
|
|
}
|
|
|
|
func TestWaitForHealthyAcceptsRunningContainerWithoutHealthcheck(t *testing.T) {
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if !strings.HasSuffix(r.URL.Path, "/containers/test-container/json") {
|
|
t.Fatalf("unexpected Docker API path: %s", r.URL.Path)
|
|
}
|
|
_ = json.NewEncoder(w).Encode(map[string]any{
|
|
"State": map[string]any{
|
|
"Running": true,
|
|
},
|
|
})
|
|
}))
|
|
defer server.Close()
|
|
|
|
cli, err := dockerclient.NewClientWithOpts(dockerclient.WithHost(server.URL), dockerclient.WithVersion("1.43"))
|
|
if err != nil {
|
|
t.Fatalf("NewClientWithOpts() error: %v", err)
|
|
}
|
|
client := &Client{cli: cli}
|
|
|
|
if err := client.WaitForHealthy(context.Background(), "test-container", time.Second); err != nil {
|
|
t.Fatalf("WaitForHealthy() unexpected error: %v", err)
|
|
}
|
|
}
|