package processapi import ( "context" "net/http" "net/http/httptest" "strings" "testing" "github.com/itworx/pulse/internal/auth" "github.com/itworx/pulse/internal/process" ) type provider struct{ value process.Snapshot } func (p provider) Snapshot(context.Context) (process.Snapshot, error) { return p.value, nil } func request(path string) *http.Request { r := httptest.NewRequest(http.MethodGet, path, nil) return r.WithContext(auth.WithPrincipal(r.Context(), auth.Principal{Subject: "viewer", Role: auth.RoleViewer})) } func TestHandlerIsReadOnlyAndBounded(t *testing.T) { response := httptest.NewRecorder() Handler{Provider: provider{value: process.Snapshot{ContractVersion: process.ContractVersion, Source: process.Source{ID: "agent-1", State: "healthy"}, Processes: []process.Process{{PID: 1, Name: "init", State: "running"}}, Total: 1}}}.ServeHTTP(response, request("/api/v1/processes?limit=1&sort=cpu")) if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), `"pid":1`) { t.Fatalf("status=%d body=%s", response.Code, response.Body.String()) } mutating := httptest.NewRecorder() Handler{}.ServeHTTP(mutating, httptest.NewRequest(http.MethodPost, "/api/v1/processes/1/kill", nil)) if mutating.Code != http.StatusNotFound { t.Fatalf("mutation route status=%d", mutating.Code) } } func TestHandlerRequiresAuthentication(t *testing.T) { response := httptest.NewRecorder() Handler{}.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/processes", nil)) if response.Code != http.StatusUnauthorized { t.Fatalf("status=%d", response.Code) } } func TestHandlerAppliesNameAndContainerFilters(t *testing.T) { snapshot := process.Snapshot{Source: process.Source{ID: "agent", State: "healthy"}, Processes: []process.Process{{PID: 1, Name: "api", ContainerName: "pulse"}, {PID: 2, Name: "postgres", ContainerName: "database"}}, Total: 2} response := httptest.NewRecorder() Handler{Provider: provider{value: snapshot}}.ServeHTTP(response, request("/api/v1/processes?limit=25&sort=cpu&q=api&container=pulse")) if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), `"name":"api"`) || !strings.Contains(response.Body.String(), `"total":1`) { t.Fatalf("status=%d body=%s", response.Code, response.Body.String()) } }