Repository navigation
Expand file tree
/
Copy pathtest_java_method_calls.py
More file actions
683 lines (548 loc) · 18 KB
/
Copy pathtest_java_method_calls.py
File metadata and controls
683 lines (548 loc) · 18 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
"""
Java method call parsing and inheritance testing.
Tests method invocations, inheritance patterns, polymorphism,
and method overriding.
"""
from pathlib import Path
from unittest.mock import MagicMock
import pytest
from codebase_rag.graph_updater import GraphUpdater
from codebase_rag.parser_loader import load_parsers
@pytest.fixture
def java_methods_project(temp_repo: Path) -> Path:
"""Create a Java project with method call patterns."""
project_path = temp_repo / "java_methods_test"
project_path.mkdir()
# Create package structure
(project_path / "src").mkdir()
(project_path / "src" / "main").mkdir()
(project_path / "src" / "main" / "java").mkdir()
(project_path / "src" / "main" / "java" / "com").mkdir()
(project_path / "src" / "main" / "java" / "com" / "example").mkdir()
return project_path
def test_basic_method_calls(
java_methods_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test basic Java method call parsing."""
test_file = (
java_methods_project
/ "src"
/ "main"
/ "java"
/ "com"
/ "example"
/ "BasicMethodCalls.java"
)
test_file.write_text(
"""
package com.example;
public class BasicMethodCalls {
private String name;
public BasicMethodCalls(String name) {
this.name = name;
}
public void instanceMethod() {
System.out.println("Instance method called");
}
public static void staticMethod() {
System.out.println("Static method called");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void demonstrateMethodCalls() {
// Instance method calls
instanceMethod();
this.instanceMethod();
// Getter/setter calls
String currentName = getName();
setName("New Name");
// Static method calls
staticMethod();
BasicMethodCalls.staticMethod();
// Method chaining
String result = getName().toUpperCase().trim();
// System method calls
System.out.println("Name: " + getName());
System.err.println("Error message");
// Math method calls
double sqrt = Math.sqrt(25);
int max = Math.max(10, 20);
}
public void callOtherObject() {
BasicMethodCalls other = new BasicMethodCalls("Other");
other.instanceMethod();
String otherName = other.getName();
other.setName("Modified");
}
}
"""
)
parsers, queries = load_parsers()
if "java" not in parsers:
pytest.skip("Java parser not available")
updater = GraphUpdater(
ingestor=mock_ingestor,
repo_path=java_methods_project,
parsers=parsers,
queries=queries,
)
updater.run()
# Check that method calls were detected by looking at CALLS relationships
call_relationships = [
c
for c in mock_ingestor.ensure_relationship_batch.call_args_list
if len(c.args) > 1 and c.args[1] == "CALLS"
]
assert len(call_relationships) > 0, "No method call relationships found"
def test_inheritance_and_polymorphism(
java_methods_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test method calls in inheritance hierarchies."""
test_file = (
java_methods_project
/ "src"
/ "main"
/ "java"
/ "com"
/ "example"
/ "InheritanceExample.java"
)
test_file.write_text(
"""
package com.example;
abstract class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
public abstract void makeSound();
public void eat() {
System.out.println(name + " is eating");
}
public String getName() {
return name;
}
}
class Dog extends Animal {
private String breed;
public Dog(String name, String breed) {
super(name);
this.breed = breed;
}
@Override
public void makeSound() {
System.out.println(getName() + " barks: Woof!");
}
public void wagTail() {
System.out.println(getName() + " wags tail");
}
public String getBreed() {
return breed;
}
}
class Cat extends Animal {
public Cat(String name) {
super(name);
}
@Override
public void makeSound() {
System.out.println(getName() + " meows: Meow!");
}
public void purr() {
System.out.println(getName() + " purrs");
}
}
public class InheritanceExample {
public void demonstratePolymorphism() {
Animal[] animals = {
new Dog("Buddy", "Golden Retriever"),
new Cat("Whiskers"),
new Dog("Max", "German Shepherd")
};
for (Animal animal : animals) {
animal.makeSound(); // Polymorphic method call
animal.eat(); // Inherited method call
if (animal instanceof Dog) {
Dog dog = (Dog) animal;
dog.wagTail();
System.out.println("Breed: " + dog.getBreed());
} else if (animal instanceof Cat) {
Cat cat = (Cat) animal;
cat.purr();
}
}
}
public void demonstrateSuper() {
Dog dog = new Dog("Rex", "Labrador");
// These will call overridden methods
dog.makeSound();
dog.eat();
// Dog-specific method
dog.wagTail();
// Inherited getter
String name = dog.getName();
String breed = dog.getBreed();
}
}
"""
)
parsers, queries = load_parsers()
if "java" not in parsers:
pytest.skip("Java parser not available")
updater = GraphUpdater(
ingestor=mock_ingestor,
repo_path=java_methods_project,
parsers=parsers,
queries=queries,
)
updater.run()
# Check class definitions
class_calls = [
call
for call in mock_ingestor.ensure_node_batch.call_args_list
if call[0][0] == "Class"
]
created_classes = {call[0][1]["qualified_name"] for call in class_calls}
# Expected class qualified names
project_name = java_methods_project.name
expected_classes = {
f"{project_name}.src.main.java.com.example.InheritanceExample.Animal",
f"{project_name}.src.main.java.com.example.InheritanceExample.Dog",
f"{project_name}.src.main.java.com.example.InheritanceExample.Cat",
f"{project_name}.src.main.java.com.example.InheritanceExample.InheritanceExample",
}
# Verify all expected classes were created
missing_classes = expected_classes - created_classes
assert not missing_classes, (
f"Missing expected classes: {sorted(list(missing_classes))}"
)
# Check method calls via CALLS relationships
call_relationships = [
c
for c in mock_ingestor.ensure_relationship_batch.call_args_list
if len(c.args) > 1 and c.args[1] == "CALLS"
]
assert len(call_relationships) > 0, "No method call relationships found"
def test_interface_method_calls(
java_methods_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test method calls through interfaces."""
test_file = (
java_methods_project
/ "src"
/ "main"
/ "java"
/ "com"
/ "example"
/ "InterfaceExample.java"
)
test_file.write_text(
"""
package com.example;
import java.util.*;
interface Drawable {
void draw();
void setColor(String color);
default void clear() {
System.out.println("Clearing drawable");
}
}
interface Resizable {
void resize(double factor);
double getArea();
}
class Rectangle implements Drawable, Resizable {
private double width, height;
private String color;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
this.color = "black";
}
@Override
public void draw() {
System.out.println("Drawing " + color + " rectangle: " + width + "x" + height);
}
@Override
public void setColor(String color) {
this.color = color;
}
@Override
public void resize(double factor) {
this.width *= factor;
this.height *= factor;
}
@Override
public double getArea() {
return width * height;
}
}
class Circle implements Drawable, Resizable {
private double radius;
private String color;
public Circle(double radius) {
this.radius = radius;
this.color = "black";
}
@Override
public void draw() {
System.out.println("Drawing " + color + " circle with radius: " + radius);
}
@Override
public void setColor(String color) {
this.color = color;
}
@Override
public void resize(double factor) {
this.radius *= factor;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}
public class InterfaceExample {
public void demonstrateInterfaceCalls() {
List<Drawable> drawables = new ArrayList<>();
drawables.add(new Rectangle(10, 5));
drawables.add(new Circle(3));
for (Drawable drawable : drawables) {
drawable.setColor("red");
drawable.draw();
drawable.clear(); // Default interface method
}
}
public void demonstrateMultipleInterfaces() {
Rectangle rect = new Rectangle(4, 6);
Circle circle = new Circle(2);
// Use as Drawable
processDrawable(rect);
processDrawable(circle);
// Use as Resizable
processResizable(rect);
processResizable(circle);
}
private void processDrawable(Drawable drawable) {
drawable.setColor("blue");
drawable.draw();
}
private void processResizable(Resizable resizable) {
double originalArea = resizable.getArea();
resizable.resize(1.5);
double newArea = resizable.getArea();
System.out.println("Area changed from " + originalArea + " to " + newArea);
}
}
"""
)
parsers, queries = load_parsers()
if "java" not in parsers:
pytest.skip("Java parser not available")
updater = GraphUpdater(
ingestor=mock_ingestor,
repo_path=java_methods_project,
parsers=parsers,
queries=queries,
)
updater.run()
# Check interface and class definitions
all_calls = mock_ingestor.ensure_node_batch.call_args_list
class_calls = [call for call in all_calls if call[0][0] == "Class"]
interface_calls = [call for call in all_calls if call[0][0] == "Interface"]
created_classes = {call[0][1]["qualified_name"] for call in class_calls}
created_interfaces = {call[0][1]["qualified_name"] for call in interface_calls}
# Expected type qualified names
project_name = java_methods_project.name
expected_classes = {
f"{project_name}.src.main.java.com.example.InterfaceExample.Rectangle",
f"{project_name}.src.main.java.com.example.InterfaceExample.Circle",
f"{project_name}.src.main.java.com.example.InterfaceExample.InterfaceExample",
}
expected_interfaces = {
f"{project_name}.src.main.java.com.example.InterfaceExample.Drawable",
f"{project_name}.src.main.java.com.example.InterfaceExample.Resizable",
}
# Verify all expected types were created
missing_classes = expected_classes - created_classes
missing_interfaces = expected_interfaces - created_interfaces
assert not missing_classes, (
f"Missing expected classes: {sorted(list(missing_classes))}"
)
assert not missing_interfaces, (
f"Missing expected interfaces: {sorted(list(missing_interfaces))}"
)
# Check interface method calls via CALLS relationships
call_relationships = [
c
for c in mock_ingestor.ensure_relationship_batch.call_args_list
if len(c.args) > 1 and c.args[1] == "CALLS"
]
assert len(call_relationships) > 0, "No method call relationships found"
def test_generic_method_calls(
java_methods_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test method calls with generics."""
test_file = (
java_methods_project
/ "src"
/ "main"
/ "java"
/ "com"
/ "example"
/ "GenericMethods.java"
)
test_file.write_text(
"""
package com.example;
import java.util.*;
public class GenericMethods {
public <T> T getFirst(List<T> list) {
return list.isEmpty() ? null : list.get(0);
}
public <T> void swap(List<T> list, int i, int j) {
T temp = list.get(i);
list.set(i, list.get(j));
list.set(j, temp);
}
public <K, V> Map<K, V> createMap(K[] keys, V[] values) {
Map<K, V> map = new HashMap<>();
for (int i = 0; i < Math.min(keys.length, values.length); i++) {
map.put(keys[i], values[i]);
}
return map;
}
public void demonstrateGenericCalls() {
// Generic method calls with type inference
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
String first = getFirst(names);
swap(names, 0, 1);
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Integer firstNumber = getFirst(numbers);
swap(numbers, 1, 3);
// Generic method calls with explicit types
String[] keyArray = {"a", "b", "c"};
Integer[] valueArray = {1, 2, 3};
Map<String, Integer> map = this.<String, Integer>createMap(keyArray, valueArray);
// Collection method calls
names.add("David");
names.remove("Alice");
boolean contains = names.contains("Bob");
int size = names.size();
// Map method calls
map.put("d", 4);
Integer value = map.get("a");
boolean hasKey = map.containsKey("b");
Set<String> keys = map.keySet();
Collection<Integer> values = map.values();
}
public void demonstrateStreamAPI() {
List<String> words = Arrays.asList("hello", "world", "java", "stream");
// Stream method chaining
List<String> result = words.stream()
.filter(word -> word.length() > 4)
.map(String::toUpperCase)
.sorted()
.collect(Collectors.toList());
// Method references
words.forEach(System.out::println);
words.stream().mapToInt(String::length).sum();
}
}
"""
)
parsers, queries = load_parsers()
if "java" not in parsers:
pytest.skip("Java parser not available")
updater = GraphUpdater(
ingestor=mock_ingestor,
repo_path=java_methods_project,
parsers=parsers,
queries=queries,
)
updater.run()
# Check generic method calls via CALLS relationships
call_relationships = [
c
for c in mock_ingestor.ensure_relationship_batch.call_args_list
if len(c.args) > 1 and c.args[1] == "CALLS"
]
assert len(call_relationships) > 0, "No generic method call relationships found"
def test_fully_qualified_static_method_calls(
java_methods_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test that fully qualified static method calls are resolved correctly.
This test specifically covers the bug where fully qualified class names
like 'java.util.Collections' were incorrectly treated as variables
instead of being checked directly in the function registry.
"""
test_file = (
java_methods_project
/ "src"
/ "main"
/ "java"
/ "com"
/ "example"
/ "StaticMethodCalls.java"
)
test_file.write_text(
"""
package com.example;
import java.util.List;
import java.util.ArrayList;
public class StaticMethodCalls {
public void demonstrateFullyQualifiedStaticCalls() {
List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
// These are the method calls that should be properly resolved
java.util.Collections.sort(list); // CALLS fully qualified static method
java.util.Collections.reverse(list); // CALLS fully qualified static method
// Also test standard library static methods
double sqrt = java.lang.Math.sqrt(25.0); // CALLS fully qualified static method
int max = java.lang.Math.max(10, 20); // CALLS fully qualified static method
// Test primitive wrapper static methods
java.lang.Integer num = java.lang.Integer.valueOf(42); // CALLS fully qualified static method
java.lang.String str = java.lang.String.valueOf(123); // CALLS fully qualified static method
java.lang.String formatted = java.lang.String.format("Value: %d", 42); // CALLS fully qualified static method
// Test with shorter qualified names (imported classes)
double pi = Math.PI; // ACCESS static field
String result = String.format("Result: %s", formatted); // CALLS static method
// Custom static method calls
StaticMethodCalls.helperMethod(); // CALLS static method
com.example.StaticMethodCalls.helperMethod(); // CALLS fully qualified static method
}
public static void helperMethod() {
java.lang.System.out.println("Helper method called"); // CALLS fully qualified static method
}
public static String formatValue(int value) {
return java.lang.String.format("Formatted: %d", value); // CALLS fully qualified static method
}
}
"""
)
parsers, queries = load_parsers()
if "java" not in parsers:
pytest.skip("Java parser not available")
updater = GraphUpdater(
ingestor=mock_ingestor,
repo_path=java_methods_project,
parsers=parsers,
queries=queries,
)
updater.run()
# Check that fully qualified static method calls were detected by looking at CALLS relationships
call_relationships = [
c
for c in mock_ingestor.ensure_relationship_batch.call_args_list
if len(c.args) > 1 and c.args[1] == "CALLS"
]
assert len(call_relationships) > 0, "No static method call relationships found"