-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathtest_replacement.py
More file actions
1555 lines (1314 loc) · 46.7 KB
/
test_replacement.py
File metadata and controls
1555 lines (1314 loc) · 46.7 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
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Tests for Java code replacement.
Tests the high-level replacement functions using complete valid Java source files.
All optimized code is syntactically valid Java that could compile.
All assertions use exact string equality for rigorous verification.
"""
from pathlib import Path
import pytest
from codeflash.code_utils.code_replacer import (
replace_function_definitions_for_language,
replace_function_definitions_in_module,
)
from codeflash.models.function_types import FunctionParent
from codeflash.languages.base import Language
from codeflash.languages import current as language_current
from codeflash.models.models import CodeStringsMarkdown
@pytest.fixture
def java_language_context():
"""Set the current language to Java for the duration of the test."""
original_language = language_current._current_language
language_current._current_language = Language.JAVA
yield
language_current._current_language = original_language
class TestReplaceFunctionDefinitionsInModule:
"""Tests for replace_function_definitions_in_module with Java."""
def test_replace_simple_method(self, tmp_path: Path, java_language_context):
"""Test replacing a simple method in a Java class."""
java_file = tmp_path / "Calculator.java"
original_code = """public class Calculator {
public int add(int a, int b) {
return a + b;
}
}
"""
java_file.write_text(original_code, encoding="utf-8")
optimized_markdown = f"""```java:{java_file.relative_to(tmp_path)}
public class Calculator {{
public int add(int a, int b) {{
return Math.addExact(a, b);
}}
}}
```"""
optimized_code = CodeStringsMarkdown.parse_markdown_code(optimized_markdown, expected_language="java")
result = replace_function_definitions_in_module(
function_names=["add"],
optimized_code=optimized_code,
module_abspath=java_file,
preexisting_objects=set(),
project_root_path=tmp_path,
)
assert result is True
new_code = java_file.read_text(encoding="utf-8")
expected = """public class Calculator {
public int add(int a, int b) {
return Math.addExact(a, b);
}
}
"""
assert new_code == expected
def test_replace_method_preserves_other_methods(self, tmp_path: Path, java_language_context):
"""Test that replacing one method preserves other methods."""
java_file = tmp_path / "Calculator.java"
original_code = """public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
public int multiply(int a, int b) {
return a * b;
}
}
"""
java_file.write_text(original_code, encoding="utf-8")
optimized_markdown = f"""```java:{java_file.relative_to(tmp_path)}
public class Calculator {{
public int add(int a, int b) {{
return Integer.sum(a, b);
}}
public int subtract(int a, int b) {{
return a - b;
}}
public int multiply(int a, int b) {{
return a * b;
}}
}}
```"""
optimized_code = CodeStringsMarkdown.parse_markdown_code(optimized_markdown, expected_language="java")
result = replace_function_definitions_in_module(
function_names=["add"],
optimized_code=optimized_code,
module_abspath=java_file,
preexisting_objects=set(),
project_root_path=tmp_path,
)
assert result is True
new_code = java_file.read_text(encoding="utf-8")
expected = """public class Calculator {
public int add(int a, int b) {
return Integer.sum(a, b);
}
public int subtract(int a, int b) {
return a - b;
}
public int multiply(int a, int b) {
return a * b;
}
}
"""
assert new_code == expected
def test_replace_method_with_javadoc(self, tmp_path: Path, java_language_context):
"""Test replacing a method that has Javadoc comments."""
java_file = tmp_path / "MathUtils.java"
original_code = """public class MathUtils {
/**
* Calculates the factorial.
* @param n the number
* @return factorial of n
*/
public long factorial(int n) {
if (n <= 1) return 1;
long result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
}
"""
java_file.write_text(original_code, encoding="utf-8")
optimized_markdown = f"""```java:{java_file.relative_to(tmp_path)}
public class MathUtils {{
/**
* Calculates the factorial (optimized).
* @param n the number
* @return factorial of n
*/
public long factorial(int n) {{
if (n <= 1) return 1;
long result = 1;
for (int i = 2; i <= n; i++) {{
result = Math.multiplyExact(result, i);
}}
return result;
}}
}}
```"""
optimized_code = CodeStringsMarkdown.parse_markdown_code(optimized_markdown, expected_language="java")
result = replace_function_definitions_in_module(
function_names=["factorial"],
optimized_code=optimized_code,
module_abspath=java_file,
preexisting_objects=set(),
project_root_path=tmp_path,
)
assert result is True
new_code = java_file.read_text(encoding="utf-8")
expected = """public class MathUtils {
/**
* Calculates the factorial (optimized).
* @param n the number
* @return factorial of n
*/
public long factorial(int n) {
if (n <= 1) return 1;
long result = 1;
for (int i = 2; i <= n; i++) {
result = Math.multiplyExact(result, i);
}
return result;
}
}
"""
assert new_code == expected
def test_no_change_when_code_identical(self, tmp_path: Path, java_language_context):
"""Test that no change is made when optimized code is identical."""
java_file = tmp_path / "Identity.java"
original_code = """public class Identity {
public int getValue() {
return 42;
}
}
"""
java_file.write_text(original_code, encoding="utf-8")
optimized_markdown = f"""```java:{java_file.relative_to(tmp_path)}
public class Identity {{
public int getValue() {{
return 42;
}}
}}
```"""
optimized_code = CodeStringsMarkdown.parse_markdown_code(optimized_markdown, expected_language="java")
result = replace_function_definitions_in_module(
function_names=["getValue"],
optimized_code=optimized_code,
module_abspath=java_file,
preexisting_objects=set(),
project_root_path=tmp_path,
)
assert result is False
new_code = java_file.read_text(encoding="utf-8")
assert new_code == original_code
class TestReplaceFunctionDefinitionsForLanguage:
"""Tests for replace_function_definitions_for_language with Java."""
def test_replace_static_method(self, tmp_path: Path):
"""Test replacing a static method."""
java_file = tmp_path / "Utils.java"
original_code = """public class Utils {
public static int square(int n) {
return n * n;
}
}
"""
java_file.write_text(original_code, encoding="utf-8")
optimized_markdown = f"""```java:{java_file.relative_to(tmp_path)}
public class Utils {{
public static int square(int n) {{
return Math.multiplyExact(n, n);
}}
}}
```"""
optimized_code = CodeStringsMarkdown.parse_markdown_code(optimized_markdown, expected_language="java")
result = replace_function_definitions_for_language(
function_names=["square"],
optimized_code=optimized_code,
module_abspath=java_file,
project_root_path=tmp_path,
)
assert result is True
new_code = java_file.read_text(encoding="utf-8")
expected = """public class Utils {
public static int square(int n) {
return Math.multiplyExact(n, n);
}
}
"""
assert new_code == expected
def test_replace_method_with_annotations(self, tmp_path: Path):
"""Test replacing a method with annotations."""
java_file = tmp_path / "Service.java"
original_code = """public class Service {
@Override
public String process(String input) {
return input.trim();
}
}
"""
java_file.write_text(original_code, encoding="utf-8")
optimized_markdown = f"""```java:{java_file.relative_to(tmp_path)}
public class Service {{
@Override
public String process(String input) {{
return input == null ? "" : input.strip();
}}
}}
```"""
optimized_code = CodeStringsMarkdown.parse_markdown_code(optimized_markdown, expected_language="java")
result = replace_function_definitions_for_language(
function_names=["process"],
optimized_code=optimized_code,
module_abspath=java_file,
project_root_path=tmp_path,
)
assert result is True
new_code = java_file.read_text(encoding="utf-8")
expected = """public class Service {
@Override
public String process(String input) {
return input == null ? "" : input.strip();
}
}
"""
assert new_code == expected
def test_replace_method_in_interface(self, tmp_path: Path):
"""Test replacing a default method in an interface."""
java_file = tmp_path / "Processor.java"
original_code = """public interface Processor {
default String process(String input) {
return input.toUpperCase();
}
}
"""
java_file.write_text(original_code, encoding="utf-8")
optimized_markdown = f"""```java:{java_file.relative_to(tmp_path)}
public interface Processor {{
default String process(String input) {{
return input == null ? null : input.toUpperCase();
}}
}}
```"""
optimized_code = CodeStringsMarkdown.parse_markdown_code(optimized_markdown, expected_language="java")
result = replace_function_definitions_for_language(
function_names=["process"],
optimized_code=optimized_code,
module_abspath=java_file,
project_root_path=tmp_path,
)
assert result is True
new_code = java_file.read_text(encoding="utf-8")
expected = """public interface Processor {
default String process(String input) {
return input == null ? null : input.toUpperCase();
}
}
"""
assert new_code == expected
def test_replace_method_in_enum(self, tmp_path: Path):
"""Test replacing a method in an enum."""
java_file = tmp_path / "Color.java"
original_code = """public enum Color {
RED, GREEN, BLUE;
public String getCode() {
return name().substring(0, 1);
}
}
"""
java_file.write_text(original_code, encoding="utf-8")
optimized_markdown = f"""```java:{java_file.relative_to(tmp_path)}
public enum Color {{
RED, GREEN, BLUE;
public String getCode() {{
return String.valueOf(name().charAt(0));
}}
}}
```"""
optimized_code = CodeStringsMarkdown.parse_markdown_code(optimized_markdown, expected_language="java")
result = replace_function_definitions_for_language(
function_names=["getCode"],
optimized_code=optimized_code,
module_abspath=java_file,
project_root_path=tmp_path,
)
assert result is True
new_code = java_file.read_text(encoding="utf-8")
expected = """public enum Color {
RED, GREEN, BLUE;
public String getCode() {
return String.valueOf(name().charAt(0));
}
}
"""
assert new_code == expected
def test_replace_generic_method(self, tmp_path: Path):
"""Test replacing a method with generics."""
java_file = tmp_path / "Container.java"
original_code = """import java.util.List;
import java.util.ArrayList;
public class Container<T> {
private List<T> items = new ArrayList<>();
public List<T> getItems() {
List<T> copy = new ArrayList<>();
for (T item : items) {
copy.add(item);
}
return copy;
}
}
"""
java_file.write_text(original_code, encoding="utf-8")
optimized_markdown = f"""```java:{java_file.relative_to(tmp_path)}
import java.util.List;
import java.util.ArrayList;
public class Container<T> {{
private List<T> items = new ArrayList<>();
public List<T> getItems() {{
return new ArrayList<>(items);
}}
}}
```"""
optimized_code = CodeStringsMarkdown.parse_markdown_code(optimized_markdown, expected_language="java")
result = replace_function_definitions_for_language(
function_names=["getItems"],
optimized_code=optimized_code,
module_abspath=java_file,
project_root_path=tmp_path,
)
assert result is True
new_code = java_file.read_text(encoding="utf-8")
expected = """import java.util.List;
import java.util.ArrayList;
public class Container<T> {
private List<T> items = new ArrayList<>();
public List<T> getItems() {
return new ArrayList<>(items);
}
}
"""
assert new_code == expected
def test_replace_method_with_throws(self, tmp_path: Path):
"""Test replacing a method with throws clause."""
java_file = tmp_path / "FileReader.java"
original_code = """import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class FileReader {
public String readFile(String path) throws IOException {
return new String(Files.readAllBytes(Path.of(path)));
}
}
"""
java_file.write_text(original_code, encoding="utf-8")
optimized_markdown = f"""```java:{java_file.relative_to(tmp_path)}
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class FileReader {{
public String readFile(String path) throws IOException {{
return Files.readString(Path.of(path));
}}
}}
```"""
optimized_code = CodeStringsMarkdown.parse_markdown_code(optimized_markdown, expected_language="java")
result = replace_function_definitions_for_language(
function_names=["readFile"],
optimized_code=optimized_code,
module_abspath=java_file,
project_root_path=tmp_path,
)
assert result is True
new_code = java_file.read_text(encoding="utf-8")
expected = """import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class FileReader {
public String readFile(String path) throws IOException {
return Files.readString(Path.of(path));
}
}
"""
assert new_code == expected
class TestRealWorldOptimizationScenarios:
"""Real-world optimization scenarios with complete valid Java code."""
def test_optimize_string_concatenation(self, tmp_path: Path):
"""Test optimizing string concatenation to StringBuilder."""
java_file = tmp_path / "StringJoiner.java"
original_code = """public class StringJoiner {
public String buildString(String[] items) {
String result = "";
for (String item : items) {
result = result + item;
}
return result;
}
}
"""
java_file.write_text(original_code, encoding="utf-8")
optimized_markdown = f"""```java:{java_file.relative_to(tmp_path)}
public class StringJoiner {{
public String buildString(String[] items) {{
StringBuilder sb = new StringBuilder();
for (String item : items) {{
sb.append(item);
}}
return sb.toString();
}}
}}
```"""
optimized_code = CodeStringsMarkdown.parse_markdown_code(optimized_markdown, expected_language="java")
result = replace_function_definitions_for_language(
function_names=["buildString"],
optimized_code=optimized_code,
module_abspath=java_file,
project_root_path=tmp_path,
)
assert result is True
new_code = java_file.read_text(encoding="utf-8")
expected = """public class StringJoiner {
public String buildString(String[] items) {
StringBuilder sb = new StringBuilder();
for (String item : items) {
sb.append(item);
}
return sb.toString();
}
}
"""
assert new_code == expected
def test_optimize_list_iteration(self, tmp_path: Path):
"""Test optimizing list iteration with streams."""
java_file = tmp_path / "ListProcessor.java"
original_code = """import java.util.List;
public class ListProcessor {
public int sumList(List<Integer> numbers) {
int sum = 0;
for (int i = 0; i < numbers.size(); i++) {
sum += numbers.get(i);
}
return sum;
}
}
"""
java_file.write_text(original_code, encoding="utf-8")
optimized_markdown = f"""```java:{java_file.relative_to(tmp_path)}
import java.util.List;
public class ListProcessor {{
public int sumList(List<Integer> numbers) {{
return numbers.stream().mapToInt(Integer::intValue).sum();
}}
}}
```"""
optimized_code = CodeStringsMarkdown.parse_markdown_code(optimized_markdown, expected_language="java")
result = replace_function_definitions_for_language(
function_names=["sumList"],
optimized_code=optimized_code,
module_abspath=java_file,
project_root_path=tmp_path,
)
assert result is True
new_code = java_file.read_text(encoding="utf-8")
expected = """import java.util.List;
public class ListProcessor {
public int sumList(List<Integer> numbers) {
return numbers.stream().mapToInt(Integer::intValue).sum();
}
}
"""
assert new_code == expected
def test_optimize_null_checks(self, tmp_path: Path):
"""Test optimizing null checks with Objects utility."""
java_file = tmp_path / "NullChecker.java"
original_code = """public class NullChecker {
public boolean isEqual(String s1, String s2) {
if (s1 == null && s2 == null) {
return true;
}
if (s1 == null || s2 == null) {
return false;
}
return s1.equals(s2);
}
}
"""
java_file.write_text(original_code, encoding="utf-8")
optimized_markdown = f"""```java:{java_file.relative_to(tmp_path)}
import java.util.Objects;
public class NullChecker {{
public boolean isEqual(String s1, String s2) {{
return Objects.equals(s1, s2);
}}
}}
```"""
optimized_code = CodeStringsMarkdown.parse_markdown_code(optimized_markdown, expected_language="java")
result = replace_function_definitions_for_language(
function_names=["isEqual"],
optimized_code=optimized_code,
module_abspath=java_file,
project_root_path=tmp_path,
)
assert result is True
new_code = java_file.read_text(encoding="utf-8")
expected = """import java.util.Objects;
public class NullChecker {
public boolean isEqual(String s1, String s2) {
return Objects.equals(s1, s2);
}
}
"""
assert new_code == expected
def test_optimize_collection_creation(self, tmp_path: Path):
"""Test optimizing collection creation with factory methods."""
java_file = tmp_path / "CollectionFactory.java"
original_code = """import java.util.ArrayList;
import java.util.List;
public class CollectionFactory {
public List<String> createList() {
List<String> list = new ArrayList<>();
list.add("one");
list.add("two");
list.add("three");
return list;
}
}
"""
java_file.write_text(original_code, encoding="utf-8")
optimized_markdown = f"""```java:{java_file.relative_to(tmp_path)}
import java.util.ArrayList;
import java.util.List;
public class CollectionFactory {{
public List<String> createList() {{
return List.of("one", "two", "three");
}}
}}
```"""
optimized_code = CodeStringsMarkdown.parse_markdown_code(optimized_markdown, expected_language="java")
result = replace_function_definitions_for_language(
function_names=["createList"],
optimized_code=optimized_code,
module_abspath=java_file,
project_root_path=tmp_path,
)
assert result is True
new_code = java_file.read_text(encoding="utf-8")
expected = """import java.util.ArrayList;
import java.util.List;
public class CollectionFactory {
public List<String> createList() {
return List.of("one", "two", "three");
}
}
"""
assert new_code == expected
class TestMultipleClassesAndMethods:
"""Tests for files with multiple classes or multiple methods being optimized."""
def test_replace_method_in_first_class(self, tmp_path: Path):
"""Test replacing a method in the first class when multiple classes exist."""
java_file = tmp_path / "MultiClass.java"
original_code = """public class Calculator {
public int add(int a, int b) {
return a + b;
}
}
class Helper {
public int helper() {
return 0;
}
}
"""
java_file.write_text(original_code, encoding="utf-8")
optimized_markdown = f"""```java:{java_file.relative_to(tmp_path)}
public class Calculator {{
public int add(int a, int b) {{
return Math.addExact(a, b);
}}
}}
class Helper {{
public int helper() {{
return 0;
}}
}}
```"""
optimized_code = CodeStringsMarkdown.parse_markdown_code(optimized_markdown, expected_language="java")
result = replace_function_definitions_for_language(
function_names=["add"],
optimized_code=optimized_code,
module_abspath=java_file,
project_root_path=tmp_path,
)
assert result is True
new_code = java_file.read_text(encoding="utf-8")
expected = """public class Calculator {
public int add(int a, int b) {
return Math.addExact(a, b);
}
}
class Helper {
public int helper() {
return 0;
}
}
"""
assert new_code == expected
def test_replace_multiple_methods(self, tmp_path: Path):
"""Test replacing multiple methods in the same class."""
java_file = tmp_path / "MathOps.java"
original_code = """public class MathOps {
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
public int multiply(int a, int b) {
return a * b;
}
}
"""
java_file.write_text(original_code, encoding="utf-8")
optimized_markdown = f"""```java:{java_file.relative_to(tmp_path)}
public class MathOps {{
public int add(int a, int b) {{
return Math.addExact(a, b);
}}
public int subtract(int a, int b) {{
return Math.subtractExact(a, b);
}}
public int multiply(int a, int b) {{
return a * b;
}}
}}
```"""
optimized_code = CodeStringsMarkdown.parse_markdown_code(optimized_markdown, expected_language="java")
result = replace_function_definitions_for_language(
function_names=["add", "subtract"],
optimized_code=optimized_code,
module_abspath=java_file,
project_root_path=tmp_path,
)
assert result is True
new_code = java_file.read_text(encoding="utf-8")
expected = """public class MathOps {
public int add(int a, int b) {
return Math.addExact(a, b);
}
public int subtract(int a, int b) {
return Math.subtractExact(a, b);
}
public int multiply(int a, int b) {
return a * b;
}
}
"""
assert new_code == expected
class TestNestedClasses:
"""Tests for nested class scenarios."""
def test_replace_method_in_nested_class(self, tmp_path: Path):
"""Test replacing a method in a nested class."""
java_file = tmp_path / "Outer.java"
original_code = """public class Outer {
public int outerMethod() {
return 1;
}
public static class Inner {
public int innerMethod() {
return 2;
}
}
}
"""
java_file.write_text(original_code, encoding="utf-8")
optimized_markdown = f"""```java:{java_file.relative_to(tmp_path)}
public class Outer {{
public int outerMethod() {{
return 1;
}}
public static class Inner {{
public int innerMethod() {{
return 2 + 0;
}}
}}
}}
```"""
optimized_code = CodeStringsMarkdown.parse_markdown_code(optimized_markdown, expected_language="java")
result = replace_function_definitions_for_language(
function_names=["innerMethod"],
optimized_code=optimized_code,
module_abspath=java_file,
project_root_path=tmp_path,
)
assert result is True
new_code = java_file.read_text(encoding="utf-8")
expected = """public class Outer {
public int outerMethod() {
return 1;
}
public static class Inner {
public int innerMethod() {
return 2 + 0;
}
}
}
"""
assert new_code == expected
class TestPreservesStructure:
"""Tests that verify code structure is preserved during replacement."""
def test_preserves_fields_and_constructors(self, tmp_path: Path):
"""Test that fields and constructors are preserved."""
java_file = tmp_path / "Counter.java"
original_code = """public class Counter {
private int count;
private final int max;
public Counter(int max) {
this.count = 0;
this.max = max;
}
public int increment() {
if (count < max) {
count++;
}
return count;
}
}
"""
java_file.write_text(original_code, encoding="utf-8")
optimized_markdown = f"""```java:{java_file.relative_to(tmp_path)}
public class Counter {{
private int count;
private final int max;
public Counter(int max) {{
this.count = 0;
this.max = max;
}}
public int increment() {{
return count < max ? ++count : count;
}}
}}
```"""
optimized_code = CodeStringsMarkdown.parse_markdown_code(optimized_markdown, expected_language="java")
result = replace_function_definitions_for_language(
function_names=["increment"],
optimized_code=optimized_code,
module_abspath=java_file,
project_root_path=tmp_path,
)
assert result is True
new_code = java_file.read_text(encoding="utf-8")
expected = """public class Counter {
private int count;
private final int max;
public Counter(int max) {
this.count = 0;
this.max = max;
}
public int increment() {
return count < max ? ++count : count;
}
}
"""
assert new_code == expected
class TestEdgeCases:
"""Edge cases and error handling tests."""
def test_empty_optimized_code_returns_false(self, tmp_path: Path):
"""Test that empty optimized code returns False."""
java_file = tmp_path / "Empty.java"
original_code = """public class Empty {
public int getValue() {
return 42;
}
}
"""
java_file.write_text(original_code, encoding="utf-8")
optimized_markdown = """```java:Empty.java
```"""
optimized_code = CodeStringsMarkdown.parse_markdown_code(optimized_markdown, expected_language="java")
result = replace_function_definitions_for_language(
function_names=["getValue"],
optimized_code=optimized_code,
module_abspath=java_file,
project_root_path=tmp_path,
)
assert result is False
new_code = java_file.read_text(encoding="utf-8")
assert new_code == original_code
def test_function_not_found_returns_false(self, tmp_path: Path):
"""Test that function not found returns False."""
java_file = tmp_path / "NotFound.java"
original_code = """public class NotFound {
public int getValue() {
return 42;
}
}
"""