faro/internal/api/api_test.go

77 lines
2.3 KiB
Go

package api
import (
"context"
"errors"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/moby/moby/api/types/container"
"github.com/moby/moby/client"
)
type fakeContainerLister struct {
containers []container.Summary
err error
options client.ContainerListOptions
}
func (f *fakeContainerLister) ContainerList(_ context.Context, options client.ContainerListOptions) (client.ContainerListResult, error) {
f.options = options
return client.ContainerListResult{Items: f.containers}, f.err
}
func TestListContainers(t *testing.T) {
docker := &fakeContainerLister{containers: []container.Summary{{
ID: "abc123", Names: []string{"/web"}, Image: "nginx:latest", State: "running",
}}}
request := httptest.NewRequest(http.MethodGet, "/api/v1/engines/1/containers", nil)
response := httptest.NewRecorder()
NewHandler(docker, testLogger()).ServeHTTP(response, request)
if response.Code != http.StatusOK {
t.Fatalf("status = %d, want %d", response.Code, http.StatusOK)
}
if !docker.options.All {
t.Error("ContainerList All = false, want true")
}
if body := response.Body.String(); !strings.Contains(body, `"id":"abc123"`) {
t.Errorf("response body does not contain container: %s", body)
}
}
func TestListContainersRejectsUnknownEngine(t *testing.T) {
response := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodGet, "/api/v1/engines/2/containers", nil)
NewHandler(&fakeContainerLister{}, testLogger()).ServeHTTP(response, request)
if response.Code != http.StatusNotFound {
t.Fatalf("status = %d, want %d", response.Code, http.StatusNotFound)
}
}
func TestListContainersHandlesDockerError(t *testing.T) {
docker := &fakeContainerLister{err: errors.New("daemon unavailable")}
response := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodGet, "/api/v1/engines/1/containers", nil)
NewHandler(docker, testLogger()).ServeHTTP(response, request)
if response.Code != http.StatusBadGateway {
t.Fatalf("status = %d, want %d", response.Code, http.StatusBadGateway)
}
if body := response.Body.String(); !strings.Contains(body, `"code":"docker_unavailable"`) {
t.Errorf("unexpected response body: %s", body)
}
}
func testLogger() *slog.Logger {
return slog.New(slog.NewTextHandler(io.Discard, nil))
}