Files
lincodex/labd/internal/lxd/client_test.go
T

156 lines
5.4 KiB
Go

package lxd_test
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"lincodex/labd/internal/lxd"
)
// apiStub answers like the LXD API: requests are recorded, and mutating
// calls return an async operation that the client must wait for.
type apiStub struct {
mu sync.Mutex
requests []string
bodies map[string]map[string]any
waits int
running bool
failOp bool
}
func (s *apiStub) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.mu.Lock()
defer s.mu.Unlock()
key := r.Method + " " + r.URL.Path
s.requests = append(s.requests, key+"?"+r.URL.RawQuery)
if r.Body != nil && r.ContentLength != 0 {
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body) // A stub; malformed bodies fail the assertions.
s.bodies[key] = body
}
switch {
case key == "GET /1.0/instances":
writeSync(w, []map[string]any{{"name": "lcxl-0102030405-r1", "status": "Running", "config": map[string]string{"user.lincodex.lab": "x"}}})
case key == "GET /1.0/instances/lcxl-0102030405-r1/state":
status := "Stopped"
if s.running {
status = "Running"
}
writeSync(w, map[string]any{"status": status})
case key == "DELETE /1.0/instances/missing", key == "DELETE /1.0/networks/missing":
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"type":"error","error":"Not found","error_code":404}`))
case key == "POST /1.0/networks":
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"type":"error","error":"The network already exists","error_code":400}`))
case strings.HasPrefix(key, "GET /1.0/operations/op-1/wait"):
s.waits++
code := 103
if s.waits > 1 {
code = 200
if s.failOp {
code = 400
}
}
writeSync(w, map[string]any{"id": "op-1", "status_code": code, "err": "copy failed"})
case r.Method == http.MethodPost || r.Method == http.MethodPut || r.Method == http.MethodDelete:
w.WriteHeader(http.StatusAccepted)
_, _ = w.Write([]byte(`{"type":"async","status_code":100,"operation":"/1.0/operations/op-1","metadata":{}}`))
default:
http.NotFound(w, r)
}
}
func writeSync(w http.ResponseWriter, metadata any) {
_ = json.NewEncoder(w).Encode(map[string]any{"type": "sync", "status_code": 200, "metadata": metadata})
}
func newStub(t *testing.T) (*apiStub, *lxd.Client) {
t.Helper()
stub := &apiStub{bodies: map[string]map[string]any{}}
server := httptest.NewServer(stub)
t.Cleanup(server.Close)
return stub, lxd.NewWithHTTPClient(server.Client(), server.URL, "labs")
}
func TestCreateInstanceCopiesTheSnapshotAndWaitsForTheOperation(t *testing.T) {
stub, client := newStub(t)
err := client.CreateInstance(context.Background(), lxd.InstanceSpec{
Name: "lcxl-0102030405-r1", Source: "lincodex-tpl-chr/base", Profiles: []string{"lincodex-lab-small"},
Config: map[string]string{"user.lincodex.lab": "x"},
Devices: map[string]map[string]string{"eth1": {"type": "nic", "network": "lxl010203040500"}},
})
if err != nil {
t.Fatalf("CreateInstance() error = %v", err)
}
body := stub.bodies["POST /1.0/instances"]
source, _ := body["source"].(map[string]any)
if body["type"] != "virtual-machine" || source["type"] != "copy" || source["source"] != "lincodex-tpl-chr/base" {
t.Fatalf("create body = %v", body)
}
if stub.waits != 2 {
t.Fatalf("operation polls = %d, want 2 (running, then success)", stub.waits)
}
for _, request := range stub.requests {
if !strings.Contains(request, "project=labs") {
t.Fatalf("request %q does not name the project", request)
}
}
}
func TestFailedOperationIsAnAPIError(t *testing.T) {
stub, client := newStub(t)
stub.failOp = true
err := client.DeleteInstance(context.Background(), "lcxl-0102030405-r1")
var apiErr *lxd.APIError
if !errors.As(err, &apiErr) || apiErr.Code != 400 {
t.Fatalf("DeleteInstance() error = %v, want an APIError 400", err)
}
}
func TestMissingObjectsAreNotFound(t *testing.T) {
_, client := newStub(t)
if err := client.DeleteInstance(context.Background(), "missing"); !errors.Is(err, lxd.ErrNotFound) {
t.Fatalf("DeleteInstance() error = %v, want ErrNotFound", err)
}
if err := client.DeleteNetwork(context.Background(), "missing"); !errors.Is(err, lxd.ErrNotFound) {
t.Fatalf("DeleteNetwork() error = %v, want ErrNotFound", err)
}
var apiErr *lxd.APIError
if err := client.CreateNetwork(context.Background(), lxd.NetworkSpec{Name: "lxl010203040500"}); !errors.As(err, &apiErr) {
t.Fatalf("CreateNetwork() error = %v, want an APIError", err)
}
}
func TestStopInstanceSkipsAStoppedInstance(t *testing.T) {
stub, client := newStub(t)
if err := client.StopInstance(context.Background(), "lcxl-0102030405-r1"); err != nil {
t.Fatalf("StopInstance() error = %v", err)
}
if _, sent := stub.bodies["PUT /1.0/instances/lcxl-0102030405-r1/state"]; sent {
t.Fatal("StopInstance() sent a stop for a stopped instance")
}
stub.running = true
if err := client.StopInstance(context.Background(), "lcxl-0102030405-r1"); err != nil {
t.Fatalf("StopInstance() error = %v", err)
}
body := stub.bodies["PUT /1.0/instances/lcxl-0102030405-r1/state"]
if body["action"] != "stop" || body["force"] != true {
t.Fatalf("stop body = %v", body)
}
}
func TestListInstancesDecodesConfig(t *testing.T) {
_, client := newStub(t)
instances, err := client.ListInstances(context.Background())
if err != nil || len(instances) != 1 || instances[0].Config["user.lincodex.lab"] != "x" {
t.Fatalf("ListInstances() = %+v, %v", instances, err)
}
}