-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathtest_instrumentation.py
More file actions
2434 lines (2074 loc) · 83.4 KB
/
test_instrumentation.py
File metadata and controls
2434 lines (2074 loc) · 83.4 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 instrumentation.
Tests the instrumentation functions with exact string equality assertions
to ensure the generated code matches expected output exactly.
Also includes end-to-end execution tests that:
1. Instrument Java code
2. Execute with Maven
3. Parse JUnit XML and timing markers from stdout
4. Verify the parsed results are correct
"""
import os
import re
import shutil
import subprocess
from pathlib import Path
import pytest
# Set API key for tests that instantiate Optimizer
os.environ["CODEFLASH_API_KEY"] = "cf-test-key"
from codeflash.discovery.functions_to_optimize import FunctionToOptimize
from codeflash.languages.base import Language
from codeflash.languages.current import set_current_language
from codeflash.models.function_types import FunctionParent
from codeflash.languages.java.build_tools import find_maven_executable
from codeflash.languages.java.discovery import discover_functions_from_source
from codeflash.languages.java.instrumentation import (
_add_behavior_instrumentation,
_add_timing_instrumentation,
create_benchmark_test,
instrument_existing_test,
instrument_for_behavior,
instrument_for_benchmarking,
instrument_generated_java_test,
remove_instrumentation,
)
class TestInstrumentForBehavior:
"""Tests for instrument_for_behavior."""
def test_returns_source_unchanged(self):
"""Test that source is returned unchanged (Java uses JUnit pass/fail)."""
source = """public class Calculator {
public int add(int a, int b) {
return a + b;
}
}
"""
functions = discover_functions_from_source(source)
result = instrument_for_behavior(source, functions)
assert result == source
def test_no_functions_unchanged(self):
"""Test that source is unchanged when no functions provided."""
source = """public class Calculator {
public int add(int a, int b) {
return a + b;
}
}
"""
result = instrument_for_behavior(source, [])
assert result == source
class TestInstrumentForBenchmarking:
"""Tests for instrument_for_benchmarking."""
def test_returns_source_unchanged(self):
"""Test that source is returned unchanged (Java uses Maven Surefire timing)."""
source = """import org.junit.jupiter.api.Test;
public class CalculatorTest {
@Test
public void testAdd() {
Calculator calc = new Calculator();
assertEquals(4, calc.add(2, 2));
}
}
"""
func = FunctionToOptimize(
function_name="add",
file_path=Path("Calculator.java"),
starting_line=1,
ending_line=5,
parents=[],
is_method=True,
language="java",
)
result = instrument_for_benchmarking(source, func)
assert result == source
class TestInstrumentExistingTest:
"""Tests for instrument_existing_test with exact string equality."""
def test_instrument_behavior_mode_simple(self, tmp_path: Path):
"""Test instrumenting a simple test in behavior mode."""
test_file = tmp_path / "CalculatorTest.java"
source = """import org.junit.jupiter.api.Test;
public class CalculatorTest {
@Test
public void testAdd() {
Calculator calc = new Calculator();
assertEquals(4, calc.add(2, 2));
}
}
"""
test_file.write_text(source)
func = FunctionToOptimize(
function_name="add",
file_path=tmp_path / "Calculator.java",
starting_line=1,
ending_line=5,
parents=[],
is_method=True,
language="java",
)
success, result = instrument_existing_test(
test_file,
call_positions=[],
function_to_optimize=func,
tests_project_root=tmp_path,
mode="behavior",
)
assert success is True
# Behavior mode now adds SQLite instrumentation
# Verify key elements are present
assert "import java.sql.Connection;" in result
assert "import java.sql.DriverManager;" in result
assert "import java.sql.PreparedStatement;" in result
# Note: java.sql.Statement is used fully qualified to avoid conflicts with other Statement classes
assert "java.sql.Statement" in result
assert "class CalculatorTest__perfinstrumented" in result
assert "CODEFLASH_OUTPUT_FILE" in result
assert "CREATE TABLE IF NOT EXISTS test_results" in result
assert "INSERT INTO test_results VALUES" in result
assert "_cf_loop1" in result
assert "_cf_iter1" in result
assert "System.nanoTime()" in result
assert "com.codeflash.Serializer.serialize((Object)" in result
def test_instrument_behavior_mode_assert_throws_expression_lambda(self, tmp_path: Path):
"""Test that assertThrows expression lambdas are not broken by behavior instrumentation.
When a target function call is inside an expression lambda (e.g., () -> Fibonacci.fibonacci(-1)),
the instrumentation must NOT wrap it in a variable assignment, as that would turn
the void-compatible lambda into a value-returning lambda and break compilation.
"""
test_file = tmp_path / "FibonacciTest.java"
source = """import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class FibonacciTest {
@Test
void testNegativeInput_ThrowsIllegalArgumentException() {
assertThrows(IllegalArgumentException.class, () -> Fibonacci.fibonacci(-1));
}
@Test
void testZeroInput_ReturnsZero() {
assertEquals(0L, Fibonacci.fibonacci(0));
}
}
"""
test_file.write_text(source)
func = FunctionToOptimize(
function_name="fibonacci",
file_path=tmp_path / "Fibonacci.java",
starting_line=1,
ending_line=10,
parents=[],
is_method=True,
language="java",
)
success, result = instrument_existing_test(
test_file,
call_positions=[],
function_to_optimize=func,
tests_project_root=tmp_path,
mode="behavior",
)
assert success is True
# The assertThrows lambda line should remain unchanged (not wrapped in variable assignment)
assert "() -> Fibonacci.fibonacci(-1)" in result
# The non-lambda call should still be wrapped
assert "_cf_result" in result
def test_instrument_behavior_mode_assert_throws_block_lambda(self, tmp_path: Path):
"""Test that assertThrows block lambdas are not broken by behavior instrumentation.
When a target function call is inside a block lambda (e.g., () -> { func(); }),
the instrumentation must NOT wrap it in a variable assignment.
"""
test_file = tmp_path / "FibonacciTest.java"
source = """import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class FibonacciTest {
@Test
void testNegativeInput_ThrowsIllegalArgumentException() {
assertThrows(IllegalArgumentException.class, () -> {
Fibonacci.fibonacci(-1);
});
}
@Test
void testZeroInput_ReturnsZero() {
assertEquals(0L, Fibonacci.fibonacci(0));
}
}
"""
test_file.write_text(source)
func = FunctionToOptimize(
function_name="fibonacci",
file_path=tmp_path / "Fibonacci.java",
starting_line=1,
ending_line=10,
parents=[],
is_method=True,
language="java",
)
success, result = instrument_existing_test(
test_file,
call_positions=[],
function_to_optimize=func,
tests_project_root=tmp_path,
mode="behavior",
)
assert success is True
assert "Fibonacci.fibonacci(-1);" in result
assert "() -> {" in result
lines_with_cf_result = [l for l in result.split("\n") if "var _cf_result" in l and "Fibonacci.fibonacci(0)" in l]
assert len(lines_with_cf_result) > 0, "Non-lambda call to fibonacci(0) should be wrapped"
def test_instrument_performance_mode_simple(self, tmp_path: Path):
"""Test instrumenting a simple test in performance mode with inner loop."""
test_file = tmp_path / "CalculatorTest.java"
source = """import org.junit.jupiter.api.Test;
public class CalculatorTest {
@Test
public void testAdd() {
Calculator calc = new Calculator();
assertEquals(4, calc.add(2, 2));
}
}
"""
test_file.write_text(source)
func = FunctionToOptimize(
function_name="add",
file_path=tmp_path / "Calculator.java",
starting_line=1,
ending_line=5,
parents=[],
is_method=True,
language="java",
)
success, result = instrument_existing_test(
test_file,
call_positions=[],
function_to_optimize=func,
tests_project_root=tmp_path,
mode="performance",
)
expected = """import org.junit.jupiter.api.Test;
public class CalculatorTest__perfonlyinstrumented {
@Test
public void testAdd() {
// Codeflash timing instrumentation with inner loop for JIT warmup
int _cf_loop1 = Integer.parseInt(System.getenv("CODEFLASH_LOOP_INDEX"));
int _cf_innerIterations1 = Integer.parseInt(System.getenv().getOrDefault("CODEFLASH_INNER_ITERATIONS", "100"));
String _cf_mod1 = "CalculatorTest";
String _cf_cls1 = "CalculatorTest";
String _cf_fn1 = "add";
for (int _cf_i1 = 0; _cf_i1 < _cf_innerIterations1; _cf_i1++) {
System.out.println("!$######" + _cf_mod1 + ":" + _cf_cls1 + ":" + _cf_fn1 + ":" + _cf_loop1 + ":" + _cf_i1 + "######$!");
long _cf_start1 = System.nanoTime();
try {
Calculator calc = new Calculator();
assertEquals(4, calc.add(2, 2));
} finally {
long _cf_end1 = System.nanoTime();
long _cf_dur1 = _cf_end1 - _cf_start1;
System.out.println("!######" + _cf_mod1 + ":" + _cf_cls1 + ":" + _cf_fn1 + ":" + _cf_loop1 + ":" + _cf_i1 + ":" + _cf_dur1 + "######!");
}
}
}
}
"""
assert success is True
assert result == expected
def test_instrument_performance_mode_multiple_tests(self, tmp_path: Path):
"""Test instrumenting multiple test methods in performance mode with inner loop."""
test_file = tmp_path / "MathTest.java"
source = """import org.junit.jupiter.api.Test;
public class MathTest {
@Test
public void testAdd() {
assertEquals(4, add(2, 2));
}
@Test
public void testSubtract() {
assertEquals(0, subtract(2, 2));
}
}
"""
test_file.write_text(source)
func = FunctionToOptimize(
function_name="calculate",
file_path=tmp_path / "Math.java",
starting_line=1,
ending_line=5,
parents=[],
is_method=True,
language="java",
)
success, result = instrument_existing_test(
test_file,
call_positions=[],
function_to_optimize=func,
tests_project_root=tmp_path,
mode="performance",
)
expected = """import org.junit.jupiter.api.Test;
public class MathTest__perfonlyinstrumented {
@Test
public void testAdd() {
// Codeflash timing instrumentation with inner loop for JIT warmup
int _cf_loop1 = Integer.parseInt(System.getenv("CODEFLASH_LOOP_INDEX"));
int _cf_innerIterations1 = Integer.parseInt(System.getenv().getOrDefault("CODEFLASH_INNER_ITERATIONS", "100"));
String _cf_mod1 = "MathTest";
String _cf_cls1 = "MathTest";
String _cf_fn1 = "calculate";
for (int _cf_i1 = 0; _cf_i1 < _cf_innerIterations1; _cf_i1++) {
System.out.println("!$######" + _cf_mod1 + ":" + _cf_cls1 + ":" + _cf_fn1 + ":" + _cf_loop1 + ":" + _cf_i1 + "######$!");
long _cf_start1 = System.nanoTime();
try {
assertEquals(4, add(2, 2));
} finally {
long _cf_end1 = System.nanoTime();
long _cf_dur1 = _cf_end1 - _cf_start1;
System.out.println("!######" + _cf_mod1 + ":" + _cf_cls1 + ":" + _cf_fn1 + ":" + _cf_loop1 + ":" + _cf_i1 + ":" + _cf_dur1 + "######!");
}
}
}
@Test
public void testSubtract() {
// Codeflash timing instrumentation with inner loop for JIT warmup
int _cf_loop2 = Integer.parseInt(System.getenv("CODEFLASH_LOOP_INDEX"));
int _cf_innerIterations2 = Integer.parseInt(System.getenv().getOrDefault("CODEFLASH_INNER_ITERATIONS", "100"));
String _cf_mod2 = "MathTest";
String _cf_cls2 = "MathTest";
String _cf_fn2 = "calculate";
for (int _cf_i2 = 0; _cf_i2 < _cf_innerIterations2; _cf_i2++) {
System.out.println("!$######" + _cf_mod2 + ":" + _cf_cls2 + ":" + _cf_fn2 + ":" + _cf_loop2 + ":" + _cf_i2 + "######$!");
long _cf_start2 = System.nanoTime();
try {
assertEquals(0, subtract(2, 2));
} finally {
long _cf_end2 = System.nanoTime();
long _cf_dur2 = _cf_end2 - _cf_start2;
System.out.println("!######" + _cf_mod2 + ":" + _cf_cls2 + ":" + _cf_fn2 + ":" + _cf_loop2 + ":" + _cf_i2 + ":" + _cf_dur2 + "######!");
}
}
}
}
"""
assert success is True
assert result == expected
def test_instrument_preserves_annotations(self, tmp_path: Path):
"""Test that annotations other than @Test are preserved with inner loop."""
test_file = tmp_path / "ServiceTest.java"
source = """import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Disabled;
public class ServiceTest {
@Test
@DisplayName("Test service call")
public void testService() {
service.call();
}
@Disabled
@Test
public void testDisabled() {
service.other();
}
}
"""
test_file.write_text(source)
func = FunctionToOptimize(
function_name="call",
file_path=tmp_path / "Service.java",
starting_line=1,
ending_line=5,
parents=[],
is_method=True,
language="java",
)
success, result = instrument_existing_test(
test_file,
call_positions=[],
function_to_optimize=func,
tests_project_root=tmp_path,
mode="performance",
)
expected = """import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Disabled;
public class ServiceTest__perfonlyinstrumented {
@Test
@DisplayName("Test service call")
public void testService() {
// Codeflash timing instrumentation with inner loop for JIT warmup
int _cf_loop1 = Integer.parseInt(System.getenv("CODEFLASH_LOOP_INDEX"));
int _cf_innerIterations1 = Integer.parseInt(System.getenv().getOrDefault("CODEFLASH_INNER_ITERATIONS", "100"));
String _cf_mod1 = "ServiceTest";
String _cf_cls1 = "ServiceTest";
String _cf_fn1 = "call";
for (int _cf_i1 = 0; _cf_i1 < _cf_innerIterations1; _cf_i1++) {
System.out.println("!$######" + _cf_mod1 + ":" + _cf_cls1 + ":" + _cf_fn1 + ":" + _cf_loop1 + ":" + _cf_i1 + "######$!");
long _cf_start1 = System.nanoTime();
try {
service.call();
} finally {
long _cf_end1 = System.nanoTime();
long _cf_dur1 = _cf_end1 - _cf_start1;
System.out.println("!######" + _cf_mod1 + ":" + _cf_cls1 + ":" + _cf_fn1 + ":" + _cf_loop1 + ":" + _cf_i1 + ":" + _cf_dur1 + "######!");
}
}
}
@Disabled
@Test
public void testDisabled() {
// Codeflash timing instrumentation with inner loop for JIT warmup
int _cf_loop2 = Integer.parseInt(System.getenv("CODEFLASH_LOOP_INDEX"));
int _cf_innerIterations2 = Integer.parseInt(System.getenv().getOrDefault("CODEFLASH_INNER_ITERATIONS", "100"));
String _cf_mod2 = "ServiceTest";
String _cf_cls2 = "ServiceTest";
String _cf_fn2 = "call";
for (int _cf_i2 = 0; _cf_i2 < _cf_innerIterations2; _cf_i2++) {
System.out.println("!$######" + _cf_mod2 + ":" + _cf_cls2 + ":" + _cf_fn2 + ":" + _cf_loop2 + ":" + _cf_i2 + "######$!");
long _cf_start2 = System.nanoTime();
try {
service.other();
} finally {
long _cf_end2 = System.nanoTime();
long _cf_dur2 = _cf_end2 - _cf_start2;
System.out.println("!######" + _cf_mod2 + ":" + _cf_cls2 + ":" + _cf_fn2 + ":" + _cf_loop2 + ":" + _cf_i2 + ":" + _cf_dur2 + "######!");
}
}
}
}
"""
assert success is True
assert result == expected
def test_missing_file(self, tmp_path: Path):
"""Test handling missing test file."""
test_file = tmp_path / "NonExistent.java"
func = FunctionToOptimize(
function_name="add",
file_path=tmp_path / "Calculator.java",
starting_line=1,
ending_line=5,
parents=[],
is_method=True,
language="java",
)
success, result = instrument_existing_test(
test_file,
call_positions=[],
function_to_optimize=func,
tests_project_root=tmp_path,
mode="behavior",
)
assert success is False
class TestKryoSerializerUsage:
"""Tests for Kryo Serializer usage in behavior mode."""
def test_serializer_used_for_return_values(self):
"""Test that captured return values use com.codeflash.Serializer.serialize()."""
source = """import org.junit.jupiter.api.Test;
public class MyTest {
@Test
public void testFoo() {
assertEquals(0, obj.foo());
}
}
"""
result = _add_behavior_instrumentation(source, "MyTest", "foo")
assert "com.codeflash.Serializer.serialize((Object)" in result
# Should NOT use old _cfSerialize helper
assert "_cfSerialize" not in result
def test_byte_array_result_variable(self):
"""Test that the serialized result variable is byte[] not String."""
source = """import org.junit.jupiter.api.Test;
public class MyTest {
@Test
public void testFoo() {
assertEquals(0, obj.foo());
}
}
"""
result = _add_behavior_instrumentation(source, "MyTest", "foo")
assert "byte[] _cf_serializedResult" in result
assert "String _cf_serializedResult" not in result
def test_blob_column_in_schema(self):
"""Test that the SQLite schema uses BLOB for return_value column."""
source = """import org.junit.jupiter.api.Test;
public class MyTest {
@Test
public void testFoo() {
assertEquals(0, obj.foo());
}
}
"""
result = _add_behavior_instrumentation(source, "MyTest", "foo")
assert "return_value BLOB" in result
assert "return_value TEXT" not in result
def test_set_bytes_for_blob_write(self):
"""Test that setBytes is used to write BLOB data to SQLite."""
source = """import org.junit.jupiter.api.Test;
public class MyTest {
@Test
public void testFoo() {
assertEquals(0, obj.foo());
}
}
"""
result = _add_behavior_instrumentation(source, "MyTest", "foo")
assert "setBytes(8, _cf_serializedResult" in result
# Should NOT use setString for return value
assert "setString(8, _cf_serializedResult" not in result
def test_no_inline_helper_injected(self):
"""Test that no inline _cfSerialize helper method is injected."""
source = """import org.junit.jupiter.api.Test;
public class MyTest {
@Test
public void testFoo() {
assertEquals(0, obj.foo());
}
}
"""
result = _add_behavior_instrumentation(source, "MyTest", "foo")
assert "private static String _cfSerialize" not in result
def test_serializer_not_used_in_performance_mode(self):
"""Test that Serializer is NOT used in performance mode (only behavior)."""
source = """import org.junit.jupiter.api.Test;
public class MyTest {
@Test
public void testFoo() {
assertEquals(0, obj.foo());
}
}
"""
result = _add_timing_instrumentation(source, "MyTest", "foo")
assert "Serializer.serialize" not in result
assert "_cfSerialize" not in result
class TestAddTimingInstrumentation:
"""Tests for _add_timing_instrumentation helper function with inner loop."""
def test_single_test_method(self):
"""Test timing instrumentation for a single test method with inner loop."""
source = """public class SimpleTest {
@Test
public void testSomething() {
doSomething();
}
}
"""
result = _add_timing_instrumentation(source, "SimpleTest", "targetFunc")
expected = """public class SimpleTest {
@Test
public void testSomething() {
// Codeflash timing instrumentation with inner loop for JIT warmup
int _cf_loop1 = Integer.parseInt(System.getenv("CODEFLASH_LOOP_INDEX"));
int _cf_innerIterations1 = Integer.parseInt(System.getenv().getOrDefault("CODEFLASH_INNER_ITERATIONS", "100"));
String _cf_mod1 = "SimpleTest";
String _cf_cls1 = "SimpleTest";
String _cf_fn1 = "targetFunc";
for (int _cf_i1 = 0; _cf_i1 < _cf_innerIterations1; _cf_i1++) {
System.out.println("!$######" + _cf_mod1 + ":" + _cf_cls1 + ":" + _cf_fn1 + ":" + _cf_loop1 + ":" + _cf_i1 + "######$!");
long _cf_start1 = System.nanoTime();
try {
doSomething();
} finally {
long _cf_end1 = System.nanoTime();
long _cf_dur1 = _cf_end1 - _cf_start1;
System.out.println("!######" + _cf_mod1 + ":" + _cf_cls1 + ":" + _cf_fn1 + ":" + _cf_loop1 + ":" + _cf_i1 + ":" + _cf_dur1 + "######!");
}
}
}
}
"""
assert result == expected
def test_multiple_test_methods(self):
"""Test timing instrumentation for multiple test methods with inner loop."""
source = """public class MultiTest {
@Test
public void testFirst() {
first();
}
@Test
public void testSecond() {
second();
}
}
"""
result = _add_timing_instrumentation(source, "MultiTest", "func")
expected = """public class MultiTest {
@Test
public void testFirst() {
// Codeflash timing instrumentation with inner loop for JIT warmup
int _cf_loop1 = Integer.parseInt(System.getenv("CODEFLASH_LOOP_INDEX"));
int _cf_innerIterations1 = Integer.parseInt(System.getenv().getOrDefault("CODEFLASH_INNER_ITERATIONS", "100"));
String _cf_mod1 = "MultiTest";
String _cf_cls1 = "MultiTest";
String _cf_fn1 = "func";
for (int _cf_i1 = 0; _cf_i1 < _cf_innerIterations1; _cf_i1++) {
System.out.println("!$######" + _cf_mod1 + ":" + _cf_cls1 + ":" + _cf_fn1 + ":" + _cf_loop1 + ":" + _cf_i1 + "######$!");
long _cf_start1 = System.nanoTime();
try {
first();
} finally {
long _cf_end1 = System.nanoTime();
long _cf_dur1 = _cf_end1 - _cf_start1;
System.out.println("!######" + _cf_mod1 + ":" + _cf_cls1 + ":" + _cf_fn1 + ":" + _cf_loop1 + ":" + _cf_i1 + ":" + _cf_dur1 + "######!");
}
}
}
@Test
public void testSecond() {
// Codeflash timing instrumentation with inner loop for JIT warmup
int _cf_loop2 = Integer.parseInt(System.getenv("CODEFLASH_LOOP_INDEX"));
int _cf_innerIterations2 = Integer.parseInt(System.getenv().getOrDefault("CODEFLASH_INNER_ITERATIONS", "100"));
String _cf_mod2 = "MultiTest";
String _cf_cls2 = "MultiTest";
String _cf_fn2 = "func";
for (int _cf_i2 = 0; _cf_i2 < _cf_innerIterations2; _cf_i2++) {
System.out.println("!$######" + _cf_mod2 + ":" + _cf_cls2 + ":" + _cf_fn2 + ":" + _cf_loop2 + ":" + _cf_i2 + "######$!");
long _cf_start2 = System.nanoTime();
try {
second();
} finally {
long _cf_end2 = System.nanoTime();
long _cf_dur2 = _cf_end2 - _cf_start2;
System.out.println("!######" + _cf_mod2 + ":" + _cf_cls2 + ":" + _cf_fn2 + ":" + _cf_loop2 + ":" + _cf_i2 + ":" + _cf_dur2 + "######!");
}
}
}
}
"""
assert result == expected
def test_timing_markers_format(self):
"""Test that timing markers have the correct format with inner loop."""
source = """public class MarkerTest {
@Test
public void testMarkers() {
action();
}
}
"""
result = _add_timing_instrumentation(source, "TestClass", "targetMethod")
expected = """public class MarkerTest {
@Test
public void testMarkers() {
// Codeflash timing instrumentation with inner loop for JIT warmup
int _cf_loop1 = Integer.parseInt(System.getenv("CODEFLASH_LOOP_INDEX"));
int _cf_innerIterations1 = Integer.parseInt(System.getenv().getOrDefault("CODEFLASH_INNER_ITERATIONS", "100"));
String _cf_mod1 = "TestClass";
String _cf_cls1 = "TestClass";
String _cf_fn1 = "targetMethod";
for (int _cf_i1 = 0; _cf_i1 < _cf_innerIterations1; _cf_i1++) {
System.out.println("!$######" + _cf_mod1 + ":" + _cf_cls1 + ":" + _cf_fn1 + ":" + _cf_loop1 + ":" + _cf_i1 + "######$!");
long _cf_start1 = System.nanoTime();
try {
action();
} finally {
long _cf_end1 = System.nanoTime();
long _cf_dur1 = _cf_end1 - _cf_start1;
System.out.println("!######" + _cf_mod1 + ":" + _cf_cls1 + ":" + _cf_fn1 + ":" + _cf_loop1 + ":" + _cf_i1 + ":" + _cf_dur1 + "######!");
}
}
}
}
"""
assert result == expected
class TestCreateBenchmarkTest:
"""Tests for create_benchmark_test."""
def test_create_benchmark(self):
"""Test creating a benchmark test."""
func = FunctionToOptimize(
function_name="add",
file_path=Path("Calculator.java"),
starting_line=1,
ending_line=5,
parents=[],
is_method=True,
language="java",
)
result = create_benchmark_test(
func,
test_setup_code="Calculator calc = new Calculator();",
invocation_code="calc.add(2, 2)",
iterations=1000,
)
expected = """
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;
/**
* Benchmark test for add.
* Generated by CodeFlash.
*/
public class TargetBenchmark {
@Test
@DisplayName("Benchmark add")
public void benchmarkAdd() {
Calculator calc = new Calculator();
// Warmup phase
for (int i = 0; i < 100; i++) {
calc.add(2, 2);
}
// Measurement phase
long startTime = System.nanoTime();
for (int i = 0; i < 1000; i++) {
calc.add(2, 2);
}
long endTime = System.nanoTime();
long totalNanos = endTime - startTime;
long avgNanos = totalNanos / 1000;
System.out.println("CODEFLASH_BENCHMARK:add:total_ns=" + totalNanos + ",avg_ns=" + avgNanos + ",iterations=1000");
}
}
"""
assert result == expected
def test_create_benchmark_different_iterations(self):
"""Test benchmark with different iteration count."""
func = FunctionToOptimize(
function_name="multiply",
file_path=Path("Math.java"),
starting_line=1,
ending_line=3,
parents=[],
is_method=True,
language="java",
)
result = create_benchmark_test(
func,
test_setup_code="",
invocation_code="multiply(5, 3)",
iterations=5000,
)
# Note: Empty test_setup_code still has 8-space indentation on its line
expected = (
"\n"
"import org.junit.jupiter.api.Test;\n"
"import org.junit.jupiter.api.DisplayName;\n"
"\n"
"/**\n"
" * Benchmark test for multiply.\n"
" * Generated by CodeFlash.\n"
" */\n"
"public class TargetBenchmark {\n"
"\n"
" @Test\n"
" @DisplayName(\"Benchmark multiply\")\n"
" public void benchmarkMultiply() {\n"
" \n" # Empty test_setup_code with 8-space indent
"\n"
" // Warmup phase\n"
" for (int i = 0; i < 500; i++) {\n"
" multiply(5, 3);\n"
" }\n"
"\n"
" // Measurement phase\n"
" long startTime = System.nanoTime();\n"
" for (int i = 0; i < 5000; i++) {\n"
" multiply(5, 3);\n"
" }\n"
" long endTime = System.nanoTime();\n"
"\n"
" long totalNanos = endTime - startTime;\n"
" long avgNanos = totalNanos / 5000;\n"
"\n"
" System.out.println(\"CODEFLASH_BENCHMARK:multiply:total_ns=\" + totalNanos + \",avg_ns=\" + avgNanos + \",iterations=5000\");\n"
" }\n"
"}\n"
)
assert result == expected
class TestRemoveInstrumentation:
"""Tests for remove_instrumentation."""
def test_returns_source_unchanged(self):
"""Test that source is returned unchanged (no-op for Java)."""
source = """import com.codeflash.CodeFlash;
import org.junit.jupiter.api.Test;
public class Test {}
"""
result = remove_instrumentation(source)
assert result == source
def test_preserves_regular_code(self):
"""Test that regular code is preserved."""
source = """public class Calculator {
public int add(int a, int b) {
return a + b;
}
}
"""
result = remove_instrumentation(source)
assert result == source
class TestInstrumentGeneratedJavaTest:
"""Tests for instrument_generated_java_test."""
def test_instrument_generated_test_behavior_mode(self):
"""Test instrumenting generated test in behavior mode.
Behavior mode should:
1. Remove assertions containing the target function call
2. Capture the function return value instead
3. Rename the class with __perfinstrumented suffix
4. Add SQLite behavior instrumentation to capture return values
"""
test_code = """import org.junit.jupiter.api.Test;
public class CalculatorTest {
@Test
public void testAdd() {
assertEquals(4, new Calculator().add(2, 2));
}
}
"""
result = instrument_generated_java_test(
test_code,
function_name="add",
qualified_name="Calculator.add",
mode="behavior",
)
# Behavior mode transforms assertions, renames class, and adds SQLite instrumentation
assert "class CalculatorTest__perfinstrumented" in result
assert "import java.sql.Connection;" in result
assert "import java.sql.DriverManager;" in result
assert "import java.sql.PreparedStatement;" in result
assert "CODEFLASH_OUTPUT_FILE" in result
assert "CREATE TABLE IF NOT EXISTS test_results" in result
assert "INSERT INTO test_results VALUES" in result
assert "_cf_serializedResult1" in result
assert "com.codeflash.Serializer.serialize" in result
def test_instrument_generated_test_performance_mode(self):
"""Test instrumenting generated test in performance mode with inner loop."""
test_code = """import org.junit.jupiter.api.Test;
public class GeneratedTest {
@Test
public void testMethod() {
target.method();
}
}
"""
result = instrument_generated_java_test(
test_code,
function_name="method",
qualified_name="Target.method",
mode="performance",
)
expected = """import org.junit.jupiter.api.Test;
public class GeneratedTest__perfonlyinstrumented {
@Test
public void testMethod() {
// Codeflash timing instrumentation with inner loop for JIT warmup
int _cf_loop1 = Integer.parseInt(System.getenv("CODEFLASH_LOOP_INDEX"));
int _cf_innerIterations1 = Integer.parseInt(System.getenv().getOrDefault("CODEFLASH_INNER_ITERATIONS", "100"));
String _cf_mod1 = "GeneratedTest";
String _cf_cls1 = "GeneratedTest";
String _cf_fn1 = "method";
for (int _cf_i1 = 0; _cf_i1 < _cf_innerIterations1; _cf_i1++) {
System.out.println("!$######" + _cf_mod1 + ":" + _cf_cls1 + ":" + _cf_fn1 + ":" + _cf_loop1 + ":" + _cf_i1 + "######$!");
long _cf_start1 = System.nanoTime();
try {
target.method();
} finally {
long _cf_end1 = System.nanoTime();
long _cf_dur1 = _cf_end1 - _cf_start1;
System.out.println("!######" + _cf_mod1 + ":" + _cf_cls1 + ":" + _cf_fn1 + ":" + _cf_loop1 + ":" + _cf_i1 + ":" + _cf_dur1 + "######!");
}
}
}
}
"""
assert result == expected
class TestTimingMarkerParsing:
"""Tests for parsing timing markers from stdout."""
def test_timing_markers_can_be_parsed(self):
"""Test that generated timing markers can be parsed with the standard regex."""
# Simulate stdout from instrumented test
stdout = """