|
| 1 | +// +build functional |
| 2 | + |
| 3 | +package main |
| 4 | + |
| 5 | +import ( |
| 6 | + "encoding/json" |
| 7 | + "os" |
| 8 | + "os/exec" |
| 9 | + "strings" |
| 10 | + "testing" |
| 11 | + "time" |
| 12 | + |
| 13 | + "github.com/docker/docker/api/types" |
| 14 | + docker "github.com/docker/docker/client" |
| 15 | + mqtt "github.com/eclipse/paho.mqtt.golang" |
| 16 | + "github.com/stretchr/testify/assert" |
| 17 | +) |
| 18 | + |
| 19 | +type testStatus struct { |
| 20 | + appStatus *Status |
| 21 | + ui *MqttTestClient |
| 22 | +} |
| 23 | + |
| 24 | +var ts testStatus |
| 25 | + |
| 26 | +func TestMain(m *testing.M) { |
| 27 | + os.Exit(setupAndRun(m)) |
| 28 | +} |
| 29 | + |
| 30 | +func setupAndRun(m *testing.M) int { |
| 31 | + ts.ui = NewMqttTestClientLocal() |
| 32 | + defer ts.ui.Close() |
| 33 | + |
| 34 | + ts.appStatus = NewStatus(program{}.Config, nil, nil, "") |
| 35 | + ts.appStatus.dockerClient, _ = docker.NewClientWithOpts(docker.WithVersion("1.38")) |
| 36 | + ts.appStatus.mqttClient = mqtt.NewClient(mqtt.NewClientOptions().AddBroker("tcp://localhost:1883").SetClientID("arduino-connector")) |
| 37 | + |
| 38 | + defer ts.appStatus.mqttClient.Disconnect(100) |
| 39 | + |
| 40 | + return m.Run() |
| 41 | +} |
| 42 | + |
| 43 | +func TestDockerPsApi(t *testing.T) { |
| 44 | + if token := ts.appStatus.mqttClient.Connect(); token.Wait() && token.Error() != nil { |
| 45 | + t.Fatal(token.Error()) |
| 46 | + } |
| 47 | + |
| 48 | + subscribeTopic(ts.appStatus.mqttClient, "0", "/containers/ps/post", ts.appStatus, ts.appStatus.ContainersPsEvent, false) |
| 49 | + resp := ts.ui.MqttSendAndReceiveTimeout(t, "/containers/ps", "{}", 50*time.Millisecond) |
| 50 | + |
| 51 | + // ask Docker about containers effectively running |
| 52 | + cmd := exec.Command("bash", "-c", "docker ps -a") |
| 53 | + out, err := cmd.CombinedOutput() |
| 54 | + if err != nil { |
| 55 | + t.Fatal(err) |
| 56 | + } |
| 57 | + |
| 58 | + lines := strings.Split(string(out), "\n") |
| 59 | + // Remove the first line (command output header) and the last line (empty line) |
| 60 | + lines = lines[1 : len(lines)-1] |
| 61 | + |
| 62 | + // Take json without INFO tag |
| 63 | + resp = strings.TrimPrefix(resp, "INFO: ") |
| 64 | + resp = strings.TrimSuffix(resp, "\n\n") |
| 65 | + var result []types.Container |
| 66 | + if err := json.Unmarshal([]byte(resp), &result); err != nil { |
| 67 | + t.Fatal(err) |
| 68 | + } |
| 69 | + |
| 70 | + assert.Equal(t, len(result), len(lines)) |
| 71 | + for i, line := range lines { |
| 72 | + containerId := strings.Fields(line)[0] |
| 73 | + assert.True(t, strings.HasPrefix(result[i].ID, containerId)) |
| 74 | + } |
| 75 | +} |
0 commit comments