-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintegration_api_test.go
More file actions
363 lines (324 loc) · 9.31 KB
/
Copy pathintegration_api_test.go
File metadata and controls
363 lines (324 loc) · 9.31 KB
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
//go:build integration
//nolint:noctx
package yaad_test
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/GrayCodeAI/yaad/config"
"github.com/GrayCodeAI/yaad/engine"
"github.com/GrayCodeAI/yaad/internal/server"
yaadtls "github.com/GrayCodeAI/yaad/internal/tls"
"github.com/GrayCodeAI/yaad/profile"
"github.com/GrayCodeAI/yaad/storage"
"github.com/GrayCodeAI/yaad/utils"
)
// This file is part of the yaad_test integration suite. It holds the utils,
// edge-case, profile-merge, TLS, config, storage, REST API, and concurrency
// tests moved verbatim out of integration_test.go for readability; behavior
// is unchanged.
func TestUtilsShortID(t *testing.T) {
cases := []struct{ input, expected string }{
{"abcdefghijklmnop", "abcdefgh"},
{"short", "short"},
{"12345678", "12345678"},
{"", ""},
{"ab", "ab"},
}
for _, c := range cases {
got := utils.ShortID(c.input)
if got != c.expected {
t.Errorf("ShortID(%q) = %q, want %q", c.input, got, c.expected)
}
}
}
func TestEdgeCaseEmptyRecall(t *testing.T) {
eng, cleanup := setup(t)
defer cleanup()
// Recall on empty DB should return empty, not error
result, err := eng.Recall(context.Background(), engine.RecallOpts{Query: "nonexistent", Limit: 5})
if err != nil {
t.Fatal(err)
}
if len(result.Nodes) != 0 {
t.Errorf("empty recall: expected 0 nodes, got %d", len(result.Nodes))
}
}
func TestEdgeCaseContextEmpty(t *testing.T) {
eng, cleanup := setup(t)
defer cleanup()
// Context on empty DB should return empty, not error
result, err := eng.Context(context.Background(), "")
if err != nil {
t.Fatal(err)
}
if result == nil {
t.Error("context: should return empty result, not nil")
}
}
func TestEdgeCaseForgetNonexistent(t *testing.T) {
eng, cleanup := setup(t)
defer cleanup()
// Forget nonexistent node should error gracefully
err := eng.Forget(context.Background(), "nonexistent-id-12345678")
if err == nil {
t.Error("forget: should error on nonexistent node")
}
}
func TestProfileMerge(t *testing.T) {
a := &profile.Profile{
Project: "test",
Static: []string{"Use jose", "Use NATS"},
Dynamic: []string{"[task] rate limiting"},
Stack: []string{"TypeScript", "NATS"},
}
b := &profile.Profile{
Static: []string{"Prefer tabs", "Use jose"}, // "Use jose" is duplicate
Dynamic: []string{"[bug] auth race"},
Stack: []string{"PostgreSQL", "NATS"}, // "NATS" is duplicate
}
merged := profile.Merge(a, b)
// Static should be deduped
if len(merged.Static) != 3 { // jose, NATS, tabs
t.Errorf("merge: expected 3 static, got %d: %v", len(merged.Static), merged.Static)
}
// Stack should be deduped
if len(merged.Stack) != 3 { // TypeScript, NATS, PostgreSQL
t.Errorf("merge: expected 3 stack, got %d: %v", len(merged.Stack), merged.Stack)
}
// Dynamic should be combined (not deduped)
if len(merged.Dynamic) != 2 {
t.Errorf("merge: expected 2 dynamic, got %d", len(merged.Dynamic))
}
}
func TestMultipleRememberAndRecall(t *testing.T) {
eng, cleanup := setup(t)
defer cleanup()
// Store 20 memories of different types
types := []string{"convention", "decision", "bug", "spec", "task"}
for i := 0; i < 20; i++ {
eng.Remember(context.Background(), engine.RememberInput{
Type: types[i%len(types)],
Content: fmt.Sprintf("Memory item %d about topic %d", i, i%5),
Scope: "project",
})
}
// Recall should find results
result, err := eng.Recall(context.Background(), engine.RecallOpts{Query: "topic", Limit: 10})
if err != nil {
t.Fatal(err)
}
if len(result.Nodes) == 0 {
t.Error("bulk recall: expected nodes")
}
t.Logf("Stored 20, recalled %d nodes", len(result.Nodes))
// Status should show correct counts
st, _ := eng.Status(context.Background(), "")
if st.Nodes < 20 {
t.Errorf("status: expected ≥20 nodes, got %d", st.Nodes)
}
}
func TestTLSCertGeneration(t *testing.T) {
dir := t.TempDir()
cfg := yaadtls.Config{Enabled: true}
tlsCfg, err := yaadtls.TLSConfig(cfg, dir)
if err != nil {
t.Fatal(err)
}
if tlsCfg == nil {
t.Fatal("tls: nil config returned")
}
if len(tlsCfg.Certificates) == 0 {
t.Error("tls: no certificates generated")
}
// Verify cert files were created
if _, err := os.Stat(filepath.Join(dir, "cert.pem")); err != nil {
t.Error("tls: cert.pem not created")
}
if _, err := os.Stat(filepath.Join(dir, "key.pem")); err != nil {
t.Error("tls: key.pem not created")
}
}
func TestConfigDefaults(t *testing.T) {
cfg := config.Default()
if cfg.Server.Port != 3456 {
t.Errorf("config: expected port 3456, got %d", cfg.Server.Port)
}
if cfg.Decay.HalfLifeDays != 30 {
t.Errorf("config: expected half_life 30, got %d", cfg.Decay.HalfLifeDays)
}
}
func TestStorageCreateAndQuery(t *testing.T) {
dir := t.TempDir()
store, err := storage.NewStore(filepath.Join(dir, "test.db"))
if err != nil {
t.Fatal(err)
}
defer func() { store.Close() }()
ctx := context.Background()
// Create node
node := &storage.Node{
ID: "test-node-1", Type: "convention", Content: "Test content",
ContentHash: "hash1", Scope: "project", Tier: 1, Confidence: 1.0, Version: 1,
}
if err := store.CreateNode(ctx, node); err != nil {
t.Fatal(err)
}
// Get node
got, err := store.GetNode(ctx, "test-node-1")
if err != nil {
t.Fatal(err)
}
if got.Content != "Test content" {
t.Errorf("storage: expected 'Test content', got '%s'", got.Content)
}
// Create edge
edge := &storage.Edge{
ID: "test-edge-1", FromID: "test-node-1", ToID: "test-node-1",
Type: "relates_to", Acyclic: false, Weight: 1.0,
}
if err := store.CreateEdge(ctx, edge); err != nil {
t.Fatal(err)
}
// Get neighbors
neighbors, err := store.GetNeighbors(ctx, "test-node-1")
if err != nil {
t.Fatal(err)
}
if len(neighbors) == 0 {
t.Error("storage: expected neighbors")
}
// Version history
if err := store.SaveVersion(ctx, "test-node-1", "old content", "test", "test update"); err != nil {
t.Fatal(err)
}
versions, err := store.GetVersions(ctx, "test-node-1")
if err != nil {
t.Fatal(err)
}
if len(versions) == 0 {
t.Error("storage: expected version history")
}
}
func TestRESTAPI(t *testing.T) {
eng, cleanup := setup(t)
defer cleanup()
mux := http.NewServeMux()
rest := server.NewRESTServer(eng, "")
rest.RegisterRoutes(mux)
ts := httptest.NewServer(mux)
defer ts.Close()
// POST /yaad/remember
body, _ := json.Marshal(engine.RememberInput{
Type: "convention", Content: "Always use TypeScript strict mode", Scope: "project",
})
resp, err := http.Post(ts.URL+"/yaad/remember", "application/json", bytes.NewReader(body))
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != 201 {
t.Errorf("remember: expected 201, got %d", resp.StatusCode)
}
var node storage.Node
json.NewDecoder(resp.Body).Decode(&node)
resp.Body.Close()
if node.ID == "" {
t.Error("remember: empty node ID")
}
// POST /yaad/recall
body, _ = json.Marshal(engine.RecallOpts{Query: "TypeScript", Limit: 5})
resp, err = http.Post(ts.URL+"/yaad/recall", "application/json", bytes.NewReader(body))
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != 200 {
t.Errorf("recall: expected 200, got %d", resp.StatusCode)
}
var result engine.RecallResult
json.NewDecoder(resp.Body).Decode(&result)
resp.Body.Close()
if len(result.Nodes) == 0 {
t.Error("recall: expected nodes, got none")
}
// GET /yaad/health
resp, _ = http.Get(ts.URL + "/yaad/health")
if resp.StatusCode != 200 {
t.Errorf("health: expected 200, got %d", resp.StatusCode)
}
resp.Body.Close()
// GET /yaad/context
resp, _ = http.Get(ts.URL + "/yaad/context")
if resp.StatusCode != 200 {
t.Errorf("context: expected 200, got %d", resp.StatusCode)
}
resp.Body.Close()
}
// TestConcurrentSQLiteAccess verifies that concurrent Remember and Recall operations
// against the real SQLite backend do not race or corrupt data.
func TestConcurrentSQLiteAccess(t *testing.T) {
eng, cleanup := setup(t)
defer cleanup()
var wg sync.WaitGroup
numWriters := 5
numReaders := 5
opsPerGoroutine := 10
// Writers
for i := 0; i < numWriters; i++ {
wg.Add(1)
go func(idx int) {
defer wg.Done()
for j := 0; j < opsPerGoroutine; j++ {
_, err := eng.Remember(context.Background(), engine.RememberInput{
Type: "convention",
Content: fmt.Sprintf("writer-%d-op-%d", idx, j),
Scope: "project",
Project: "concurrent-test",
})
if err != nil {
// Under CI load, occasional SQLITE_BUSY is expected even with
// _busy_timeout. Skip individual operations rather than failing.
if strings.Contains(err.Error(), "database is locked") {
time.Sleep(10 * time.Millisecond)
continue
}
t.Errorf("writer %d op %d failed: %v", idx, j, err)
}
}
}(i)
}
// Readers
for i := 0; i < numReaders; i++ {
wg.Add(1)
go func(idx int) {
defer wg.Done()
for j := 0; j < opsPerGoroutine; j++ {
_, err := eng.Recall(context.Background(), engine.RecallOpts{
Query: "writer",
Project: "concurrent-test",
Limit: 10,
})
if err != nil {
t.Errorf("reader %d op %d failed: %v", idx, j, err)
}
}
}(i)
}
wg.Wait()
st, err := eng.Status(context.Background(), "concurrent-test")
if err != nil {
t.Fatalf("status failed: %v", err)
}
expectedNodes := numWriters * opsPerGoroutine
if st.Nodes < expectedNodes {
t.Errorf("expected at least %d nodes, got %d", expectedNodes, st.Nodes)
}
}