summaryrefslogtreecommitdiff
path: root/internal/api/server_test.go
blob: c3b77ae97a8f588f092eb18aa738301f699c04a9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
package api

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"testing"

	"context"

	"github.com/claudomator/claudomator/internal/executor"
	"github.com/claudomator/claudomator/internal/storage"
	"github.com/claudomator/claudomator/internal/task"
)

func testServer(t *testing.T) (*Server, *storage.DB) {
	t.Helper()
	dbPath := filepath.Join(t.TempDir(), "test.db")
	store, err := storage.Open(dbPath)
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { store.Close() })

	logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
	runner := &mockRunner{}
	pool := executor.NewPool(2, runner, store, logger)
	srv := NewServer(store, pool, logger)
	return srv, store
}

type mockRunner struct{}

func (m *mockRunner) Run(_ context.Context, _ *task.Task, _ *storage.Execution) error {
	return nil
}

func TestHealthEndpoint(t *testing.T) {
	srv, _ := testServer(t)
	req := httptest.NewRequest("GET", "/api/health", nil)
	w := httptest.NewRecorder()

	srv.Handler().ServeHTTP(w, req)

	if w.Code != http.StatusOK {
		t.Errorf("status: want 200, got %d", w.Code)
	}
	var body map[string]string
	json.NewDecoder(w.Body).Decode(&body)
	if body["status"] != "ok" {
		t.Errorf("want status=ok, got %v", body)
	}
}

func TestCreateTask_Success(t *testing.T) {
	srv, _ := testServer(t)

	payload := `{
		"name": "API Task",
		"description": "Created via API",
		"claude": {
			"instructions": "do the thing",
			"model": "sonnet"
		},
		"timeout": "5m",
		"tags": ["api"]
	}`
	req := httptest.NewRequest("POST", "/api/tasks", bytes.NewBufferString(payload))
	req.Header.Set("Content-Type", "application/json")
	w := httptest.NewRecorder()

	srv.Handler().ServeHTTP(w, req)

	if w.Code != http.StatusCreated {
		t.Fatalf("status: want 201, got %d; body: %s", w.Code, w.Body.String())
	}

	var created task.Task
	json.NewDecoder(w.Body).Decode(&created)
	if created.Name != "API Task" {
		t.Errorf("name: want 'API Task', got %q", created.Name)
	}
	if created.ID == "" {
		t.Error("expected auto-generated ID")
	}
}

func TestCreateTask_InvalidJSON(t *testing.T) {
	srv, _ := testServer(t)

	req := httptest.NewRequest("POST", "/api/tasks", bytes.NewBufferString("{bad json"))
	w := httptest.NewRecorder()
	srv.Handler().ServeHTTP(w, req)

	if w.Code != http.StatusBadRequest {
		t.Errorf("status: want 400, got %d", w.Code)
	}
}

func TestCreateTask_ValidationFailure(t *testing.T) {
	srv, _ := testServer(t)

	payload := `{"name": "", "claude": {"instructions": ""}}`
	req := httptest.NewRequest("POST", "/api/tasks", bytes.NewBufferString(payload))
	w := httptest.NewRecorder()
	srv.Handler().ServeHTTP(w, req)

	if w.Code != http.StatusBadRequest {
		t.Errorf("status: want 400, got %d", w.Code)
	}
}

func TestListTasks_Empty(t *testing.T) {
	srv, _ := testServer(t)

	req := httptest.NewRequest("GET", "/api/tasks", nil)
	w := httptest.NewRecorder()
	srv.Handler().ServeHTTP(w, req)

	if w.Code != http.StatusOK {
		t.Errorf("status: want 200, got %d", w.Code)
	}

	var tasks []task.Task
	json.NewDecoder(w.Body).Decode(&tasks)
	if len(tasks) != 0 {
		t.Errorf("want 0 tasks, got %d", len(tasks))
	}
}

func TestGetTask_NotFound(t *testing.T) {
	srv, _ := testServer(t)

	req := httptest.NewRequest("GET", "/api/tasks/nonexistent", nil)
	w := httptest.NewRecorder()
	srv.Handler().ServeHTTP(w, req)

	if w.Code != http.StatusNotFound {
		t.Errorf("status: want 404, got %d", w.Code)
	}
}

func TestListTasks_WithTasks(t *testing.T) {
	srv, store := testServer(t)

	// Create tasks directly in store.
	for i := 0; i < 3; i++ {
		tk := &task.Task{
			ID: fmt.Sprintf("lt-%d", i), Name: fmt.Sprintf("T%d", i),
			Claude: task.ClaudeConfig{Instructions: "x"}, Priority: task.PriorityNormal,
			Retry: task.RetryConfig{MaxAttempts: 1, Backoff: "linear"},
			Tags: []string{}, DependsOn: []string{}, State: task.StatePending,
		}
		store.CreateTask(tk)
	}

	req := httptest.NewRequest("GET", "/api/tasks", nil)
	w := httptest.NewRecorder()
	srv.Handler().ServeHTTP(w, req)

	var tasks []task.Task
	json.NewDecoder(w.Body).Decode(&tasks)
	if len(tasks) != 3 {
		t.Errorf("want 3 tasks, got %d", len(tasks))
	}
}

func TestCORS_Headers(t *testing.T) {
	srv, _ := testServer(t)

	req := httptest.NewRequest("OPTIONS", "/api/tasks", nil)
	w := httptest.NewRecorder()
	srv.Handler().ServeHTTP(w, req)

	if w.Header().Get("Access-Control-Allow-Origin") != "*" {
		t.Error("missing CORS origin header")
	}
	if w.Code != http.StatusOK {
		t.Errorf("OPTIONS status: want 200, got %d", w.Code)
	}
}