my-homelab-configs/apps/opsproof/overlay/services/jeannie_test.go

68 lines
2.3 KiB
Go

package services
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func TestStatusUsesAuthenticatedReadOnlyCommand(t *testing.T) {
requestCount := 0
server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
if request.Header.Get("Authorization") != "Bearer test-token" {
t.Fatalf("authorization header was not set")
}
switch request.URL.Path {
case "/v1/execute":
var payload struct {
Command string `json:"command"`
Args []string `json:"args"`
}
if err := json.NewDecoder(request.Body).Decode(&payload); err != nil {
t.Fatal(err)
}
if payload.Command != "status" || len(payload.Args) != 2 || payload.Args[0] != "all" || payload.Args[1] != "--json" {
t.Fatalf("unexpected command payload: %#v", payload)
}
response.WriteHeader(http.StatusAccepted)
_, _ = response.Write([]byte(`{"id":"status-1","status":"queued"}`))
case "/v1/executions/status-1":
requestCount++
_, _ = response.Write([]byte(`{"id":"status-1","status":"failed","output":"OCI config loaded\n{\"title\":\"Jeannie Status: all\",\"mode\":\"fast\",\"cluster\":{\"profile\":\"k3s\",\"runtime\":\"k3s\"},\"rows\":[{\"status\":\"fail\",\"area\":\"Kubernetes apps\",\"check\":\"n8n\",\"summary\":\"health=Progressing\",\"detail\":\"private detail\"}]}"}`))
default:
http.NotFound(response, request)
}
}))
defer server.Close()
client := NewJeannieClient(server.URL, "test-token")
client.PollInterval = time.Millisecond
snapshot, err := client.Status(context.Background())
if err != nil {
t.Fatal(err)
}
if requestCount != 1 || snapshot.Cluster.Profile != "k3s" || len(snapshot.Rows) != 1 {
t.Fatalf("unexpected snapshot: %#v", snapshot)
}
if snapshot.Rows[0].Check != "n8n" || snapshot.Rows[0].Summary != "health=Progressing" {
t.Fatalf("unexpected sanitized row: %#v", snapshot.Rows[0])
}
}
func TestStatusFailsClosedWithoutCredentials(t *testing.T) {
client := NewJeannieClient("http://127.0.0.1:8787", "")
if _, err := client.Status(context.Background()); err == nil {
t.Fatal("expected missing token to fail")
}
}
func TestDecodeStatusOutputRejectsNonJSON(t *testing.T) {
if _, err := decodeStatusOutput("status unavailable"); err == nil {
t.Fatal("expected invalid output to fail")
}
}