agent/pkg/agentic/remote_client_test.go
Snider 537226bd4d feat: AX v0.8.0 upgrade — Core features + quality gates
AX Quality Gates (RFC-025):
- Eliminate os/exec from all test + production code (12+ files)
- Eliminate encoding/json from all test files (15 files, 66 occurrences)
- Eliminate os from all test files except TestMain (Go runtime contract)
- Eliminate path/filepath, net/url from all files
- String concat: 39 violations replaced with core.Concat()
- Test naming AX-7: 264 test functions renamed across all 6 packages
- Example test 1:1 coverage complete

Core Features Adopted:
- Task Composition: agent.completion pipeline (QA → PR → Verify → Ingest → Poke)
- PerformAsync: completion pipeline runs with WaitGroup + progress tracking
- Config: agents.yaml loaded once, feature flags (auto-qa/pr/merge/ingest)
- Named Locks: c.Lock("drain") for queue serialisation
- Registry: workspace state with cross-package QUERY access
- QUERY: c.QUERY(WorkspaceQuery{Status: "running"}) for cross-service queries
- Action descriptions: 25+ Actions self-documenting
- Data mounts: prompts/tasks/flows/personas/workspaces via c.Data()
- Content Actions: agentic.prompt/task/flow/persona callable via IPC
- Drive endpoints: forge + brain registered with tokens
- Drive REST helpers: DriveGet/DrivePost/DriveDo for Drive-aware HTTP
- HandleIPCEvents: auto-discovered by WithService (no manual wiring)
- Entitlement: frozen-queue gate on write Actions
- CLI dispatch: workspace dispatch wired to real dispatch method
- CLI: --quiet/-q and --debug/-d global flags
- CLI: banner, version, check (with service/action/command counts), env
- main.go: minimal — 5 services + c.Run(), no os import
- cmd tests: 84.2% coverage (was 0%)

Co-Authored-By: Virgil <virgil@lethean.io>
2026-03-26 06:38:02 +00:00

285 lines
8.7 KiB
Go

// SPDX-License-Identifier: EUPL-1.2
package agentic
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
core "dappco.re/go/core"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// --- mcpInitialize ---
func TestRemoteclient_McpInitialize_Good(t *testing.T) {
callCount := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
callCount++
assert.Equal(t, "POST", r.Method)
assert.Equal(t, "application/json", r.Header.Get("Content-Type"))
assert.Equal(t, "Bearer test-token", r.Header.Get("Authorization"))
if callCount == 1 {
// Initialize request
var body map[string]any
bodyStr := core.ReadAll(r.Body)
core.JSONUnmarshalString(bodyStr.Value.(string), &body)
assert.Equal(t, "initialize", body["method"])
w.Header().Set("Mcp-Session-Id", "session-abc")
w.Header().Set("Content-Type", "text/event-stream")
fmt.Fprintf(w, "data: {\"result\":{}}\n\n")
} else {
// Initialized notification
w.WriteHeader(200)
}
}))
t.Cleanup(srv.Close)
sessionID, err := mcpInitialize(context.Background(), srv.URL, "test-token")
require.NoError(t, err)
assert.Equal(t, "session-abc", sessionID)
assert.Equal(t, 2, callCount, "should make init + notification requests")
}
func TestRemoteclient_McpInitialize_Bad_ServerError(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(500)
}))
t.Cleanup(srv.Close)
_, err := mcpInitialize(context.Background(), srv.URL, "")
assert.Error(t, err)
assert.Contains(t, err.Error(), "HTTP 500")
}
func TestRemoteclient_McpInitialize_Bad_Unreachable(t *testing.T) {
_, err := mcpInitialize(context.Background(), "http://127.0.0.1:1", "")
assert.Error(t, err)
assert.Contains(t, err.Error(), "request failed")
}
// --- mcpCall ---
func TestRemoteclient_McpCall_Good(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "Bearer mytoken", r.Header.Get("Authorization"))
assert.Equal(t, "sess-123", r.Header.Get("Mcp-Session-Id"))
w.Header().Set("Content-Type", "text/event-stream")
fmt.Fprintf(w, "event: message\ndata: {\"result\":{\"content\":[{\"text\":\"hello\"}]}}\n\n")
}))
t.Cleanup(srv.Close)
body := []byte(`{"jsonrpc":"2.0","id":1,"method":"tools/call"}`)
result, err := mcpCall(context.Background(), srv.URL, "mytoken", "sess-123", body)
require.NoError(t, err)
assert.Contains(t, string(result), "hello")
}
func TestRemoteclient_McpCall_Bad_HTTP500(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(500)
}))
t.Cleanup(srv.Close)
_, err := mcpCall(context.Background(), srv.URL, "", "", nil)
assert.Error(t, err)
assert.Contains(t, err.Error(), "HTTP 500")
}
func TestRemoteclient_McpCall_Bad_NoSSEData(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
fmt.Fprintf(w, "event: ping\n\n") // No data: line
}))
t.Cleanup(srv.Close)
_, err := mcpCall(context.Background(), srv.URL, "", "", nil)
assert.Error(t, err)
assert.Contains(t, err.Error(), "no data")
}
// --- setHeaders ---
func TestRemoteclient_SetHeaders_Good_All(t *testing.T) {
req, _ := http.NewRequest("POST", "http://example.com", nil)
mcpHeaders(req, "my-token", "my-session")
assert.Equal(t, "application/json", req.Header.Get("Content-Type"))
assert.Equal(t, "application/json, text/event-stream", req.Header.Get("Accept"))
assert.Equal(t, "Bearer my-token", req.Header.Get("Authorization"))
assert.Equal(t, "my-session", req.Header.Get("Mcp-Session-Id"))
}
func TestRemoteclient_SetHeaders_Good_NoToken(t *testing.T) {
req, _ := http.NewRequest("POST", "http://example.com", nil)
mcpHeaders(req, "", "")
assert.Empty(t, req.Header.Get("Authorization"))
assert.Empty(t, req.Header.Get("Mcp-Session-Id"))
}
// --- setHeaders Bad ---
func TestRemoteclient_SetHeaders_Bad(t *testing.T) {
// Both token and session empty — only Content-Type and Accept are set
req, _ := http.NewRequest("POST", "http://example.com", nil)
mcpHeaders(req, "", "")
assert.Equal(t, "application/json", req.Header.Get("Content-Type"))
assert.Equal(t, "application/json, text/event-stream", req.Header.Get("Accept"))
assert.Empty(t, req.Header.Get("Authorization"), "no auth header when token is empty")
assert.Empty(t, req.Header.Get("Mcp-Session-Id"), "no session header when session is empty")
}
// --- readSSEData ---
func TestRemoteclient_ReadSSEData_Good(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
fmt.Fprintf(w, "event: message\ndata: {\"key\":\"value\"}\n\n")
}))
t.Cleanup(srv.Close)
resp, err := http.Get(srv.URL)
require.NoError(t, err)
defer resp.Body.Close()
data, err := readSSEData(resp)
require.NoError(t, err)
assert.Equal(t, `{"key":"value"}`, string(data))
}
func TestRemoteclient_ReadSSEData_Bad_NoData(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "event: ping\n\n")
}))
t.Cleanup(srv.Close)
resp, err := http.Get(srv.URL)
require.NoError(t, err)
defer resp.Body.Close()
_, err = readSSEData(resp)
assert.Error(t, err)
assert.Contains(t, err.Error(), "no data")
}
// --- drainSSE ---
func TestRemoteclient_DrainSSE_Good(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "data: line1\ndata: line2\n\n")
}))
t.Cleanup(srv.Close)
resp, err := http.Get(srv.URL)
require.NoError(t, err)
defer resp.Body.Close()
// Should not panic
drainSSE(resp)
}
// --- McpInitialize Ugly ---
func TestRemoteclient_McpInitialize_Ugly_NonJSONSSE(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Mcp-Session-Id", "sess-ugly")
w.Header().Set("Content-Type", "text/event-stream")
// Return non-JSON in SSE data line
fmt.Fprintf(w, "data: this is not json at all\n\n")
}))
t.Cleanup(srv.Close)
// mcpInitialize drains the SSE body but doesn't parse it — should succeed
sessionID, err := mcpInitialize(context.Background(), srv.URL, "tok")
require.NoError(t, err)
assert.Equal(t, "sess-ugly", sessionID)
}
// --- McpCall Ugly ---
func TestRemoteclient_McpCall_Ugly_EmptyResponseBody(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
// Write nothing — empty body
}))
t.Cleanup(srv.Close)
_, err := mcpCall(context.Background(), srv.URL, "", "", nil)
assert.Error(t, err)
assert.Contains(t, err.Error(), "no data")
}
// --- ReadSSEData Ugly ---
func TestRemoteclient_ReadSSEData_Ugly_OnlyEventLines(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
// Only event: lines, no data: lines
fmt.Fprintf(w, "event: message\nevent: done\n\n")
}))
t.Cleanup(srv.Close)
resp, err := http.Get(srv.URL)
require.NoError(t, err)
defer resp.Body.Close()
_, err = readSSEData(resp)
assert.Error(t, err)
assert.Contains(t, err.Error(), "no data")
}
// --- SetHeaders Ugly ---
func TestRemoteclient_SetHeaders_Ugly_VeryLongToken(t *testing.T) {
req, _ := http.NewRequest("POST", "http://example.com", nil)
longToken := strings.Repeat("a", 10000)
mcpHeaders(req, longToken, "sess-123")
assert.Equal(t, "Bearer "+longToken, req.Header.Get("Authorization"))
assert.Equal(t, "sess-123", req.Header.Get("Mcp-Session-Id"))
assert.Equal(t, "application/json", req.Header.Get("Content-Type"))
}
// --- DrainSSE Bad/Ugly ---
func TestRemoteclient_DrainSSE_Bad_EmptyBody(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Write nothing — empty body
}))
t.Cleanup(srv.Close)
resp, err := http.Get(srv.URL)
require.NoError(t, err)
defer resp.Body.Close()
// Should not panic on empty body
assert.NotPanics(t, func() { drainSSE(resp) })
}
func TestRemoteclient_DrainSSE_Ugly_VeryLargeResponse(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Write many SSE lines
for i := 0; i < 1000; i++ {
fmt.Fprintf(w, "data: line-%d padding-text-to-make-it-bigger-and-test-scanner-handling\n", i)
}
fmt.Fprintf(w, "\n")
}))
t.Cleanup(srv.Close)
resp, err := http.Get(srv.URL)
require.NoError(t, err)
defer resp.Body.Close()
// Should drain all lines without panic
assert.NotPanics(t, func() { drainSSE(resp) })
}