-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueryServiceTest.java
More file actions
808 lines (627 loc) · 32.1 KB
/
Copy pathQueryServiceTest.java
File metadata and controls
808 lines (627 loc) · 32.1 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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
package io.github.randomcodespace.iq.query;
import io.github.randomcodespace.iq.config.CodeIqConfig;
import io.github.randomcodespace.iq.graph.GraphStore;
import io.github.randomcodespace.iq.model.CodeEdge;
import io.github.randomcodespace.iq.model.CodeNode;
import io.github.randomcodespace.iq.model.EdgeKind;
import io.github.randomcodespace.iq.model.NodeKind;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class QueryServiceTest {
@Mock
private GraphStore graphStore;
private CodeIqConfig config;
private StatsService statsService;
private QueryService service;
@BeforeEach
void setUp() {
config = new CodeIqConfig();
config.setMaxDepth(10);
config.setMaxRadius(10);
service = new QueryService(graphStore, config);
}
private CodeNode makeNode(String id, NodeKind kind, String label) {
var node = new CodeNode(id, kind, label);
node.setLayer("backend");
node.setModule("app");
node.setFilePath("src/app.py");
return node;
}
private CodeNode makeNodeWithEdge(String id, NodeKind kind, String label,
String targetId, EdgeKind edgeKind) {
var node = makeNode(id, kind, label);
var target = makeNode(targetId, NodeKind.CLASS, "Target");
var edge = new CodeEdge("edge:" + id + ":" + targetId, edgeKind, id, target);
node.setEdges(new ArrayList<>(List.of(edge)));
return node;
}
// --- getStats ---
@Test
void getStatsShouldReturnNodeAndEdgeCounts() {
// Mock Cypher aggregation from GraphStore
Map<String, Object> aggregateStats = new java.util.LinkedHashMap<>();
aggregateStats.put("graph", Map.of("nodes", 2L, "edges", 1L, "files", 2L));
aggregateStats.put("languages", Map.of("java", 2L));
aggregateStats.put("frameworks", Map.of());
aggregateStats.put("infra", Map.of("databases", Map.of(), "messaging", Map.of(), "cloud", Map.of()));
Map<String, Object> rest = new java.util.LinkedHashMap<>();
rest.put("total", 1L);
rest.put("by_method", Map.of("GET", 1L));
Map<String, Object> connections = new java.util.LinkedHashMap<>();
connections.put("rest", rest);
connections.put("grpc", 0L);
connections.put("websocket", 0L);
connections.put("producers", 0L);
connections.put("consumers", 0L);
aggregateStats.put("connections", connections);
aggregateStats.put("auth", Map.of());
aggregateStats.put("architecture", Map.of("classes", 1L));
when(graphStore.computeAggregateStats()).thenReturn(aggregateStats);
when(graphStore.countNodesByKind()).thenReturn(List.of(
Map.of("kind", "endpoint", "cnt", 1L),
Map.of("kind", "class", "cnt", 1L)));
when(graphStore.countNodesByLayer()).thenReturn(List.of(
Map.of("layer", "backend", "cnt", 2L)));
Map<String, Object> stats = service.getStats();
@SuppressWarnings("unchecked")
Map<String, Object> graph = (Map<String, Object>) stats.get("graph");
assertEquals(2L, graph.get("nodes"));
assertEquals(1L, graph.get("edges"));
assertEquals(2L, graph.get("files"));
assertNotNull(stats.get("languages"));
assertNotNull(stats.get("frameworks"));
assertNotNull(stats.get("infra"));
assertNotNull(stats.get("connections"));
assertNotNull(stats.get("auth"));
assertNotNull(stats.get("architecture"));
@SuppressWarnings("unchecked")
Map<String, Object> resultConnections = (Map<String, Object>) stats.get("connections");
@SuppressWarnings("unchecked")
Map<String, Object> resultRest = (Map<String, Object>) resultConnections.get("rest");
assertEquals(1L, resultRest.get("total"));
assertEquals(2L, stats.get("node_count"));
assertEquals(1L, stats.get("edge_count"));
assertNotNull(stats.get("nodes_by_kind"));
assertNotNull(stats.get("nodes_by_layer"));
}
// --- listKinds ---
@Test
void listKindsShouldReturnKindCounts() {
when(graphStore.countNodesByKind()).thenReturn(List.of(
Map.of("kind", "endpoint", "cnt", 2L),
Map.of("kind", "class", "cnt", 1L)));
Map<String, Object> result = service.listKinds();
assertNotNull(result.get("kinds"));
assertEquals(3L, result.get("total"));
@SuppressWarnings("unchecked")
List<Map<String, Object>> kinds = (List<Map<String, Object>>) result.get("kinds");
// endpoint has 2 nodes, should be first (sorted by count desc)
assertEquals("endpoint", kinds.getFirst().get("kind"));
assertEquals(2L, kinds.getFirst().get("count"));
}
// --- nodesByKind ---
@Test
void nodesByKindShouldReturnPaginated() {
var n1 = makeNode("n1", NodeKind.ENDPOINT, "getUsers");
when(graphStore.findByKindPaginated("endpoint", 0, 50)).thenReturn(List.of(n1));
when(graphStore.countByKind("endpoint")).thenReturn(1L);
Map<String, Object> result = service.nodesByKind("endpoint", 50, 0);
assertEquals("endpoint", result.get("kind"));
assertEquals(1L, result.get("total"));
assertEquals(0, result.get("offset"));
assertEquals(50, result.get("limit"));
}
// --- listNodes ---
@Test
void listNodesShouldFilterByKind() {
var n1 = makeNode("n1", NodeKind.ENDPOINT, "getUsers");
when(graphStore.findByKindPaginated("endpoint", 0, 100)).thenReturn(List.of(n1));
Map<String, Object> result = service.listNodes("endpoint", 100, 0);
@SuppressWarnings("unchecked")
List<Map<String, Object>> nodes = (List<Map<String, Object>>) result.get("nodes");
assertEquals(1, nodes.size());
}
@Test
void listNodesShouldReturnAllWhenNoKind() {
var n1 = makeNode("n1", NodeKind.ENDPOINT, "getUsers");
when(graphStore.findAllPaginated(0, 100)).thenReturn(List.of(n1));
Map<String, Object> result = service.listNodes(null, 100, 0);
assertEquals(1, result.get("count"));
}
// --- listEdges ---
@Test
void listEdgesShouldFilterByKind() {
when(graphStore.findEdgesByKindPaginated("calls", 0, 100)).thenReturn(List.of(
Map.of("id", "e1", "kind", "calls", "sourceId", "n1", "targetId", "n2")));
when(graphStore.countEdgesByKind("calls")).thenReturn(1L);
Map<String, Object> result = service.listEdges("calls", 100, 0);
@SuppressWarnings("unchecked")
List<Map<String, Object>> edges = (List<Map<String, Object>>) result.get("edges");
assertEquals(1, edges.size());
}
@Test
void listEdgesShouldExcludeNonMatchingKind() {
when(graphStore.findEdgesByKindPaginated("imports", 0, 100)).thenReturn(List.of());
when(graphStore.countEdgesByKind("imports")).thenReturn(0L);
Map<String, Object> result = service.listEdges("imports", 100, 0);
@SuppressWarnings("unchecked")
List<Map<String, Object>> edges = (List<Map<String, Object>>) result.get("edges");
assertEquals(0, edges.size());
}
// --- nodeDetailWithEdges ---
@Test
void nodeDetailShouldReturnDetailWithEdges() {
var n1 = makeNodeWithEdge("n1", NodeKind.ENDPOINT, "getUsers",
"n2", EdgeKind.CALLS);
when(graphStore.findById("n1")).thenReturn(Optional.of(n1));
when(graphStore.findIncomingNeighbors("n1")).thenReturn(List.of());
Map<String, Object> result = service.nodeDetailWithEdges("n1");
assertNotNull(result);
assertEquals("n1", result.get("id"));
assertNotNull(result.get("outgoing_edges"));
assertNotNull(result.get("incoming_nodes"));
}
@Test
void nodeDetailShouldReturnNullForMissing() {
when(graphStore.findById("nonexistent")).thenReturn(Optional.empty());
assertNull(service.nodeDetailWithEdges("nonexistent"));
}
// --- getNeighbors ---
@Test
void getNeighborsShouldUseBothDirection() {
var n2 = makeNode("n2", NodeKind.CLASS, "UserService");
when(graphStore.findNeighbors("n1")).thenReturn(List.of(n2));
Map<String, Object> result = service.getNeighbors("n1", "both");
assertEquals("both", result.get("direction"));
assertEquals(1, result.get("count"));
}
@Test
void getNeighborsShouldUseOutDirection() {
when(graphStore.findOutgoingNeighbors("n1")).thenReturn(List.of());
Map<String, Object> result = service.getNeighbors("n1", "out");
assertEquals("out", result.get("direction"));
verify(graphStore).findOutgoingNeighbors("n1");
}
@Test
void getNeighborsShouldUseInDirection() {
when(graphStore.findIncomingNeighbors("n1")).thenReturn(List.of());
Map<String, Object> result = service.getNeighbors("n1", "in");
assertEquals("in", result.get("direction"));
verify(graphStore).findIncomingNeighbors("n1");
}
// --- shortestPath ---
@Test
void shortestPathShouldReturnPath() {
when(graphStore.findShortestPath("a", "b")).thenReturn(List.of("a", "c", "b"));
Map<String, Object> result = service.shortestPath("a", "b");
assertNotNull(result);
assertEquals("a", result.get("source"));
assertEquals("b", result.get("target"));
assertEquals(2, result.get("length"));
}
@Test
void shortestPathShouldReturnNullWhenNoPath() {
when(graphStore.findShortestPath("a", "b")).thenReturn(List.of());
assertNull(service.shortestPath("a", "b"));
}
// --- findCycles ---
@Test
void findCyclesShouldReturnCycles() {
List<List<String>> cycles = List.of(List.of("a", "b", "a"));
when(graphStore.findCycles(100)).thenReturn(cycles);
Map<String, Object> result = service.findCycles(100);
assertEquals(1, result.get("count"));
}
// --- traceImpact ---
@Test
void traceImpactShouldCapDepth() {
config.setMaxDepth(5);
var impacted = makeNode("n2", NodeKind.CLASS, "Service");
when(graphStore.traceImpact("n1", 5)).thenReturn(List.of(impacted));
Map<String, Object> result = service.traceImpact("n1", 20);
assertEquals(5, result.get("depth"));
verify(graphStore).traceImpact("n1", 5);
}
// --- egoGraph ---
@Test
void egoGraphShouldCapRadius() {
config.setMaxRadius(5);
when(graphStore.findEgoGraph("center", 5)).thenReturn(new ArrayList<>());
var centerNode = makeNode("center", NodeKind.MODULE, "app");
when(graphStore.findById("center")).thenReturn(Optional.of(centerNode));
Map<String, Object> result = service.egoGraph("center", 20);
assertEquals(5, result.get("radius"));
verify(graphStore).findEgoGraph("center", 5);
}
// --- consumersOf ---
@Test
void consumersOfShouldReturnConsumers() {
var consumer = makeNode("c1", NodeKind.METHOD, "handleMessage");
when(graphStore.findConsumers("topic1")).thenReturn(List.of(consumer));
Map<String, Object> result = service.consumersOf("topic1");
assertEquals("topic1", result.get("target"));
assertEquals(1, result.get("count"));
}
// --- producersOf ---
@Test
void producersOfShouldReturnProducers() {
when(graphStore.findProducers("topic1")).thenReturn(List.of());
Map<String, Object> result = service.producersOf("topic1");
assertEquals(0, result.get("count"));
}
// --- callersOf ---
@Test
void callersOfShouldReturnCallers() {
when(graphStore.findCallers("fn1")).thenReturn(List.of());
Map<String, Object> result = service.callersOf("fn1");
assertEquals("fn1", result.get("target"));
}
// --- dependenciesOf ---
@Test
void dependenciesOfShouldReturnDeps() {
when(graphStore.findDependencies("mod1")).thenReturn(List.of());
Map<String, Object> result = service.dependenciesOf("mod1");
assertEquals("mod1", result.get("module"));
}
// --- dependentsOf ---
@Test
void dependentsOfShouldReturnDeps() {
when(graphStore.findDependents("mod1")).thenReturn(List.of());
Map<String, Object> result = service.dependentsOf("mod1");
assertEquals("mod1", result.get("module"));
}
// --- findComponentByFile ---
@Test
void findComponentByFileShouldReturnFileNodes() {
var n1 = makeNode("n1", NodeKind.MODULE, "app");
when(graphStore.findByFilePath("src/app.py")).thenReturn(List.of(n1));
Map<String, Object> result = service.findComponentByFile("src/app.py");
assertEquals("src/app.py", result.get("file"));
assertEquals(1, result.get("count"));
assertEquals("app", result.get("module"));
assertEquals("backend", result.get("layer"));
}
@Test
void findComponentByFileShouldHandleNoResults() {
when(graphStore.findByFilePath("unknown.py")).thenReturn(List.of());
Map<String, Object> result = service.findComponentByFile("unknown.py");
assertEquals(0, result.get("count"));
assertNull(result.get("module"));
}
// --- searchGraph ---
@Test
void searchGraphShouldReturnResults() {
var n1 = makeNode("n1", NodeKind.CLASS, "UserService");
when(graphStore.search("User", 50)).thenReturn(List.of(n1));
List<Map<String, Object>> results = service.searchGraph("User", 50);
assertEquals(1, results.size());
assertEquals("UserService", results.getFirst().get("label"));
}
@Test
void searchGraphShouldCapLimit() {
when(graphStore.search("test", 200)).thenReturn(List.of());
service.searchGraph("test", 500);
verify(graphStore).search("test", 200);
}
// --- findDeadCode ---
@Test
void findDeadCodeShouldReturnNodesWithoutSemanticIncoming() {
var deadClass = makeNode("cls:dead", NodeKind.CLASS, "UnusedHelper");
when(graphStore.findNodesWithoutIncomingSemantic(anyList(), anyList(), anyList(), eq(0), eq(100)))
.thenReturn(List.of(deadClass));
Map<String, Object> result = service.findDeadCode(null, 100);
assertEquals(1, result.get("count"));
@SuppressWarnings("unchecked")
List<Map<String, Object>> deadCode = (List<Map<String, Object>>) result.get("dead_code");
assertEquals("cls:dead", deadCode.getFirst().get("id"));
assertEquals("class", deadCode.getFirst().get("kind"));
assertEquals("UnusedHelper", deadCode.getFirst().get("label"));
}
@Test
void findDeadCodeShouldPassSemanticEdgeKinds() {
when(graphStore.findNodesWithoutIncomingSemantic(anyList(), anyList(), anyList(), eq(0), eq(50)))
.thenReturn(List.of());
service.findDeadCode(null, 50);
// Verify semantic edge kinds are passed (not structural ones like contains, defines)
@SuppressWarnings("unchecked")
var captor = org.mockito.ArgumentCaptor.forClass(List.class);
verify(graphStore).findNodesWithoutIncomingSemantic(anyList(), captor.capture(), anyList(), eq(0), eq(50));
@SuppressWarnings("unchecked")
List<String> semanticKinds = captor.getValue();
assertTrue(semanticKinds.contains("calls"), "Should include 'calls'");
assertTrue(semanticKinds.contains("imports"), "Should include 'imports'");
assertTrue(semanticKinds.contains("depends_on"), "Should include 'depends_on'");
assertTrue(semanticKinds.contains("extends"), "Should include 'extends'");
assertTrue(semanticKinds.contains("implements"), "Should include 'implements'");
assertFalse(semanticKinds.contains("contains"), "Should NOT include 'contains'");
assertFalse(semanticKinds.contains("defines"), "Should NOT include 'defines'");
}
@Test
void findDeadCodeShouldExcludeEntryPointKinds() {
when(graphStore.findNodesWithoutIncomingSemantic(anyList(), anyList(), anyList(), eq(0), eq(50)))
.thenReturn(List.of());
service.findDeadCode(null, 50);
// Verify entry point kinds are excluded
@SuppressWarnings("unchecked")
var kindCaptor = org.mockito.ArgumentCaptor.forClass(List.class);
// args: kinds, semanticEdgeKinds, excludeNodeKinds, offset, limit
verify(graphStore).findNodesWithoutIncomingSemantic(anyList(), anyList(), kindCaptor.capture(), eq(0), eq(50));
@SuppressWarnings("unchecked")
List<String> excludeKinds = kindCaptor.getValue();
assertTrue(excludeKinds.contains("endpoint"), "Should exclude endpoints");
assertTrue(excludeKinds.contains("websocket_endpoint"), "Should exclude websocket endpoints");
assertTrue(excludeKinds.contains("migration"), "Should exclude migrations");
assertTrue(excludeKinds.contains("config_file"), "Should exclude config files");
assertTrue(excludeKinds.contains("guard"), "Should exclude guards");
assertTrue(excludeKinds.contains("middleware"), "Should exclude middleware");
assertTrue(excludeKinds.contains("topic"), "Should exclude topics");
assertTrue(excludeKinds.contains("queue"), "Should exclude queues");
assertTrue(excludeKinds.contains("event"), "Should exclude events");
assertTrue(excludeKinds.contains("message_queue"), "Should exclude message queues");
}
@Test
void findDeadCodeShouldNotFlagMessageDrivenComponents() {
var guard = makeNode("guard:AuthGuard", NodeKind.GUARD, "AuthGuard");
var middleware = makeNode("mid:LoggingMiddleware", NodeKind.MIDDLEWARE, "LoggingMiddleware");
var topic = makeNode("topic:UserEvents", NodeKind.TOPIC, "UserEvents");
var queue = makeNode("queue:EmailQueue", NodeKind.QUEUE, "EmailQueue");
var event = makeNode("event:OrderPlaced", NodeKind.EVENT, "OrderPlaced");
var messageQueue = makeNode("mq:NotificationQueue", NodeKind.MESSAGE_QUEUE, "NotificationQueue");
// These are excluded via ENTRY_POINT_KINDS so graphStore won't return them
when(graphStore.findNodesWithoutIncomingSemantic(anyList(), anyList(), anyList(), eq(0), eq(100)))
.thenReturn(List.of());
Map<String, Object> result = service.findDeadCode(null, 100);
@SuppressWarnings("unchecked")
List<Map<String, Object>> deadCode = (List<Map<String, Object>>) result.get("dead_code");
assertTrue(deadCode.isEmpty(), "Message-driven and security components should not be flagged as dead code");
}
@Test
void findDeadCodeShouldIncludeProtectsInSemanticEdgeKinds() {
when(graphStore.findNodesWithoutIncomingSemantic(anyList(), anyList(), anyList(), eq(0), eq(50)))
.thenReturn(List.of());
service.findDeadCode(null, 50);
@SuppressWarnings("unchecked")
var captor = org.mockito.ArgumentCaptor.forClass(List.class);
verify(graphStore).findNodesWithoutIncomingSemantic(anyList(), captor.capture(), anyList(), eq(0), eq(50));
@SuppressWarnings("unchecked")
List<String> semanticKinds = captor.getValue();
assertTrue(semanticKinds.contains("protects"), "Should include 'protects' as semantic edge");
assertFalse(semanticKinds.contains("uses"), "Should NOT include 'uses' — not a valid EdgeKind");
}
@Test
void findDeadCodeShouldFilterBySpecificKind() {
when(graphStore.findNodesWithoutIncomingSemantic(eq(List.of("method")), anyList(), anyList(), eq(0), eq(50)))
.thenReturn(List.of());
service.findDeadCode("method", 50);
verify(graphStore).findNodesWithoutIncomingSemantic(eq(List.of("method")), anyList(), anyList(), eq(0), eq(50));
}
@Test
void findDeadCodeShouldReturnEmptyWhenAllNodesHaveSemanticEdges() {
when(graphStore.findNodesWithoutIncomingSemantic(anyList(), anyList(), anyList(), eq(0), eq(100)))
.thenReturn(List.of());
Map<String, Object> result = service.findDeadCode(null, 100);
assertEquals(0, result.get("count"));
@SuppressWarnings("unchecked")
List<Map<String, Object>> deadCode = (List<Map<String, Object>>) result.get("dead_code");
assertTrue(deadCode.isEmpty());
}
// --- findRelatedEndpoints ---
@Test
void findRelatedEndpointsShouldUsesBatchQueryInsteadOfNPlusOne() {
var classNode = makeNode("cls:UserService", NodeKind.CLASS, "UserService");
var endpointNode = makeNode("ep:getUsers", NodeKind.ENDPOINT, "getUsers");
when(graphStore.search("UserService", 50)).thenReturn(List.of(classNode));
when(graphStore.findEndpointNeighborsBatch(List.of("cls:UserService")))
.thenReturn(Map.of("cls:UserService", List.of(endpointNode)));
Map<String, Object> result = service.findRelatedEndpoints("UserService");
assertEquals("UserService", result.get("identifier"));
assertEquals(1, result.get("count"));
assertEquals(1, result.get("searched_nodes"));
@SuppressWarnings("unchecked")
List<Map<String, Object>> endpoints = (List<Map<String, Object>>) result.get("endpoints");
assertEquals("ep:getUsers", endpoints.getFirst().get("id"));
assertEquals("cls:UserService", endpoints.getFirst().get("connected_via"));
// Verify no per-node findNeighbors calls were made
verify(graphStore, never()).findNeighbors(anyString());
}
@Test
void findRelatedEndpointsShouldIncludeDirectEndpointMatches() {
var endpointNode = makeNode("ep:getUsers", NodeKind.ENDPOINT, "getUsers");
when(graphStore.search("getUsers", 50)).thenReturn(List.of(endpointNode));
// Endpoint nodes are partitioned directly into the result list — nonEndpointIds is empty
when(graphStore.findEndpointNeighborsBatch(List.of())).thenReturn(Map.of());
Map<String, Object> result = service.findRelatedEndpoints("getUsers");
assertEquals(1, result.get("count"));
@SuppressWarnings("unchecked")
List<Map<String, Object>> endpoints = (List<Map<String, Object>>) result.get("endpoints");
assertEquals("ep:getUsers", endpoints.getFirst().get("id"));
// Direct endpoint matches have no connected_via
assertNull(endpoints.getFirst().get("connected_via"));
}
@Test
void findRelatedEndpointsShouldDeduplicateEndpoints() {
var endpointNode = makeNode("ep:getUsers", NodeKind.ENDPOINT, "getUsers");
// Endpoint node is a direct match — nonEndpointIds is empty, batch returns nothing
when(graphStore.search("ep", 50)).thenReturn(List.of(endpointNode));
when(graphStore.findEndpointNeighborsBatch(List.of())).thenReturn(Map.of());
Map<String, Object> result = service.findRelatedEndpoints("ep");
// Should appear exactly once (direct match)
assertEquals(1, result.get("count"));
}
// --- nodeToMap ---
@Test
void nodeToMapShouldIncludeAllFields() {
var node = makeNode("n1", NodeKind.ENDPOINT, "getUsers");
node.setFqn("com.example.getUsers");
node.setLineStart(10);
node.setLineEnd(20);
node.setAnnotations(List.of("@GetMapping"));
node.setProperties(Map.of("method", "GET"));
Map<String, Object> map = service.nodeToMap(node);
assertEquals("n1", map.get("id"));
assertEquals("endpoint", map.get("kind"));
assertEquals("getUsers", map.get("label"));
assertEquals("com.example.getUsers", map.get("fqn"));
assertEquals("app", map.get("module"));
assertEquals("src/app.py", map.get("file_path"));
assertEquals(10, map.get("line_start"));
assertEquals(20, map.get("line_end"));
assertEquals("backend", map.get("layer"));
assertNotNull(map.get("annotations"));
assertNotNull(map.get("properties"));
}
@Test
void nodeToMapShouldOmitNullFields() {
var node = new CodeNode("n1", NodeKind.CLASS, "Foo");
Map<String, Object> map = service.nodeToMap(node);
assertEquals("n1", map.get("id"));
assertNull(map.get("fqn"));
assertNull(map.get("module"));
assertNull(map.get("file_path"));
assertNull(map.get("line_start"));
assertNull(map.get("layer"));
}
// --- getFileTree ---
@Test
@SuppressWarnings("unchecked")
void getFileTreeShouldBuildHierarchicalTree() {
when(graphStore.getFilePathsWithCounts(anyInt())).thenReturn(new GraphStore.FilePathResult(List.of(
Map.of("filePath", "src/main/Foo.java", "nodeCount", 3L),
Map.of("filePath", "src/main/Bar.java", "nodeCount", 1L),
Map.of("filePath", "src/test/FooTest.java", "nodeCount", 2L),
Map.of("filePath", "pom.xml", "nodeCount", 1L)), false));
Map<String, Object> result = service.getFileTree(null);
assertEquals(4L, result.get("total_files"));
List<Map<String, Object>> tree = (List<Map<String, Object>>) result.get("tree");
// Directories first (src), then files (pom.xml)
assertEquals(2, tree.size());
Map<String, Object> srcNode = tree.get(0);
assertEquals("src", srcNode.get("name"));
assertEquals("directory", srcNode.get("type"));
assertEquals(6L, srcNode.get("nodeCount")); // aggregate: 3+1+2
Map<String, Object> pomNode = tree.get(1);
assertEquals("pom.xml", pomNode.get("name"));
assertEquals("file", pomNode.get("type"));
assertEquals(1L, pomNode.get("nodeCount"));
}
@Test
@SuppressWarnings("unchecked")
void getFileTreeShouldIncludePathFieldAtEveryLevel() {
when(graphStore.getFilePathsWithCounts(anyInt())).thenReturn(new GraphStore.FilePathResult(List.of(
Map.of("filePath", "src/main/java/Foo.java", "nodeCount", 2L),
Map.of("filePath", "pom.xml", "nodeCount", 1L)), false));
Map<String, Object> result = service.getFileTree(null);
List<Map<String, Object>> tree = (List<Map<String, Object>>) result.get("tree");
// Root-level directory: path = "src"
Map<String, Object> src = tree.get(0);
assertEquals("src", src.get("path"));
// Nested directory: path = "src/main"
List<Map<String, Object>> srcChildren = (List<Map<String, Object>>) src.get("children");
Map<String, Object> main = srcChildren.get(0);
assertEquals("src/main", main.get("path"));
// Deeper directory: path = "src/main/java"
List<Map<String, Object>> mainChildren = (List<Map<String, Object>>) main.get("children");
Map<String, Object> java = mainChildren.get(0);
assertEquals("src/main/java", java.get("path"));
// File inside directory: path = "src/main/java/Foo.java"
List<Map<String, Object>> javaChildren = (List<Map<String, Object>>) java.get("children");
Map<String, Object> foo = javaChildren.get(0);
assertEquals("src/main/java/Foo.java", foo.get("path"));
// Root-level file: path = "pom.xml"
Map<String, Object> pom = tree.get(1);
assertEquals("pom.xml", pom.get("path"));
}
@Test
@SuppressWarnings("unchecked")
void getFileTreeShouldSortDirectoriesBeforeFiles() {
when(graphStore.getFilePathsWithCounts(anyInt())).thenReturn(new GraphStore.FilePathResult(List.of(
Map.of("filePath", "README.md", "nodeCount", 1L),
Map.of("filePath", "src/Foo.java", "nodeCount", 2L)), false));
Map<String, Object> result = service.getFileTree(null);
List<Map<String, Object>> tree = (List<Map<String, Object>>) result.get("tree");
assertEquals("src", tree.get(0).get("name")); // directory first
assertEquals("README.md", tree.get(1).get("name")); // file second
}
@Test
@SuppressWarnings("unchecked")
void getFileTreeShouldRespectDepthLimit() {
when(graphStore.getFilePathsWithCounts(anyInt())).thenReturn(new GraphStore.FilePathResult(List.of(
Map.of("filePath", "src/main/java/Foo.java", "nodeCount", 5L)), false));
Map<String, Object> result = service.getFileTree(2);
List<Map<String, Object>> tree = (List<Map<String, Object>>) result.get("tree");
// depth=2: root children (depth=1) + their direct children (depth=2), no deeper
Map<String, Object> src = tree.get(0); // src (depth 1)
List<Map<String, Object>> srcChildren = (List<Map<String, Object>>) src.get("children");
Map<String, Object> main = srcChildren.get(0); // main (depth 2)
List<Map<String, Object>> mainChildren = (List<Map<String, Object>>) main.get("children");
assertTrue(mainChildren.isEmpty()); // depth limit reached
}
@Test
@SuppressWarnings("unchecked")
void getFileTreeShouldReturnEmptyTreeForNoNodes() {
when(graphStore.getFilePathsWithCounts(anyInt())).thenReturn(new GraphStore.FilePathResult(List.of(), false));
Map<String, Object> result = service.getFileTree(null);
assertEquals(0L, result.get("total_files"));
List<Map<String, Object>> tree = (List<Map<String, Object>>) result.get("tree");
assertTrue(tree.isEmpty());
}
@Test
@SuppressWarnings("unchecked")
void getFileTreeShouldBeDeterministic() {
List<Map<String, Object>> paths = List.of(
Map.of("filePath", "src/B.java", "nodeCount", 2L),
Map.of("filePath", "src/A.java", "nodeCount", 1L),
Map.of("filePath", "lib/C.java", "nodeCount", 3L));
when(graphStore.getFilePathsWithCounts(anyInt())).thenReturn(new GraphStore.FilePathResult(paths, false));
Map<String, Object> first = service.getFileTree(null);
when(graphStore.getFilePathsWithCounts(anyInt())).thenReturn(new GraphStore.FilePathResult(paths, false));
Map<String, Object> second = service.getFileTree(null);
assertEquals(first.toString(), second.toString());
}
// --- findRelatedEndpoints ---
@Test
@SuppressWarnings("unchecked")
void findRelatedEndpointsShouldReturnDirectEndpointMatches() {
var ep = makeNode("ep1", NodeKind.ENDPOINT, "GET /users");
when(graphStore.search("users", 50)).thenReturn(List.of(ep));
when(graphStore.findEndpointNeighborsBatch(List.of())).thenReturn(Map.of());
Map<String, Object> result = service.findRelatedEndpoints("users");
assertEquals(1, result.get("count"));
List<Map<String, Object>> endpoints = (List<Map<String, Object>>) result.get("endpoints");
assertEquals("ep1", endpoints.getFirst().get("id"));
verify(graphStore, never()).findNeighbors(anyString());
}
@Test
@SuppressWarnings("unchecked")
void findRelatedEndpointsShouldUseBatchQueryForNeighbors() {
var cls = makeNode("cls1", NodeKind.CLASS, "UserService");
var ep = makeNode("ep1", NodeKind.ENDPOINT, "GET /users");
when(graphStore.search("UserService", 50)).thenReturn(List.of(cls));
when(graphStore.findEndpointNeighborsBatch(List.of("cls1"))).thenReturn(Map.of("cls1", List.of(ep)));
Map<String, Object> result = service.findRelatedEndpoints("UserService");
assertEquals(1, result.get("count"));
List<Map<String, Object>> endpoints = (List<Map<String, Object>>) result.get("endpoints");
assertEquals("ep1", endpoints.getFirst().get("id"));
assertEquals("cls1", endpoints.getFirst().get("connected_via"));
verify(graphStore, never()).findNeighbors(anyString());
}
@Test
void findRelatedEndpointsShouldReturnEmptyWhenNoMatches() {
when(graphStore.search("unknown", 50)).thenReturn(List.of());
when(graphStore.findEndpointNeighborsBatch(List.of())).thenReturn(Map.of());
Map<String, Object> result = service.findRelatedEndpoints("unknown");
assertEquals(0, result.get("count"));
assertEquals(0, result.get("searched_nodes"));
}
}