-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools_graph_test.go
More file actions
375 lines (343 loc) · 11.6 KB
/
Copy pathtools_graph_test.go
File metadata and controls
375 lines (343 loc) · 11.6 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
364
365
366
367
368
369
370
371
372
373
374
375
package mcp_test
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"reflect"
"sort"
"strings"
"testing"
"github.com/randomcodespace/codeiq/internal/graph"
"github.com/randomcodespace/codeiq/internal/mcp"
"github.com/randomcodespace/codeiq/internal/model"
"github.com/randomcodespace/codeiq/internal/query"
)
// fixtureStore opens a fresh Kuzu store under t.TempDir, applies the
// schema, and seeds a 3-node / 2-edge fixture: serviceA --CALLS--> b,
// serviceA --DEPENDS_ON--> c. Returns the store and a teardown.
func fixtureStore(t *testing.T) *graph.Store {
t.Helper()
dir := filepath.Join(t.TempDir(), "fx.kuzu")
s, err := graph.Open(dir)
if err != nil {
t.Fatalf("Open: %v", err)
}
t.Cleanup(func() { _ = s.Close() })
if err := s.ApplySchema(); err != nil {
t.Fatalf("ApplySchema: %v", err)
}
// Seed nodes + edges.
stmts := []struct {
q string
p map[string]any
}{
{`CREATE (:CodeNode {id: 'svc:a', kind: 'service', label: 'serviceA', label_lower: 'servicea', layer: 'backend'})`, nil},
{`CREATE (:CodeNode {id: 'cls:b', kind: 'class', label: 'B', label_lower: 'b', layer: 'backend', file_path: 'src/B.java'})`, nil},
{`CREATE (:CodeNode {id: 'cls:c', kind: 'class', label: 'C', label_lower: 'c', layer: 'backend', file_path: 'src/C.java'})`, nil},
{`MATCH (a:CodeNode {id: 'svc:a'}), (b:CodeNode {id: 'cls:b'}) CREATE (a)-[:CALLS]->(b)`, nil},
{`MATCH (a:CodeNode {id: 'svc:a'}), (c:CodeNode {id: 'cls:c'}) CREATE (a)-[:DEPENDS_ON]->(c)`, nil},
{`MATCH (a:CodeNode {id: 'svc:a'}), (b:CodeNode {id: 'cls:b'}) CREATE (a)-[:CONTAINS]->(b)`, nil},
{`MATCH (a:CodeNode {id: 'svc:a'}), (c:CodeNode {id: 'cls:c'}) CREATE (a)-[:CONTAINS]->(c)`, nil},
}
for _, st := range stmts {
if st.p == nil {
if _, err := s.Cypher(st.q); err != nil {
t.Fatalf("seed %q: %v", st.q, err)
}
}
}
return s
}
func fixtureDeps(t *testing.T) *mcp.Deps {
t.Helper()
store := fixtureStore(t)
stats := query.NewStatsServiceFromStore(func() ([]*model.CodeNode, []*model.CodeEdge, error) {
nodes, err := store.LoadAllNodes()
if err != nil {
return nil, nil, err
}
edges, err := store.LoadAllEdges()
if err != nil {
return nil, nil, err
}
return nodes, edges, nil
})
return &mcp.Deps{
Store: store,
Query: query.NewService(store),
Stats: stats,
Topology: query.NewTopology(store),
MaxResults: 100,
MaxDepth: 5,
}
}
// callTool registers a single tool, then invokes it directly through the
// SDK in-memory pair. Returns the parsed JSON text body.
func callTool(t *testing.T, d *mcp.Deps, name string, args map[string]any) map[string]any {
t.Helper()
srv, _ := mcp.NewServer(mcp.ServerOptions{Name: "x", Version: "0"})
if err := mcp.RegisterGraph(srv, d); err != nil {
t.Fatalf("RegisterGraph: %v", err)
}
sess, cleanup := connectInMemoryTest(t, srv)
defer cleanup()
ctx, cancel := contextDeadline(t)
defer cancel()
res, err := sess.CallTool(ctx, sdkCallToolParams(name, args))
if err != nil {
t.Fatalf("CallTool(%s): %v", name, err)
}
if len(res.Content) == 0 {
t.Fatalf("%s returned empty content", name)
}
tc, ok := res.Content[0].(textContent)
if !ok {
t.Fatalf("%s content type = %T", name, res.Content[0])
}
var out map[string]any
if err := json.Unmarshal([]byte(tc.Text), &out); err != nil {
t.Fatalf("%s unmarshal: %v\nbody=%s", name, err, tc.Text)
}
return out
}
func TestRegisterGraphRegistersAllTwentyTools(t *testing.T) {
srv, _ := mcp.NewServer(mcp.ServerOptions{Name: "x", Version: "0"})
if err := mcp.RegisterGraph(srv, &mcp.Deps{}); err != nil {
t.Fatalf("RegisterGraph: %v", err)
}
want := []string{
"get_stats", "get_detailed_stats", "query_nodes", "query_edges",
"get_node_neighbors", "get_ego_graph", "find_cycles", "find_shortest_path",
"find_consumers", "find_producers", "find_callers", "find_dependencies",
"find_dependents", "find_dead_code", "find_component_by_file",
"trace_impact", "find_related_endpoints", "search_graph",
"run_cypher", "read_file",
}
got := srv.Registry().Names()
sort.Strings(got)
sort.Strings(want)
if !reflect.DeepEqual(got, want) {
t.Fatalf("registered tools:\n got=%v\nwant=%v", got, want)
}
}
func TestRegisterGraphUserFacingRegistersTwoTools(t *testing.T) {
srv, _ := mcp.NewServer(mcp.ServerOptions{Name: "x", Version: "0"})
if err := mcp.RegisterGraphUserFacing(srv, &mcp.Deps{}); err != nil {
t.Fatalf("RegisterGraphUserFacing: %v", err)
}
want := []string{"read_file", "run_cypher"}
got := srv.Registry().Names()
sort.Strings(got)
if !reflect.DeepEqual(got, want) {
t.Fatalf("registered tools:\n got=%v\nwant=%v", got, want)
}
}
func TestGetStatsReturnsCounts(t *testing.T) {
d := fixtureDeps(t)
out := callTool(t, d, "get_stats", nil)
// The OrderedMap serializes to a JSON object with at minimum a
// `graph` (or top-level total_nodes / total_edges) key.
if len(out) == 0 {
t.Fatalf("get_stats returned empty object: %v", out)
}
}
func TestQueryNodesByKind(t *testing.T) {
d := fixtureDeps(t)
out := callTool(t, d, "query_nodes", map[string]any{"kind": "class", "limit": 10})
cnt, _ := out["count"].(float64)
if cnt != 2 {
t.Fatalf("query_nodes class count = %v, want 2 (cls:b, cls:c). out=%v", cnt, out)
}
}
func TestQueryNodesLimitCapped(t *testing.T) {
d := fixtureDeps(t)
d.MaxResults = 1
out := callTool(t, d, "query_nodes", map[string]any{"kind": "class", "limit": 999})
lim, _ := out["limit"].(float64)
if lim != 1 {
t.Fatalf("limit capped to %v, want 1", lim)
}
}
func TestQueryEdgesByKind(t *testing.T) {
d := fixtureDeps(t)
out := callTool(t, d, "query_edges", map[string]any{"kind": "CALLS", "limit": 10})
cnt, _ := out["count"].(float64)
if cnt != 1 {
t.Fatalf("query_edges CALLS count = %v, want 1", cnt)
}
}
func TestGetNodeNeighborsBoth(t *testing.T) {
d := fixtureDeps(t)
out := callTool(t, d, "get_node_neighbors", map[string]any{"node_id": "svc:a"})
if _, ok := out["incoming"]; !ok {
t.Fatalf("missing incoming in response: %v", out)
}
if _, ok := out["outgoing"]; !ok {
t.Fatalf("missing outgoing in response: %v", out)
}
}
func TestGetNodeNeighborsMissingNodeIDIsInvalidInput(t *testing.T) {
d := fixtureDeps(t)
out := callTool(t, d, "get_node_neighbors", nil)
if out["code"] != mcp.CodeInvalidInput {
t.Fatalf("code = %v, want INVALID_INPUT. body=%v", out["code"], out)
}
}
func TestGetEgoGraphRadiusCapped(t *testing.T) {
d := fixtureDeps(t)
d.MaxDepth = 1
out := callTool(t, d, "get_ego_graph", map[string]any{"center": "svc:a", "radius": 999})
r, _ := out["radius"].(float64)
if r != 1 {
t.Fatalf("radius capped to %v, want 1. body=%v", r, out)
}
}
func TestFindCyclesEmptyOnAcyclic(t *testing.T) {
d := fixtureDeps(t)
out := callTool(t, d, "find_cycles", nil)
cnt, _ := out["count"].(float64)
if cnt != 0 {
t.Fatalf("cycles in acyclic fixture = %v, want 0", cnt)
}
}
func TestFindShortestPathConnected(t *testing.T) {
d := fixtureDeps(t)
out := callTool(t, d, "find_shortest_path", map[string]any{"source": "svc:a", "target": "cls:b"})
path, ok := out["path"].([]any)
if !ok || len(path) < 2 {
t.Fatalf("path missing or too short: %v", out)
}
}
func TestFindShortestPathDisconnected(t *testing.T) {
d := fixtureDeps(t)
out := callTool(t, d, "find_shortest_path", map[string]any{"source": "cls:b", "target": "cls:c"})
if _, ok := out["error"]; !ok {
// Even when no direct path exists, the helpers may build a 2-hop
// indirection through serviceA via CONTAINS. Either is acceptable;
// assert one of the two valid shapes.
if _, hasPath := out["path"]; !hasPath {
t.Fatalf("expected error or path key, got %v", out)
}
}
}
func TestFindCallersTargetIDRequired(t *testing.T) {
d := fixtureDeps(t)
out := callTool(t, d, "find_callers", nil)
if out["code"] != mcp.CodeInvalidInput {
t.Fatalf("code = %v, want INVALID_INPUT", out["code"])
}
}
func TestFindCallersReturnsList(t *testing.T) {
d := fixtureDeps(t)
out := callTool(t, d, "find_callers", map[string]any{"target_id": "cls:b"})
if _, ok := out["callers"]; !ok {
t.Fatalf("missing callers key: %v", out)
}
}
func TestFindDeadCodeFiltersEntryPoints(t *testing.T) {
d := fixtureDeps(t)
// cls:b has incoming CALLS from svc:a — should not be dead.
out := callTool(t, d, "find_dead_code", nil)
cnt, _ := out["count"].(float64)
dead, _ := out["dead_code"].([]any)
if cnt != float64(len(dead)) {
t.Fatalf("count/list mismatch: %v vs %d", cnt, len(dead))
}
}
func TestRunCypherReadOnly(t *testing.T) {
d := fixtureDeps(t)
out := callTool(t, d, "run_cypher", map[string]any{"query": "MATCH (n:CodeNode) RETURN n.id AS id ORDER BY id"})
rows, _ := out["rows"].([]any)
if len(rows) != 3 {
t.Fatalf("run_cypher rows = %d, want 3", len(rows))
}
}
func TestRunCypherBlocksMutation(t *testing.T) {
d := fixtureDeps(t)
out := callTool(t, d, "run_cypher", map[string]any{"query": "CREATE (:X)"})
if _, ok := out["error"]; !ok {
t.Fatalf("expected error envelope for mutation, got %v", out)
}
}
func TestRunCypherTruncates(t *testing.T) {
d := fixtureDeps(t)
d.MaxResults = 1
out := callTool(t, d, "run_cypher", map[string]any{"query": "MATCH (n:CodeNode) RETURN n.id AS id"})
if trunc, _ := out["truncated"].(bool); !trunc {
t.Fatalf("expected truncated=true, got %v", out)
}
mr, _ := out["max_results"].(float64)
if mr != 1 {
t.Fatalf("max_results = %v, want 1", mr)
}
}
func TestSearchGraphFindsLabel(t *testing.T) {
d := fixtureDeps(t)
out := callTool(t, d, "search_graph", map[string]any{"query": "service"})
cnt, _ := out["count"].(float64)
if cnt < 1 {
t.Fatalf("search 'service' count = %v, want >= 1", cnt)
}
}
func TestFindComponentByFile(t *testing.T) {
d := fixtureDeps(t)
out := callTool(t, d, "find_component_by_file", map[string]any{"file_path": "src/B.java"})
cnt, _ := out["count"].(float64)
if cnt != 1 {
t.Fatalf("nodes for src/B.java = %v, want 1. body=%v", cnt, out)
}
}
func TestTraceImpactDepthCapped(t *testing.T) {
d := fixtureDeps(t)
d.MaxDepth = 1
out := callTool(t, d, "trace_impact", map[string]any{"node_id": "svc:a", "depth": 999})
// BlastRadius returns an OrderedMap; we mostly assert it doesn't error
// out and has a depth-capped shape (the capped depth shows up as a
// `depth` field on the response).
if _, ok := out["depth"]; !ok {
// Tolerate alternate shape — BlastRadius emits {center, layers...}
if len(out) == 0 {
t.Fatalf("trace_impact empty response: %v", out)
}
}
}
func TestFindRelatedEndpointsRequiresIdentifier(t *testing.T) {
d := fixtureDeps(t)
out := callTool(t, d, "find_related_endpoints", nil)
if out["code"] != mcp.CodeInvalidInput {
t.Fatalf("code = %v, want INVALID_INPUT", out["code"])
}
}
func TestReadFileToolDelegates(t *testing.T) {
d := fixtureDeps(t)
root := t.TempDir()
d.RootPath = root
if err := os.WriteFile(filepath.Join(root, "x.txt"), []byte("hi\n"), 0o644); err != nil {
t.Fatalf("write: %v", err)
}
out := callTool(t, d, "read_file", map[string]any{"file_path": "x.txt"})
c, _ := out["content"].(string)
if c != "hi\n" {
t.Fatalf("content = %q, want hi\\n. out=%v", c, out)
}
}
func TestReadFileToolMissingPath(t *testing.T) {
d := fixtureDeps(t)
d.RootPath = t.TempDir()
out := callTool(t, d, "read_file", map[string]any{"file_path": "nope.txt"})
if out["code"] != mcp.CodeFileReadFailed {
t.Fatalf("code = %v, want FILE_READ_FAILED. body=%v", out["code"], out)
}
}
func TestReadFileToolDisabledWithoutRoot(t *testing.T) {
d := fixtureDeps(t)
d.RootPath = ""
out := callTool(t, d, "read_file", map[string]any{"file_path": "x.txt"})
if out["code"] != mcp.CodeInternalError {
t.Fatalf("code = %v, want INTERNAL_ERROR", out["code"])
}
if !strings.Contains(fmt.Sprint(out["message"]), "root") {
t.Fatalf("message = %v, want root substring", out["message"])
}
}