1package docker
2
3import (
4 "context"
5 "encoding/json"
6 "net/http"
7 "net/http/httptest"
8 "strings"
9 "testing"
10
11 "github.com/docker/docker/client"
12 "github.com/stretchr/testify/assert"
13 "github.com/stretchr/testify/require"
14
15 "github.com/bnema/gordon/internal/domain"
16)
17
18func TestRuntime_CreateContainerAppliesRestartPolicy(t *testing.T) {
19 var createBody map[string]any
20 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
21 switch {
22 case r.Method == http.MethodPost && r.URL.Path == "/v1.41/containers/create":
23 require.NoError(t, json.NewDecoder(r.Body).Decode(&createBody))
24 w.Header().Set("Content-Type", "application/json")
25 _, _ = w.Write([]byte(`{"Id":"abc123","Warnings":null}`))
26 case r.Method == http.MethodGet && r.URL.Path == "/v1.41/containers/abc123/json":
27 w.Header().Set("Content-Type", "application/json")
28 _, _ = w.Write([]byte(`{
29 "Id":"abc123",
30 "Name":"/gordon-app.example.com",
31 "Image":"sha256:image",
32 "Created":"2026-05-05T00:00:00Z",
33 "Config":{"Image":"nginx:latest","Labels":{}},
34 "State":{"Status":"created","ExitCode":0},
35 "NetworkSettings":{"Ports":{}}
36 }`))
37 default:
38 t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
39 }
40 }))
41 defer server.Close()
42
43 host := strings.TrimPrefix(server.URL, "http://")
44 cli, err := client.NewClientWithOpts(client.WithHost("tcp://"+host), client.WithVersion("1.41"), client.WithHTTPClient(server.Client()))
45 require.NoError(t, err)
46
47 runtime := NewRuntimeWithClient(cli)
48 created, err := runtime.CreateContainer(context.Background(), &domain.ContainerConfig{
49 Image: "nginx:latest",
50 Name: "gordon-app.example.com",
51 RestartPolicy: domain.RestartPolicyAlways,
52 })
53 require.NoError(t, err)
54 assert.Equal(t, "abc123", created.ID)
55
56 require.NotNil(t, createBody)
57 hostConfig, ok := createBody["HostConfig"].(map[string]any)
58 require.True(t, ok)
59 restartPolicy, ok := hostConfig["RestartPolicy"].(map[string]any)
60 require.True(t, ok)
61 assert.Equal(t, domain.RestartPolicyAlways, restartPolicy["Name"])
62}