Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

test(ai): comprehensive eval coverage (~71%) including scenarios, overrides, and error cases

rcourtman9b304f8a78b1
diff --git a/internal/ai/eval/network_error_test.go b/internal/ai/eval/network_error_test.go
new file mode 100644
index 0000000000..cda0bc03e1
--- /dev/null
+++ b/internal/ai/eval/network_error_test.go
@@ -0,0 +1,91 @@
+package eval
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+)
+
+func TestRunner_ExecuteStep_NetworkError(t *testing.T) {
+ // Server immediately closes connection
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ panic("panic to force connection reset")
+ }))
+ defer server.Close()
+
+ runner := NewRunner(DefaultConfig())
+ runner.config.BaseURL = server.URL
+ runner.config.StepRetries = 0 // Fail fast
+
+ step := Step{Name: "NetFail", Prompt: "Hi"}
+ result := runner.executeStep(step, "")
+
+ assert.False(t, result.Success)
+ assert.Error(t, result.Error)
+}
+
+func TestRunner_ExecuteStep_HTTPError(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusInternalServerError)
+ w.Write([]byte("Internal Server Error"))
+ }))
+ defer server.Close()
+
+ runner := NewRunner(DefaultConfig())
+ runner.config.BaseURL = server.URL
+ runner.config.StepRetries = 0
+
+ step := Step{Name: "HTTPFail", Prompt: "Hi"}
+ result := runner.executeStep(step, "")
+
+ assert.False(t, result.Success)
+ assert.Error(t, result.Error)
+ assert.Contains(t, result.Error.Error(), "500")
+}
+
+func TestRunner_ExecuteStep_ContextTimeout(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ time.Sleep(200 * time.Millisecond)
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer server.Close()
+
+ cfg := DefaultConfig()
+ cfg.RequestTimeout = 100 * time.Millisecond
+ runner := NewRunner(cfg)
+ runner.config.BaseURL = server.URL
+
+ step := Step{Name: "Timeout", Prompt: "Hi"}
+ result := runner.executeStep(step, "")
+
+ assert.False(t, result.Success)
+ assert.Error(t, result.Error)
+ assert.Contains(t, result.Error.Error(), "context deadline exceeded")
+}
+
+func TestRunner_ExecuteStep_SSE_BadContentType(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json") // Wrong content type
+ w.WriteHeader(http.StatusOK)
+ w.Write([]byte("{}"))
+ }))
+ defer server.Close()
+
+ runner := NewRunner(DefaultConfig())
+ runner.config.BaseURL = server.URL
+
+ step := Step{Name: "BadContentType", Prompt: "Hi"}
+ result := runner.executeStep(step, "")
+
+ // It might succeed if it just parses the body, or fail if it strictly checks content type/stream
+ // The current implementation likely tries to scan it as SSE.
+ // If it's not SSE, scan might fail or return nothing.
+ // Let's see what happens.
+
+ // If parseSSEStream expects data: prefix lines, it acts as empty response?
+ // And empty response triggers retry or failure?
+ assert.False(t, result.Success)
+}
diff --git a/internal/ai/eval/patrol_override_test.go b/internal/ai/eval/patrol_override_test.go
new file mode 100644
index 0000000000..f3ffe298f2
--- /dev/null
+++ b/internal/ai/eval/patrol_override_test.go
@@ -0,0 +1,110 @@
+package eval
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestApplyPatrolModelOverride(t *testing.T) {
+ // Setup mock server
+ currentModel := "gpt-3.5-turbo"
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/api/settings/ai" && r.Method == "GET" {
+ json.NewEncoder(w).Encode(aiSettingsResponse{PatrolModel: currentModel})
+ return
+ }
+ if r.URL.Path == "/api/settings/ai/update" && r.Method == "PUT" {
+ var req aiSettingsUpdateRequest
+ json.NewDecoder(r.Body).Decode(&req)
+ if req.PatrolModel != nil {
+ currentModel = *req.PatrolModel
+ }
+ w.WriteHeader(http.StatusOK)
+ return
+ }
+ w.WriteHeader(http.StatusNotFound)
+ }))
+ defer server.Close()
+
+ runner := NewRunner(DefaultConfig())
+ runner.config.BaseURL = server.URL
+ runner.config.Model = "gpt-4" // Target override
+
+ // 1. Test override triggers update
+ restore, err := runner.applyPatrolModelOverride(context.Background())
+ require.NoError(t, err)
+ require.NotNil(t, restore)
+
+ // Check server state updated
+ assert.Equal(t, "openai:gpt-4", currentModel)
+
+ // 2. Test restore reverts update
+ restore()
+ assert.Equal(t, "gpt-3.5-turbo", currentModel)
+}
+
+func TestApplyPatrolModelOverride_NoChangeNeeded(t *testing.T) {
+ currentModel := "openai:gpt-4" // Use normalized format
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/api/settings/ai" && r.Method == "GET" {
+ json.NewEncoder(w).Encode(aiSettingsResponse{PatrolModel: currentModel})
+ return
+ }
+ }))
+ defer server.Close()
+
+ runner := NewRunner(DefaultConfig())
+ runner.config.BaseURL = server.URL
+ runner.config.Model = "gpt-4" // Normalized to openai:gpt-4
+
+ restore, err := runner.applyPatrolModelOverride(context.Background())
+ require.NoError(t, err)
+ assert.Nil(t, restore) // No override applied
+}
+
+func TestApplyPatrolModelOverride_EnvVar(t *testing.T) {
+ // Note: NormalizeModelString uses config.ParseModelString which might default to openai
+ // if provider is missing. But for "claude-3-opus" it likely detects anthropic.
+ os.Setenv("EVAL_PATROL_MODEL", "claude-3-opus")
+ defer os.Unsetenv("EVAL_PATROL_MODEL")
+
+ currentModel := "openai:gpt-4"
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/api/settings/ai" && r.Method == "GET" {
+ json.NewEncoder(w).Encode(aiSettingsResponse{PatrolModel: currentModel})
+ return
+ }
+ if r.URL.Path == "/api/settings/ai/update" && r.Method == "PUT" {
+ var req aiSettingsUpdateRequest
+ json.NewDecoder(r.Body).Decode(&req)
+ if req.PatrolModel != nil {
+ currentModel = *req.PatrolModel
+ }
+ w.WriteHeader(http.StatusOK)
+ return
+ }
+ }))
+ defer server.Close()
+
+ runner := NewRunner(DefaultConfig())
+ runner.config.BaseURL = server.URL
+ // config.Model doesn't matter, env var takes precedence
+
+ restore, err := runner.applyPatrolModelOverride(context.Background())
+ require.NoError(t, err)
+ require.NotNil(t, restore)
+
+ assert.Equal(t, "anthropic:claude-3-opus", currentModel)
+ restore()
+ assert.Equal(t, "openai:gpt-4", currentModel)
+}
diff --git a/internal/ai/eval/patrol_scenario_test.go b/internal/ai/eval/patrol_scenario_test.go
new file mode 100644
index 0000000000..b23a360d34
--- /dev/null
+++ b/internal/ai/eval/patrol_scenario_test.go
@@ -0,0 +1,220 @@
+package eval
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+)
+
+func TestRunner_RunPatrolScenario_Success(t *testing.T) {
+ // Mock state
+ running := false
+ done := false
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ // Basic Auth Check
+ u, p, ok := r.BasicAuth()
+ if !ok || u != "admin" || p != "admin" {
+ w.WriteHeader(http.StatusUnauthorized)
+ return
+ }
+
+ switch r.URL.Path {
+ case "/api/ai/patrol/status":
+ if r.Method != "GET" {
+ w.WriteHeader(http.StatusMethodNotAllowed)
+ return
+ }
+ // Status logic:
+ // Initially not running.
+ // After trigger, running=true.
+ // After stream connected/finished, running=false (simulated here)
+ // For simplicity, let's say after 2 status checks while running, it finishes.
+
+ // If already done, return not running
+ if done {
+ json.NewEncoder(w).Encode(map[string]bool{"running": false, "healthy": true})
+ return
+ }
+
+ if running {
+ // Simulate finishing eventually
+ // The real runner polls. Let's make it finish quickly.
+ // We'll let the stream handler flip the 'done' bit?
+ // Or just flip it here after a check?
+ // Let's rely on the runner logic: it waits for idle first, then triggers.
+
+ // For "waitForPatrolComplete", it polls.
+ // We return true until stream is consumed?
+ // Let's keep it simple: always return running=true here, until we flip it externally?
+ // Or just return false immediately if done.
+ }
+
+ // Logic:
+ // 1. Runner checks idle -> returns false
+ // 2. Runner triggers -> sets running=true (internal mock state)
+ // 3. Runner polls completion -> returns true for a bit, then false
+
+ json.NewEncoder(w).Encode(map[string]bool{"running": running, "healthy": true})
+
+ case "/api/ai/patrol/run":
+ if r.Method != "POST" {
+ w.WriteHeader(http.StatusMethodNotAllowed)
+ return
+ }
+ running = true
+ done = false
+ w.WriteHeader(http.StatusOK)
+
+ case "/api/ai/patrol/stream":
+ if r.Method != "GET" {
+ w.WriteHeader(http.StatusMethodNotAllowed)
+ return
+ }
+ w.Header().Set("Content-Type", "text/event-stream")
+
+ // Send some events
+ fmt.Fprintf(w, "data: {\"type\":\"start\"}\n\n")
+ fmt.Fprintf(w, "data: {\"type\":\"tool_start\",\"tool_id\":\"t1\",\"tool_name\":\"scan\"}\n\n")
+ time.Sleep(10 * time.Millisecond)
+ fmt.Fprintf(w, "data: {\"type\":\"tool_end\",\"tool_id\":\"t1\",\"tool_output\":\"ok\",\"tool_success\":true}\n\n")
+ fmt.Fprintf(w, "data: {\"type\":\"complete\"}\n\n")
+
+ // Signal that we are done running after stream closes/finishes
+ running = false
+ done = true
+
+ case "/api/ai/patrol/findings":
+ if r.Method != "GET" {
+ w.WriteHeader(http.StatusMethodNotAllowed)
+ return
+ }
+ findings := []PatrolFinding{
+ {ID: "f1", Key: "issue.1", Severity: "high", Title: "Issue"},
+ }
+ json.NewEncoder(w).Encode(findings)
+
+ default:
+ w.WriteHeader(http.StatusNotFound)
+ }
+ }))
+ defer server.Close()
+
+ runner := NewRunner(DefaultConfig())
+ runner.config.BaseURL = server.URL
+ runner.config.Verbose = true
+
+ scenario := PatrolScenario{
+ Name: "Patrol Success",
+ Timeout: 5 * time.Second,
+ Assertions: []PatrolAssertion{
+ PatrolAssertCompleted(),
+ PatrolAssertHasFindings(),
+ PatrolAssertToolUsed("scan"),
+ PatrolAssertNoToolErrors(),
+ },
+ }
+
+ result := runner.RunPatrolScenario(scenario)
+
+ assert.True(t, result.Success)
+ assert.True(t, result.Completed)
+ assert.Len(t, result.Findings, 1)
+ assert.Len(t, result.ToolCalls, 1)
+
+ // Check assertions passed
+ for _, a := range result.Assertions {
+ assert.True(t, a.Passed, "Assertion failed: %s", a.Name)
+ }
+}
+
+func TestRunner_RunPatrolScenario_SetupTeardown(t *testing.T) {
+ setupCalled := false
+ teardownCalled := false
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ // Simple mock allowing everything
+ if r.URL.Path == "/api/ai/patrol/status" {
+ json.NewEncoder(w).Encode(map[string]bool{"running": false})
+ return
+ }
+ if r.URL.Path == "/api/ai/patrol/run" {
+ w.WriteHeader(http.StatusOK)
+ return
+ }
+ if r.URL.Path == "/api/ai/patrol/stream" {
+ // quick stream
+ w.Header().Set("Content-Type", "text/event-stream")
+ fmt.Fprintf(w, "data: {\"type\":\"complete\"}\n\n")
+ return
+ }
+ if r.URL.Path == "/api/ai/patrol/findings" {
+ json.NewEncoder(w).Encode([]PatrolFinding{})
+ return
+ }
+ }))
+ defer server.Close()
+
+ runner := NewRunner(DefaultConfig())
+ runner.config.BaseURL = server.URL
+
+ scenario := PatrolScenario{
+ Name: "Setup Teardown",
+ Setup: func(r *Runner) error {
+ setupCalled = true
+ return nil
+ },
+ Teardown: func(r *Runner) error {
+ teardownCalled = true
+ return nil
+ },
+ }
+
+ result := runner.RunPatrolScenario(scenario)
+ assert.True(t, result.Success)
+ assert.True(t, setupCalled)
+ assert.True(t, teardownCalled)
+}
+
+func TestRunner_RunPatrolScenario_SetupFail(t *testing.T) {
+ runner := NewRunner(DefaultConfig())
+
+ scenario := PatrolScenario{
+ Name: "Setup Fail",
+ Setup: func(r *Runner) error {
+ return fmt.Errorf("setup failed")
+ },
+ }
+
+ result := runner.RunPatrolScenario(scenario)
+ assert.False(t, result.Success)
+ assert.Contains(t, result.Error.Error(), "setup failed")
+}
+
+func TestRunner_RunPatrolScenario_TriggerFail(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/api/ai/patrol/status" {
+ json.NewEncoder(w).Encode(map[string]bool{"running": false})
+ return
+ }
+ if r.URL.Path == "/api/ai/patrol/run" {
+ w.WriteHeader(http.StatusInternalServerError) // Trigger fails
+ return
+ }
+ }))
+ defer server.Close()
+
+ runner := NewRunner(DefaultConfig())
+ runner.config.BaseURL = server.URL
+
+ scenario := PatrolScenario{Name: "Trigger Fail"}
+ result := runner.RunPatrolScenario(scenario)
+
+ assert.False(t, result.Success)
+ assert.Contains(t, result.Error.Error(), "status 500")
+}
diff --git a/internal/ai/eval/print_helpers_test.go b/internal/ai/eval/print_helpers_test.go
new file mode 100644
index 0000000000..1fe9a498cb
--- /dev/null
+++ b/internal/ai/eval/print_helpers_test.go
@@ -0,0 +1,137 @@
+package eval
+
+import (
+ "fmt"
+ "io"
+ "os"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+)
+
+// captureOutput captures stdout during the execution of f
+func captureOutput(f func()) string {
+ old := os.Stdout
+ r, w, _ := os.Pipe()
+ os.Stdout = w
+
+ f()
+
+ w.Close()
+ os.Stdout = old
+
+ out, _ := io.ReadAll(r)
+ return string(out)
+}
+
+func TestPrintStepResult(t *testing.T) {
+ runner := &Runner{config: DefaultConfig()} // Verbose defaults to true
+ runner.config.Verbose = true
+
+ result := &StepResult{
+ StepName: "Test Step",
+ Prompt: "Do something",
+ Success: true,
+ Duration: 100 * time.Millisecond,
+ InputTokens: 10,
+ OutputTokens: 20,
+ Content: "Done.",
+ ToolCalls: []ToolCallEvent{
+ {Name: "tool1", Input: "arg", Output: "res", Success: true},
+ },
+ Assertions: []AssertionResult{
+ {Name: "check", Passed: true, Message: "ok"},
+ },
+ }
+
+ output := captureOutput(func() {
+ runner.printStepResult(result)
+ })
+
+ assert.Contains(t, output, "Duration:")
+ assert.Contains(t, output, "tool1")
+ assert.Contains(t, output, "[OK]:") // Tool call status
+ assert.Contains(t, output, "[PASS]") // Assertion status
+}
+
+func TestPrintStepResult_Failure(t *testing.T) {
+ runner := &Runner{config: DefaultConfig()}
+ result := &StepResult{
+ StepName: "Fail Step",
+ Success: false,
+ Error: fmt.Errorf("oops"),
+ Assertions: []AssertionResult{
+ {Name: "bad", Passed: false, Message: "failed"},
+ },
+ }
+
+ output := captureOutput(func() {
+ runner.printStepResult(result)
+ })
+
+ assert.Contains(t, output, "ERROR: oops")
+ assert.Contains(t, output, "[FAIL] bad: failed")
+}
+
+func TestPrintPatrolSummary(t *testing.T) {
+ runner := &Runner{config: DefaultConfig()}
+ runner.config.Verbose = true
+
+ result := PatrolRunResult{
+ ScenarioName: "Patrol 1",
+ Success: true,
+ Duration: 5 * time.Second,
+ Completed: true,
+ ToolCalls: []ToolCallEvent{
+ {Name: "scan", Input: "all", Output: "ok", Success: true},
+ },
+ Findings: []PatrolFinding{
+ {Key: "k1", Severity: "high", Title: "issue"},
+ },
+ Content: "Summary text",
+ Assertions: []AssertionResult{
+ {Name: "a1", Passed: true, Message: "good"},
+ },
+ Quality: &PatrolQualityReport{
+ CoverageKnown: true,
+ SignalsMatched: 1,
+ SignalsTotal: 1,
+ SignalCoverage: 1.0,
+ Signals: []PatrolSignalResult{
+ {SignalType: "s1", Matched: true, ResourceID: "r1"},
+ },
+ },
+ }
+
+ output := captureOutput(func() {
+ runner.PrintPatrolSummary(result)
+ })
+
+ assert.Contains(t, output, "PATROL SCENARIO: Patrol 1")
+ assert.Contains(t, output, "Result: PASSED")
+ assert.Contains(t, output, "scan")
+ assert.Contains(t, output, "k1")
+ assert.Contains(t, output, "Summary text")
+ assert.Contains(t, output, "Signal coverage: 1/1 (100%)")
+}
+
+func TestPrintPatrolSummary_Failure(t *testing.T) {
+ runner := &Runner{config: DefaultConfig()}
+ result := PatrolRunResult{
+ ScenarioName: "Patrol Fail",
+ Success: false,
+ Error: fmt.Errorf("crash"),
+ Assertions: []AssertionResult{
+ {Name: "a1", Passed: false, Message: "bad"},
+ },
+ }
+
+ output := captureOutput(func() {
+ runner.PrintPatrolSummary(result)
+ })
+
+ assert.Contains(t, output, "ERROR: crash")
+ assert.Contains(t, output, "Result: FAILED")
+ assert.Contains(t, output, "Assertion 'a1': bad")
+}
diff --git a/internal/ai/eval/scenario_test.go b/internal/ai/eval/scenario_test.go
new file mode 100644
index 0000000000..d3fb2af2d3
--- /dev/null
+++ b/internal/ai/eval/scenario_test.go
@@ -0,0 +1,166 @@
+package eval
+
+import (
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+)
+
+func TestRunner_RunScenario_Success(t *testing.T) {
+ // Mock server that returns different responses based on request count (or prompt)
+ calls := 0
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls++
+ w.Header().Set("Content-Type", "text/event-stream")
+
+ if calls == 1 {
+ // Step 1 response
+ fmt.Fprintf(w, "data: {\"type\":\"content\",\"data\":{\"text\":\"Step 1 done\"}}\n\n")
+ fmt.Fprintf(w, "data: {\"type\":\"done\",\"data\":{\"session_id\":\"session-1\"}}\n\n")
+ return
+ }
+
+ if calls == 2 {
+ // Step 2 response (uses same session)
+ // Check prompt or headers if needed, but simple counter is enough for flow test
+ fmt.Fprintf(w, "data: {\"type\":\"content\",\"data\":{\"text\":\"Step 2 done\"}}\n\n")
+ fmt.Fprintf(w, "data: {\"type\":\"done\",\"data\":{\"session_id\":\"session-1\"}}\n\n")
+ return
+ }
+
+ // Should not reach here
+ w.WriteHeader(http.StatusInternalServerError)
+ }))
+ defer server.Close()
+
+ runner := NewRunner(DefaultConfig())
+ runner.config.BaseURL = server.URL
+ runner.config.Verbose = false
+ runner.config.Preflight = false // Disable preflight for this specific test
+
+ scenario := Scenario{
+ Name: "Multi-Step Success",
+ Steps: []Step{
+ {
+ Name: "Step 1",
+ Prompt: "First",
+ Assertions: []Assertion{
+ AssertContentContains("Step 1"),
+ },
+ },
+ {
+ Name: "Step 2",
+ Prompt: "Second",
+ Assertions: []Assertion{
+ AssertContentContains("Step 2"),
+ },
+ },
+ },
+ }
+
+ result := runner.RunScenario(scenario)
+
+ assert.True(t, result.Passed)
+ assert.Len(t, result.Steps, 2)
+ assert.Equal(t, "Step 1 done", result.Steps[0].Content)
+ assert.Equal(t, "Step 2 done", result.Steps[1].Content)
+ assert.Equal(t, "session-1", result.Steps[1].SessionID) // Should propagate
+}
+
+func TestRunner_RunScenario_AssertionFailure(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "text/event-stream")
+ fmt.Fprintf(w, "data: {\"type\":\"content\",\"data\":{\"text\":\"Step done\"}}\n\n")
+ fmt.Fprintf(w, "data: {\"type\":\"done\",\"data\":{\"session_id\":\"session-1\"}}\n\n")
+ }))
+ defer server.Close()
+
+ runner := NewRunner(DefaultConfig())
+ runner.config.BaseURL = server.URL
+
+ scenario := Scenario{
+ Name: "Assertion Failure",
+ Steps: []Step{
+ {
+ Name: "Step 1",
+ Prompt: "Run",
+ Assertions: []Assertion{
+ func(result *StepResult) AssertionResult {
+ return AssertionResult{Name: "FailAlways", Passed: false, Message: "Boom"}
+ },
+ },
+ },
+ {
+ Name: "Step 2",
+ Prompt: "Should not run",
+ },
+ },
+ }
+
+ result := runner.RunScenario(scenario)
+
+ assert.False(t, result.Passed)
+ assert.Len(t, result.Steps, 1) // Should stop after first step
+ assert.False(t, result.Steps[0].Success)
+}
+
+func TestRunner_RunScenario_WithPreflight(t *testing.T) {
+ calls := 0
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls++
+ w.Header().Set("Content-Type", "text/event-stream")
+ // Preflight and Step 1 return same simple response
+ fmt.Fprintf(w, "data: {\"type\":\"content\",\"data\":{\"text\":\"Hello\"}}\n\n")
+ fmt.Fprintf(w, "data: {\"type\":\"done\",\"data\":{\"session_id\":\"session-1\"}}\n\n")
+ }))
+ defer server.Close()
+
+ runner := NewRunner(DefaultConfig())
+ runner.config.BaseURL = server.URL
+ runner.config.Preflight = true
+
+ scenario := Scenario{
+ Name: "Preflight Scenario",
+ Steps: []Step{
+ {Name: "Step 1", Prompt: "Hi"},
+ },
+ }
+
+ result := runner.RunScenario(scenario)
+
+ assert.True(t, result.Passed)
+ // Steps should include Preflight + Step 1 = 2 steps
+ assert.Len(t, result.Steps, 2)
+ assert.Equal(t, "Preflight", result.Steps[0].StepName)
+ assert.Equal(t, "Step 1", result.Steps[1].StepName)
+}
+
+func TestRunner_RunScenario_PreflightFail(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ // Fail connection
+ w.WriteHeader(http.StatusInternalServerError)
+ }))
+ defer server.Close()
+
+ runner := NewRunner(DefaultConfig())
+ runner.config.BaseURL = server.URL
+ runner.config.Preflight = true
+ runner.config.StepRetries = 0 // Fail fast
+
+ scenario := Scenario{
+ Name: "Preflight Fail",
+ Steps: []Step{
+ {Name: "Step 1", Prompt: "Hi"},
+ },
+ }
+
+ result := runner.RunScenario(scenario)
+
+ assert.False(t, result.Passed)
+ assert.Len(t, result.Steps, 1) // Only preflight step captured
+ assert.Equal(t, "Preflight", result.Steps[0].StepName)
+ assert.False(t, result.Steps[0].Success)
+}