66 lines
2.0 KiB
Go
66 lines
2.0 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"io"
|
|
"net/http"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
type roundTripFunc func(*http.Request) (*http.Response, error)
|
|
|
|
func (function roundTripFunc) Do(request *http.Request) (*http.Response, error) {
|
|
return function(request)
|
|
}
|
|
|
|
func TestListContainers(t *testing.T) {
|
|
client := roundTripFunc(func(request *http.Request) (*http.Response, error) {
|
|
if got, want := request.URL.String(), "http://localhost:8080/api/v1/engines/1/containers"; got != want {
|
|
t.Errorf("request URL = %q, want %q", got, want)
|
|
}
|
|
return &http.Response{
|
|
StatusCode: http.StatusOK,
|
|
Status: "200 OK",
|
|
Body: io.NopCloser(strings.NewReader(`{"containers":[{"id":"abc123","names":["/web"],"image":"nginx","state":"running","status":"Up 1 minute"}]}`)),
|
|
}, nil
|
|
})
|
|
|
|
result, err := listContainers(context.Background(), client, defaultServerURL, 1)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(result.Containers) != 1 || result.Containers[0].ID != "abc123" {
|
|
t.Fatalf("unexpected containers: %#v", result.Containers)
|
|
}
|
|
}
|
|
|
|
func TestListContainersReturnsAPIError(t *testing.T) {
|
|
client := roundTripFunc(func(_ *http.Request) (*http.Response, error) {
|
|
return &http.Response{
|
|
StatusCode: http.StatusNotFound,
|
|
Status: "404 Not Found",
|
|
Body: io.NopCloser(strings.NewReader(`{"error":{"code":"engine_not_found","message":"engine not found"}}`)),
|
|
}, nil
|
|
})
|
|
|
|
_, err := listContainers(context.Background(), client, defaultServerURL, 2)
|
|
if err == nil || !strings.Contains(err.Error(), "engine not found") {
|
|
t.Fatalf("error = %v, want engine-not-found message", err)
|
|
}
|
|
}
|
|
|
|
func TestRunContainersPrintsTable(t *testing.T) {
|
|
var output bytes.Buffer
|
|
printContainers(&output, []containerResponse{{
|
|
ID: "1234567890abcdef", Names: []string{"/web"}, Image: "nginx", State: "running", Status: "Up",
|
|
}})
|
|
|
|
for _, expected := range []string{"1234567890ab", "web", "nginx", "running"} {
|
|
if !strings.Contains(output.String(), expected) {
|
|
t.Errorf("output %q does not contain %q", output.String(), expected)
|
|
}
|
|
}
|
|
}
|