-
Notifications
You must be signed in to change notification settings - Fork 707
Expand file tree
/
Copy pathgraphTools.test.ts
More file actions
439 lines (353 loc) · 14.8 KB
/
graphTools.test.ts
File metadata and controls
439 lines (353 loc) · 14.8 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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
import { describe, it, expect, beforeAll, afterAll } from "vitest";
import { FalkorDB } from "falkordb";
import { getDefaultRepoHandler } from "./DefaultRepoHandler";
import { getGraphService } from "./graphTools";
import path from "path";
// Comprehensive test suite for all 8 fetchUsageCodeExamples scenarios using real data
const shouldRunGraphTests = process.env.RUN_GRAPH_TESTS === "1";
const describeMaybe = shouldRunGraphTests ? describe : describe.skip;
describeMaybe("fetchUsageCodeExamples - All 8 Scenarios with Real Data", () => {
let client: FalkorDB;
let graphService: any;
const realRepoData = {
owner: "FalkorDB",
repo: "GraphRAG-SDK",
host: "gitmcp.io",
urlType: "github" as const,
};
const testRepoData = {
owner: "testuser",
repo: "test-scenario-repo",
host: "gitmcp.io",
urlType: "github" as const,
};
const nonExistentRepoData = {
owner: "nonexistent",
repo: "fake-repo",
host: "gitmcp.io",
urlType: "github" as const,
};
beforeAll(async () => {
const host = process.env.FALKORDB_HOST || "127.0.0.1";
const port = parseInt(process.env.FALKORDB_PORT || "6379");
client = await FalkorDB.connect({
socket: { host, port },
});
graphService = getGraphService();
});
afterAll(async () => {
if (client) {
// Clean up any test graphs
try {
const graphs = await client.list();
const testGraphs = ["test-scenario-repo", "fake-repo"];
for (const graphName of testGraphs) {
if (graphs.includes(graphName)) {
const graph = client.selectGraph(graphName);
await graph.delete();
console.log(`Cleaned up test graph: ${graphName}`);
}
}
} catch (error) {
console.log("Test cleanup error (expected):", error);
}
await client.close();
}
});
describe("Scenario 1: Graph exists + Function found", () => {
it("should return actual code examples when function exists in real graph", async () => {
const graphExists = await graphService.checkGraphExists("GraphRAG-SDK");
if (!graphExists) {
console.log("⚠️ GraphRAG-SDK graph not found, skipping Scenario 1");
return;
}
const tools = getDefaultRepoHandler().getTools(realRepoData, {}, {});
const toolCb = tools.find((t) => t.name === "fetchUsageCodeExamples")?.cb;
if (!toolCb) {
throw new Error("fetchUsageCodeExamples tool not found");
}
const result = await toolCb({
functionName: "chat_session",
});
expect(result.content[0].text).toMatch(
/📋 Code Example Results for "chat_session" function/,
);
expect(result.content[0].text).toMatch(/Found \d+ function/);
expect(result.content[0].text).toMatch(/Code Example \d+:/);
console.log("✅ Scenario 1: Real code examples returned");
console.log(
"Sample response:",
result.content[0].text.substring(0, 300) + "...",
);
});
});
describe("Scenario 2: Graph exists + No results + Creation in progress", () => {
it("should show creation progress when function not found but creation ongoing", async () => {
const graphExists = await graphService.checkGraphExists("GraphRAG-SDK");
if (!graphExists) {
console.log("⚠️ GraphRAG-SDK graph not found, skipping Scenario 2");
return;
}
// Test with a function that definitely doesn't exist
const tools = getDefaultRepoHandler().getTools(realRepoData, {}, {});
const toolCb = tools.find((t) => t.name === "fetchUsageCodeExamples")?.cb;
if (!toolCb) {
throw new Error("fetchUsageCodeExamples tool not found");
}
// Manually set creation in progress to simulate this scenario
const repoKey = `${realRepoData.owner}/${realRepoData.repo}`;
graphService.setCreationLock(repoKey, true);
const result = await toolCb({
functionName: "definitely_nonexistent_function_12345",
});
// Clean up the lock
graphService.setCreationLock(repoKey, false);
// Should show either creation progress or no results found
const isCreationProgress = result.content[0].text.includes(
"Graph Creation Still In Progress",
);
const isNoResults = result.content[0].text.includes(
"No calling functions found",
);
expect(isCreationProgress || isNoResults).toBe(true);
console.log("✅ Scenario 2: Handled non-existent function properly");
});
});
describe("Scenario 3: Graph exists + No results + Creation complete", () => {
it("should show 'no functions found' when function doesn't exist", async () => {
const graphExists = await graphService.checkGraphExists("GraphRAG-SDK");
if (!graphExists) {
console.log("⚠️ GraphRAG-SDK graph not found, skipping Scenario 3");
return;
}
const tools = getDefaultRepoHandler().getTools(realRepoData, {}, {});
const toolCb = tools.find((t) => t.name === "fetchUsageCodeExamples")?.cb;
if (!toolCb) {
throw new Error("fetchUsageCodeExamples tool not found");
}
// Ensure no creation in progress
const repoKey = `${realRepoData.owner}/${realRepoData.repo}`;
graphService.setCreationLock(repoKey, false);
const result = await toolCb({
functionName: "absolutely_nonexistent_function_xyz_999",
});
expect(result.content[0].text).toMatch(
/🔍 No calling functions found|No function|not found/i,
);
console.log("✅ Scenario 3: No functions found message displayed");
});
});
describe("Scenario 4: Graph exists + Query timeout", () => {
it("should handle timeout gracefully with real database", async () => {
const graphExists = await graphService.checkGraphExists("GraphRAG-SDK");
if (!graphExists) {
console.log("⚠️ GraphRAG-SDK graph not found, skipping Scenario 4");
return;
}
const tools = getDefaultRepoHandler().getTools(realRepoData, {}, {});
const toolCb = tools.find((t) => t.name === "fetchUsageCodeExamples")?.cb;
if (!toolCb) {
throw new Error("fetchUsageCodeExamples tool not found");
}
// Test with a function that might cause complex queries
const start = Date.now();
const result = await toolCb({
functionName: "chat_session",
});
const duration = Date.now() - start;
// Should complete within reasonable time (< 10 seconds) or show timeout
if (duration > 10000) {
expect(result.content[0].text).toMatch(/timeout|taking too long/i);
console.log("✅ Scenario 4: Timeout handled gracefully");
} else {
console.log("✅ Scenario 4: Query completed within timeout period");
}
});
});
describe("Scenario 5: No graph + Creation in progress", () => {
it("should show creation progress for non-existent graph", async () => {
const repoKey = `${testRepoData.owner}/${testRepoData.repo}`;
// Ensure graph doesn't exist
const graphExists = await graphService.checkGraphExists(
testRepoData.repo,
);
expect(graphExists).toBe(false);
// Set creation in progress manually
graphService.setCreationLock(repoKey, true);
const tools = getDefaultRepoHandler().getTools(testRepoData, {}, {});
const toolCb = tools.find((t) => t.name === "fetchUsageCodeExamples")?.cb;
if (!toolCb) {
throw new Error("fetchUsageCodeExamples tool not found");
}
const result = await toolCb({
functionName: "test_function",
});
expect(result.content[0].text).toMatch(/🔄.*Graph Creation In Progress/);
expect(result.content[0].text).toMatch(/testuser\/test-scenario-repo/);
// Clean up
graphService.setCreationLock(repoKey, false);
console.log("✅ Scenario 5: Creation progress displayed");
});
});
describe("Scenario 6: No graph + First time (Start creation)", () => {
it("should initiate graph creation for new repository", async () => {
const repoKey = `${nonExistentRepoData.owner}/${nonExistentRepoData.repo}`;
// Clean up any existing state
graphService.setCreationLock(repoKey, false);
graphService.clearStaleLocks(repoKey);
// Ensure graph doesn't exist
const graphExists = await graphService.checkGraphExists(
nonExistentRepoData.repo,
);
expect(graphExists).toBe(false);
const tools = getDefaultRepoHandler().getTools(
nonExistentRepoData,
{},
{},
);
const toolCb = tools.find((t) => t.name === "fetchUsageCodeExamples")?.cb;
if (!toolCb) {
throw new Error("fetchUsageCodeExamples tool not found");
}
const result = await toolCb({
functionName: "test_function",
});
expect(result.content[0].text).toMatch(/🚀.*Starting Code Analysis/);
expect(result.content[0].text).toMatch(
/Graph creation has been initiated/,
);
expect(result.content[0].text).toMatch(/5-10 minutes/);
console.log("✅ Scenario 6: Graph creation initiated");
// Verify creation lock was set
const progress = graphService.getCreationProgress(repoKey);
expect(progress.inProgress).toBe(true);
// Clean up
graphService.setCreationLock(repoKey, false);
});
});
describe("Scenario 7: GitHub API timeout during code fetching", () => {
it("should handle GitHub API timeouts gracefully", async () => {
const graphExists = await graphService.checkGraphExists("GraphRAG-SDK");
if (!graphExists) {
console.log("⚠️ GraphRAG-SDK graph not found, skipping Scenario 7");
return;
}
// Test with a function that exists but might have GitHub API issues
const tools = getDefaultRepoHandler().getTools(realRepoData, {}, {});
const toolCb = tools.find((t) => t.name === "fetchUsageCodeExamples")?.cb;
if (!toolCb) {
throw new Error("fetchUsageCodeExamples tool not found");
}
const result = await toolCb({
functionName: "chat_session",
});
// Should either return code examples or show fallback message
const hasCodeExamples = result.content[0].text.includes("Code Example");
const hasFallback = result.content[0].text.includes(
"temporarily unavailable",
);
expect(hasCodeExamples || hasFallback).toBe(true);
console.log("✅ Scenario 7: GitHub API handling working");
});
});
describe("Scenario 8: General error/exception", () => {
it("should handle database connection errors gracefully", async () => {
// Create a repo data with invalid configuration to trigger errors
const invalidRepoData = {
owner: "", // Empty string should cause URL construction errors
repo: "", // Empty string should cause URL construction errors
host: "gitmcp.io",
urlType: "github" as const,
};
const tools = getDefaultRepoHandler().getTools(invalidRepoData, {}, {});
const toolCb = tools.find((t) => t.name === "fetchUsageCodeExamples")?.cb;
if (!toolCb) {
throw new Error("fetchUsageCodeExamples tool not found");
}
try {
const result = await toolCb({
functionName: "test_function",
});
// Should either return error message or fail with empty repo data
const hasError =
result.content[0].text.includes("❌") ||
result.content[0].text.includes("Error") ||
result.content[0].text.includes("failed") ||
result.content[0].text.includes("Invalid") ||
result.content[0].text.includes("empty");
expect(hasError).toBe(true);
console.log("✅ Scenario 8: Error handling working");
} catch (error) {
// If an exception is thrown, that's also valid error handling
expect(error).toBeDefined();
console.log("✅ Scenario 8: Error handling working (exception thrown)");
}
});
});
describe("Edge Cases and State Management", () => {
it("should handle stale lock cleanup properly", async () => {
const repoKey = `${testRepoData.owner}/${testRepoData.repo}`;
// Manually create a stale lock (simulate old timestamp)
const registry = graphService.getGlobalCreationRegistry?.() || new Map();
registry.set(repoKey, {
inProgress: true,
timestamp: Date.now() - 15 * 60 * 1000, // 15 minutes ago
phase: "Stale analysis",
});
const tools = getDefaultRepoHandler().getTools(testRepoData, {}, {});
const toolCb = tools.find((t) => t.name === "fetchUsageCodeExamples")?.cb;
if (!toolCb) {
throw new Error("fetchUsageCodeExamples tool not found");
}
const result = await toolCb({
functionName: "test_function",
});
// Should clean up stale locks and either start fresh or show progress
expect(result.content[0].text).toMatch(
/Starting Code Analysis|Graph Creation/,
);
console.log("✅ Stale lock cleanup working");
});
it("should handle multiple repositories independently", async () => {
const repo1Key = `${realRepoData.owner}/${realRepoData.repo}`;
const repo2Key = `${testRepoData.owner}/${testRepoData.repo}`;
// Set different states for each repo
graphService.setCreationLock(repo1Key, false);
graphService.setCreationLock(repo2Key, true);
const tools1 = getDefaultRepoHandler().getTools(realRepoData, {}, {});
const tools2 = getDefaultRepoHandler().getTools(testRepoData, {}, {});
const toolCb1 = tools1.find(
(t) => t.name === "fetchUsageCodeExamples",
)?.cb;
const toolCb2 = tools2.find(
(t) => t.name === "fetchUsageCodeExamples",
)?.cb;
if (!toolCb1 || !toolCb2) {
throw new Error(
"fetchUsageCodeExamples tool not found in one or both handlers",
);
}
const [result1, result2] = await Promise.all([
toolCb1({ functionName: "test_function" }),
toolCb2({ functionName: "test_function" }),
]);
// Results should be different based on repo state
expect(result1.content[0].text).not.toEqual(result2.content[0].text);
console.log("✅ Multi-repository independence working");
// Clean up
graphService.setCreationLock(repo1Key, false);
graphService.setCreationLock(repo2Key, false);
});
it("should validate real FalkorDB connection and operations", async () => {
// Test actual database operations
const graphs = await client.list();
expect(Array.isArray(graphs)).toBe(true);
// Test graph service connection
const isConnected = await graphService.checkGraphExists("GraphRAG-SDK");
expect(typeof isConnected).toBe("boolean");
console.log(
`✅ FalkorDB operations working. Available graphs: ${graphs.join(", ")}`,
);
});
});
});