vdi-cloud/platform/pkg/proxmox/client_test.go

78 lines
2.3 KiB
Go

package proxmox
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func TestTLSAndTaskLifecycle(t *testing.T) {
polls := 0
ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "PVEAPIToken=vdi@pve!console=secret" {
t.Error("missing PVE token")
}
w.Header().Set("Content-Type", "application/json")
switch {
case strings.HasSuffix(r.URL.Path, "/status/start"):
if r.Method != "POST" {
t.Error("action should POST")
}
w.Write([]byte(`{"data":"UPID:node:123"}`))
case strings.HasSuffix(r.URL.Path, "/status/current"):
w.Write([]byte(`{"data":{"status":"running"}}`))
case strings.Contains(r.URL.Path, "/tasks/"):
polls++
if polls < 2 {
w.Write([]byte(`{"data":{"status":"running"}}`))
} else {
w.Write([]byte(`{"data":{"status":"stopped","exitstatus":"OK"}}`))
}
default:
w.WriteHeader(404)
}
}))
defer ts.Close()
c, err := New(ts.URL, "vdi@pve!console", "secret", "")
if err != nil {
t.Fatal(err)
}
if _, err = c.Action(context.Background(), "node", 201, "start"); err == nil {
t.Fatal("untrusted PVE certificate must not be accepted")
}
c.HTTP = ts.Client()
upid, err := c.Action(context.Background(), "node", 201, "start")
if err != nil {
t.Fatal(err)
}
if err = c.Wait(context.Background(), "node", upid, time.Millisecond); err != nil {
t.Fatal(err)
}
if polls != 2 {
t.Fatalf("expected task polling; got %d", polls)
}
if _, err = c.Action(context.Background(), "node", 201, "restore"); err == nil {
t.Fatal("restore must never map to hard reset")
}
}
func TestFailedPVEJobIsNotSuccess(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"data":{"status":"stopped","exitstatus":"ERROR: disk full"}}`))
}))
defer ts.Close()
c := &Client{BaseURL: ts.URL, HTTP: ts.Client()}
if err := c.Wait(context.Background(), "node", "task", time.Millisecond); err == nil {
t.Fatal("failed PVE job reported as success")
}
}
func TestRejectInsecureOrigin(t *testing.T) {
for _, base := range []string{"http://pve:8006", "https://user:password@pve:8006", "https://pve:8006/other"} {
if _, err := New(base, "id", "secret", ""); err == nil {
t.Fatalf("accepted %s", base)
}
}
}