-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenhanced_mcts_test_generator.py
More file actions
4217 lines (3461 loc) · 186 KB
/
enhanced_mcts_test_generator.py
File metadata and controls
4217 lines (3461 loc) · 186 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
#!/usr/bin/env python3
"""
Enhanced MCTS Test Generator
This module provides an enhanced Monte Carlo Tree Search (MCTS) implementation
for test generation. It serves as a base class for more specialized implementations
such as the Failure-Aware MCTS.
"""
import os
import re
import time
import random
import logging
import traceback
from collections import defaultdict
# Import modules for test validation and LLM interactions
from feedback import (
save_test_code, generate_test_summary,read_source_code,
find_source_code, run_tests_with_jacoco, get_coverage_percentage,
call_anthropic_api, call_gpt_api, call_deepseek_api, extract_java_code
)
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("enhanced_mcts_test_generator")
class TestMethodExtractor:
"""
Utility class for extracting test methods from test code
"""
@staticmethod
def extract_methods(test_code):
"""
Extract test methods from the test code
Parameters:
test_code (str): Test code
Returns:
list: Extracted test methods
"""
methods = []
# Pattern to match test methods
method_pattern = r'@Test\s+(?:@\w+\s+)*public\s+void\s+(\w+)\s*\([^)]*\)\s*(?:throws\s+[\w,\s.]+\s*)?\{([\s\S]*?)(?=\s*@Test|\s*private|\s*public|\s*protected|\s*\}[\s\n]*(?:\}|\Z))'
# Find all matches
matches = re.finditer(method_pattern, test_code)
for match in matches:
method_name = match.group(1)
method_body = match.group(2)
# Create method info
method = {
"name": method_name,
"code": f"@Test\npublic void {method_name}() {{\n{method_body}\n}}",
"body": method_body
}
methods.append(method)
return methods
@staticmethod
def __init__(self):
# Common imports needed for JUnit tests
self.standard_imports = [
"import org.junit.jupiter.api.Test;",
"import org.junit.jupiter.api.BeforeEach;",
"import org.junit.jupiter.api.AfterEach;",
"import org.junit.jupiter.api.DisplayName;",
"import static org.junit.jupiter.api.Assertions.*;",
"import java.util.List;",
"import java.util.ArrayList;",
"import java.util.Arrays;",
"import java.util.Properties;",
"import java.util.Iterator;",
"import java.util.ListIterator;",
"import java.time.Duration;",
"import java.nio.charset.StandardCharsets;"
]
# Patterns for common issues
self.issue_patterns = {
"method_not_found": re.compile(r"cannot find symbol.*method\s+(\w+)"),
"class_not_found": re.compile(r"cannot find symbol.*class\s+(\w+)"),
"var_not_found": re.compile(r"cannot find symbol.*variable\s+(\w+)"),
"private_access": re.compile(r"(\w+).*has private access"),
"unreported_exception": re.compile(r"unreported exception\s+([\w.]+)"),
"incompatible_types": re.compile(r"incompatible types:\s+(.*)\s+cannot be converted to\s+(.*)"),
"repeat_method": re.compile(r"cannot find symbol.*method repeat\(int\)"),
"missing_bracket": re.compile(r"(.*expected.*})|(.*expected.*)"),
}
# Cache of previously successful fixes
self.fix_cache = {}
def validate_and_fix(self, test_code, error_messages, class_name, package_name, source_code=None):
"""
Validate test code and fix common issues
Parameters:
test_code (str): Test code to validate and fix
error_messages (list): List of error messages from previous compilation
class_name (str): Name of the class being tested
package_name (str): Package name
source_code (str): Source code of the class being tested
Returns:
str: Fixed test code
"""
if not test_code or not class_name:
return test_code
# Apply cached fixes for this class if available
cache_key = f"{package_name}.{class_name}"
if cache_key in self.fix_cache:
for issue, fix in self.fix_cache[cache_key].items():
test_code = self.apply_fix(test_code, issue, fix)
# Fix package and imports
test_code = self.fix_package_and_imports(test_code, package_name)
# Fix common Java syntax issues
# test_code = self.fix_java_syntax(test_code)
# Fix specific issues based on error messages
if error_messages:
test_code = self.fix_from_errors(test_code, error_messages, class_name, source_code)
# Fix common test structure issues
test_code = self.fix_test_structure(test_code, class_name)
# Fix access modifier issues
if source_code:
test_code = self.fix_access_modifiers(test_code, class_name, source_code)
return test_code
def apply_fix(self, test_code, issue, fix):
"""Apply a specific fix to the test code"""
if issue == "add_imports":
for import_stmt in fix:
if import_stmt not in test_code:
# Find where to add the import - after package or after existing imports
if "package " in test_code:
package_end = test_code.find(';', test_code.find("package ")) + 1
if "import " in test_code[:package_end + 100]:
# Add after last import
last_import = test_code.rfind(';', 0, package_end + 200)
test_code = test_code[:last_import+1] + "\n" + import_stmt + test_code[last_import+1:]
else:
# Add after package
test_code = test_code[:package_end] + "\n\n" + import_stmt + test_code[package_end:]
else:
# Add at the beginning
test_code = import_stmt + "\n" + test_code
elif issue == "replace_pattern":
pattern, replacement = fix
test_code = re.sub(pattern, replacement, test_code)
return test_code
def fix_package_and_imports(self, test_code, package_name):
"""Fix package declaration and ensure necessary imports"""
# Check and fix package declaration
if "package " not in test_code and package_name:
test_code = f"package {package_name};\n\n{test_code}"
# Add standard imports if not present
for import_stmt in self.standard_imports:
if import_stmt not in test_code:
# Find where to add imports - after package or at the beginning
if "package " in test_code:
package_end = test_code.find(';', test_code.find("package ")) + 1
if "import " in test_code[:package_end + 100]:
# Don't add, as there are already imports and we might duplicate
pass
else:
# Add after package
test_code = test_code[:package_end] + "\n\n" + import_stmt + test_code[package_end:]
else:
# Add at the beginning
test_code = import_stmt + "\n" + test_code
return test_code
def fix_java_syntax(self, test_code):
"""Fix common Java syntax issues"""
# Check for missing closing braces
open_braces = test_code.count('{')
close_braces = test_code.count('}')
if open_braces > close_braces:
# Add missing closing braces
test_code += "}" * (open_braces - close_braces)
# Replace String.repeat with alternate implementation
if "repeat(" in test_code:
test_code = re.sub(r'(["\w]+)\.repeat\((\d+)\)',
r'String.join("", java.util.Collections.nCopies(\2, \1))',
test_code)
return test_code
def fix_from_errors(self, test_code, error_messages, class_name, source_code):
"""Fix issues based on specific error messages"""
for error in error_messages:
# Fix missing import issues
if "cannot find symbol" in error and "class" in error:
for pattern in ["class ListIterator", "class Arrays"]:
if pattern in error:
if pattern == "class ListIterator":
if "import java.util.ListIterator;" not in test_code:
idx = test_code.find("import ")
if idx >= 0:
end_idx = test_code.find(";", idx) + 1
test_code = test_code[:end_idx] + "\nimport java.util.ListIterator;" + test_code[end_idx:]
else:
test_code = "import java.util.ListIterator;\n" + test_code
elif pattern == "class Arrays":
if "import java.util.Arrays;" not in test_code:
idx = test_code.find("import ")
if idx >= 0:
end_idx = test_code.find(";", idx) + 1
test_code = test_code[:end_idx] + "\nimport java.util.Arrays;" + test_code[end_idx:]
else:
test_code = "import java.util.Arrays;\n" + test_code
# Fix private access issues
if "has private access" in error:
match = self.issue_patterns["private_access"].search(error)
if match:
private_method = match.group(1)
# Instead of trying to access private method directly, remove it
pattern = rf'(\s+|\.)({private_method}\s*\([^)]*\))'
if re.search(pattern, test_code):
# Find which test methods use this private method
test_methods_with_private = []
method_pattern = r'@Test[^{]*{[^}]*' + re.escape(private_method)
for match in re.finditer(method_pattern, test_code, re.DOTALL):
# Extract the method
method_text = test_code[match.start():match.end()]
method_name = re.search(r'void\s+(\w+)\s*\(', method_text)
if method_name:
test_methods_with_private.append(method_name.group(1))
# Remove problematic test methods
for method_name in test_methods_with_private:
method_pattern = rf'@Test[^{{]*void\s+{method_name}\s*\([^{{]*{{[^}}]*}}'
test_code = re.sub(method_pattern, '', test_code, flags=re.DOTALL)
# Fix unreported exception issues
if "unreported exception" in error:
match = self.issue_patterns["unreported_exception"].search(error)
if match:
exception_type = match.group(1)
# Find methods that need to declare this exception
method_pattern = r'(@Test[^{]*void\s+\w+\s*\([^)]*\))\s*{'
test_code = re.sub(method_pattern, rf'\1 throws {exception_type} {{', test_code)
return test_code
def fix_test_structure(self, test_code, class_name):
"""Fix common test structure issues"""
# Ensure the class has the right name pattern
test_class_name = f"{class_name}Test"
class_pattern = r'class\s+(\w+)'
match = re.search(class_pattern, test_code)
if match and match.group(1) != test_class_name:
test_code = re.sub(class_pattern, f'class {test_class_name}', test_code)
# Fix @DisplayName annotations if missing quotes
display_name_pattern = r'@DisplayName\(([^"\'"][^)]*)\)'
if re.search(display_name_pattern, test_code):
test_code = re.sub(display_name_pattern, r'@DisplayName("\1")', test_code)
return test_code
def fix_access_modifiers(self, test_code, class_name, source_code):
"""Fix issues with access modifiers"""
# If we don't have the source code, we can't reliably fix access modifiers
if not source_code:
return test_code
# Find private methods in the source code
private_methods = []
private_pattern = r'private\s+\w+\s+(\w+)\s*\('
for match in re.finditer(private_pattern, source_code):
private_methods.append(match.group(1))
# Find tests that try to call these private methods
for method in private_methods:
# Look for direct calls to private methods
call_pattern = rf'\.{method}\s*\('
if re.search(call_pattern, test_code):
# Find which test methods call this private method
test_methods_with_private = []
method_pattern = r'@Test[^{]*{[^}]*' + re.escape(method)
for match in re.finditer(method_pattern, test_code, re.DOTALL):
# Extract the method
method_text = test_code[match.start():match.end()]
method_name = re.search(r'void\s+(\w+)\s*\(', method_text)
if method_name:
test_methods_with_private.append(method_name.group(1))
# Remove problematic test methods
for method_name in test_methods_with_private:
method_pattern = rf'@Test[^{{]*void\s+{method_name}\s*\([^{{]*{{[^}}]*}}'
test_code = re.sub(method_pattern, '', test_code, flags=re.DOTALL)
return test_code
class TestMethodExtractor:
"""Extracts individual test methods from a test class"""
def extract_methods(self, test_code):
"""
Extract individual test methods from test code
Parameters:
test_code (str): Full test class code
Returns:
list: List of dictionaries with method information
"""
methods = []
if not test_code:
return methods
# Look for @Test annotations followed by method declarations
# Find all method start points
annotation_pattern = r'(@Test[\s\S]*?)(?=@Test|$)'
annotation_blocks = re.finditer(annotation_pattern, test_code)
for block_match in annotation_blocks:
block = block_match.group(1)
# Check if this block contains a method declaration
method_match = re.search(r'void\s+(\w+)\s*\([^)]*\)', block)
if not method_match:
continue
method_name = method_match.group(1)
# Find the opening brace for this method
open_brace_idx = test_code.find('{', block_match.start())
if open_brace_idx == -1:
continue
# Find the matching closing brace by counting braces
brace_count = 1
close_brace_idx = -1
for i in range(open_brace_idx + 1, len(test_code)):
if test_code[i] == '{':
brace_count += 1
elif test_code[i] == '}':
brace_count -= 1
if brace_count == 0:
close_brace_idx = i
break
if close_brace_idx != -1:
# Extract the complete method
method_code = test_code[block_match.start():close_brace_idx + 1]
methods.append({
'name': method_name,
'code': method_code
})
return methods
def combine_methods(self, base_class, methods):
"""
Combine individual test methods into a complete test class
Parameters:
base_class (str): Base test class structure (imports, class declaration, etc.)
methods (list): List of method dictionaries
Returns:
str: Complete test class with combined methods
"""
if not base_class or not methods:
return base_class
# Find class body
class_match = re.search(r'(class\s+\w+\s*\{)', base_class)
if not class_match:
return base_class
class_start = class_match.end()
class_end = base_class.rfind('}')
# Extract existing methods to avoid duplicates
existing_methods = self.extract_methods(base_class)
existing_names = {m.get("name", ""): True for m in existing_methods if isinstance(m, dict)}
existing_bodies = set()
for method in existing_methods:
if isinstance(method, dict) and "code" in method:
# Create simplified signature for comparison
simplified = re.sub(r'\/\/.*?\n', '', method["code"]) # Remove comments
simplified = re.sub(r'\s+', ' ', simplified) # Normalize whitespace
existing_bodies.add(simplified)
# Add methods, checking for duplicates
methods_text = "\n\n"
added_methods = []
for method in methods:
if isinstance(method, dict) and "code" in method:
# Get method name
name_match = re.search(r'void\s+(\w+)\s*\(', method["code"])
if not name_match:
continue
method_name = name_match.group(1)
original_name = method_name
# Check if name exists - rename if needed
if method_name in existing_names:
# Try to find a unique name
counter = 1
while f"{method_name}_{counter}" in existing_names:
counter += 1
new_name = f"{method_name}_{counter}"
# Rename method
method["code"] = re.sub(
r'void\s+' + re.escape(original_name) + r'\s*\(',
f'void {new_name}(',
method["code"]
)
method_name = new_name
# Check for similar method bodies
simplified = re.sub(r'\/\/.*?\n', '', method["code"]) # Remove comments
simplified = re.sub(r'\s+', ' ', simplified) # Normalize whitespace
if simplified in existing_bodies:
continue # Skip duplicates
# Add the method
methods_text += method["code"] + "\n\n"
existing_names[method_name] = True
existing_bodies.add(simplified)
added_methods.append(method_name)
if not added_methods:
return base_class # No methods to add
# Log which methods were added
logger.info(f"Added {len(added_methods)} unique methods: {', '.join(added_methods)}")
# If class end not found, simply append methods
if class_end <= class_start:
return base_class + methods_text + "\n}"
else:
# Insert before class closing brace
return base_class[:class_end] + methods_text + base_class[class_end:]
def create_temp_test_class(base_test, method_code):
"""
Create a temporary test class with the given base test and an additional method
Parameters:
base_test (str): Base test class code
method_code (str): Method code to add
Returns:
str: Combined test class code
"""
# Find the end of the class
class_end = base_test.rfind('}')
if class_end <= 0:
return base_test
# Insert method before class end
return base_test[:class_end] + "\n\n" + method_code + "\n\n" + base_test[class_end:]
class AdaptiveMCTSNode:
"""Node in the Adaptive MCTS tree with enhanced exploration strategy"""
def __init__(self, state, parent=None, action=None):
self.state = state
self.parent = parent
self.action = action # Action that led to this state
self.children = []
self.visits = 0
self.value = 0.0
self.untried_actions = None # Will be populated after expansion
self.potential_actions = [] # Potential actions with scores
self.exploration_factor = 1.0 # Adaptive exploration factor
def generate_possible_actions(self, test_prompt, source_code, uncovered_data=None):
"""Generate possible actions based on current state with priority scoring"""
if not self.state.executed:
self.state.evaluate()
actions = []
# If test contains nested classes, prioritize fixing that
# if self.state.has_nested_classes:
# actions.append({
# "type": "flatten_test_structure",
# "description": "Refactor test to remove nested classes and use flat structure",
# "priority": 100 # Highest priority
# })
# self.untried_actions = actions
# return actions
# Add actions for fixing compilation errors
print("--------------------------------")
print(self.state.compilation_errors)
print("--------------------------------")
if self.state.compilation_errors:
actions.append({
"type": "fix_critical_errors",
"description": "Fix compilation errors in tests",
"priority": 100000
})
# Add actions for improving coverage
if self.state.uncovered_lines:
# Sample uncovered lines with priority based on their location
sorted_lines = sorted(self.state.uncovered_lines, key=lambda x: x['line'])
# Target lines in the middle of the class first
if source_code:
source_lines = source_code.split('\n')
middle_index = len(source_lines) // 2
for line in sorted_lines[:5]: # Limit to 5 to avoid too many similar actions
# Calculate priority based on distance from middle
distance_from_middle = abs(line['line'] - middle_index)
line_priority = 80 - min(distance_from_middle, 30)
actions.append({
"type": "target_line",
"line": line['line'],
"description": f"Add test to cover line {line['line']}",
"priority": line_priority
})
if self.state.uncovered_branches:
# Sample branches with priority based on branch location
sorted_branches = sorted(self.state.uncovered_branches, key=lambda x: x['line'])
for branch in sorted_branches[:3]: # Limit to 3
actions.append({
"type": "target_branch",
"line": branch['line'],
"description": f"Add test to cover branch at line {branch['line']}",
"priority": 75
})
# Action for finding bugs through edge cases
actions.append({
"type": "test_edge_cases",
"description": "Add tests for edge cases that might reveal bugs",
"priority": 60 + (len(self.state.detected_bugs) * 5) # Higher priority if already found bugs
})
# Action for detecting resource issues
actions.append({
"type": "test_for_resource_issues",
"description": "Test for resource leaks, infinite loops, and memory issues",
"priority": 50 + (len(self.state.memory_errors) * 10) # Higher priority if memory issues detected
})
# Action for investigating assertion failures
if self.state.assertion_failures:
actions.append({
"type": "investigate_assertions",
"description": "Investigate and refine assertion failures that may indicate real bugs",
"priority": 70
})
# Action for bug hunting
actions.append({
"type": "hunt_bugs",
"description": "Focus on finding bugs (edge cases, invariants)",
"priority": 55
})
actions.append({
"type": "test_numerical_precision",
"description": "Test mathematical functions with different precision settings",
"priority": 65
})
actions.append({
"type": "test_with_special_chars",
"description": "Add tests with special characters (CJK, emoji, control chars)",
"priority": 65
})
actions.append({
"type": "test_with_numeric_edge_cases",
"description": "Add tests with numeric edge cases (negative, max values, precision limits)",
"priority": 60
})
actions.append({
"type": "test_with_multiple_iterators",
"description": "Add tests that use multiple iterators on the same data source",
"priority": 70
})
# NEW: Add format compatibility testing
actions.append({
"type": "test_format_compatibility",
"description": "Test format compatibility with standard specifications (Excel, etc.)",
"priority": 68
})
# NEW: Add empty/null values testing
actions.append({
"type": "test_empty_null_values",
"description": "Test behavior with empty strings, null values, and blank entries",
"priority": 72
})
# NEW: Add file structure boundary testing
actions.append({
"type": "test_boundary_file_structures",
"description": "Test boundary cases in file structures (empty lines, trailing chars)",
"priority": 72
})
# NEW: Add permission flags testing
actions.append({
"type": "test_permission_flag_combinations",
"description": "Test combinations of permission flags and special values",
"priority": 65
})
# NEW: Add sequential operations testing
actions.append({
"type": "test_sequential_operations",
"description": "Test sequences of operations that may interact (create-modify-use pattern)",
"priority": 75
})
# actions.append({
# "type": "test_malformed_html",
# "description": "Test with malformed/incomplete HTML tags",
# "priority": 75
# })
actions.append({
"type": "test_binary_data",
"description": "Test parsing with binary data or invalid encoding",
"priority": 80 # Higher priority to catch hanging issues
})
# actions.append({
# "type": "test_duplicate_attributes",
# "description": "Test HTML with duplicate attributes on elements",
# "priority": 70
# })
# Action for refactoring tests
# actions.append({
# "type": "refactor_tests",
# "description": "Refactor tests for better organization and maintainability",
# "priority": 40
# })
# Action for improving assertions
actions.append({
"type": "improve_assertions",
"description": "Improve test assertions for better validation",
"priority": 45
})
# Add specialized actions for verified bugs
verified_bugs = [bug for bug in self.state.detected_bugs
if bug.get("verified", False) and bug.get("is_real_bug", True)]
if verified_bugs:
# Prioritize verified bugs highly
actions.append({
"type": "verify_bugs",
"description": "Add tests to verify confirmed bugs, if not a bug please fix it",
"priority": 85,
"bugs": verified_bugs
})
# Handle other potential bugs for verification
elif len(self.state.detected_bugs) > 0:
# Get high confidence unverified bugs
high_confidence_bugs = [bug for bug in self.state.detected_bugs
if bug.get("confidence", 0) >= 0.7 and not bug.get("verified", False)]
if high_confidence_bugs:
actions.append({
"type": "verify_potential_bugs",
"description": "Verify and add tests for high-confidence potential bugs, if not a bug please fix it",
"priority": 75,
"bugs": high_confidence_bugs
})
else:
actions.append({
"type": "verify_bugs",
"description": "Verify potential bugs, if not a bug please fix it",
"priority": 65,
"bugs": self.state.detected_bugs
})
# Use uncovered data to target specific uncovered code
if uncovered_data and 'uncovered_methods' in uncovered_data:
for method in uncovered_data['uncovered_methods'][:2]: # Limit to 2
actions.append({
"type": "target_method",
"method": method,
"description": f"Add tests to cover method: {method}",
"priority": 85
})
# Store potential actions with their priorities
self.potential_actions = sorted(actions, key=lambda x: -x['priority'])
# Set untried actions (copy to avoid modifying the original)
self.untried_actions = self.potential_actions.copy()
return self.potential_actions
def is_fully_expanded(self):
"""Check if all possible actions have been tried"""
return self.untried_actions is not None and len(self.untried_actions) == 0
def best_child(self, exploration_weight=1.0):
"""Select best child node using UCB1 formula with adaptive exploration"""
if not self.children:
return None
# Use adaptive exploration factor
effective_exploration = exploration_weight * self.exploration_factor
# UCB1 formula with node potential
log_visits = np.log(self.visits) if self.visits > 0 else 0
def ucb_score(child):
# Base UCB1 score
exploitation = child.value / child.visits if child.visits > 0 else 0
exploration = effective_exploration * np.sqrt(2 * log_visits / child.visits) if child.visits > 0 else float('inf')
# Add potential score component to bias toward promising states
potential_bias = 0.1 * child.state.potential_score / 100 if hasattr(child.state, 'potential_score') else 0
# Extra bonus for states with verified bugs
verified_bugs_count = child.state.count_verified_bugs() if hasattr(child.state, 'count_verified_bugs') else 0
verified_bonus = verified_bugs_count * 0.2
# 添加新的多样性分数
diversity_score = 0.0
# 如果此状态包含特殊输入测试,增加多样性分数
if hasattr(child.state, 'has_special_input_tests') and child.state.has_special_input_tests:
diversity_score += 0.3
# 如果此状态包含异常路径测试,增加多样性分数
if hasattr(child.state, 'has_exception_path_tests') and child.state.has_exception_path_tests:
diversity_score += 0.2
# 组合最终分数
return exploitation + exploration + potential_bias + verified_bonus + diversity_score
return max(self.children, key=ucb_score)
def add_child(self, state, action):
"""Add a child node"""
child = AdaptiveMCTSNode(state, self, action)
self.children.append(child)
# Track and adapt exploration factor based on results
if self.parent and self.parent.exploration_factor:
# If this child found new verified bugs or increased coverage, reduce exploration
# to focus more on exploitation of this promising area
if (state.coverage > self.state.coverage + 5) or state.count_verified_bugs() > 0:
child.exploration_factor = max(0.5, self.exploration_factor - 0.2)
elif state.has_critical_errors():
# If this child has critical errors, increase exploration to try different paths
child.exploration_factor = min(2.0, self.exploration_factor + 0.3)
else:
# Otherwise inherit parent's exploration factor with slight randomization
child.exploration_factor = self.exploration_factor * random.uniform(0.9, 1.1)
return child
def update(self, reward):
"""Update node statistics"""
self.visits += 1
self.value += reward
# Adapt exploration factor based on reward
if self.visits > 3:
recent_avg = self.value / self.visits
if recent_avg > 100: # Very good results, reduce exploration
self.exploration_factor = max(0.5, self.exploration_factor - 0.1)
elif recent_avg < 0: # Poor results, increase exploration
self.exploration_factor = min(2.0, self.exploration_factor + 0.1)
class EnhancedMCTSTestGenerator:
"""Uses Enhanced Monte Carlo Tree Search to guide LLM test generation"""
def __init__(self, project_dir, prompt_dir, class_name, package_name,
initial_test_code, source_code, test_prompt,
max_iterations=20, exploration_weight=1.0,
use_anthropic=True, verify_bugs_mode="batch",
focus_on_bugs=True, initial_coverage=0.0, project_type='maven'):
self.project_dir = project_dir
self.prompt_dir = prompt_dir
self.class_name = class_name
self.package_name = package_name
self.initial_test_code = initial_test_code
self.source_code = source_code
self.test_prompt = test_prompt
self.max_iterations = max_iterations # Increased since we're doing one tree
self.exploration_weight = exploration_weight
self.use_anthropic = use_anthropic
self.verify_bugs_mode = verify_bugs_mode
self.focus_on_bugs = focus_on_bugs
self.initial_coverage = initial_coverage
self.project_type = project_type
self.critical_bug_checked = False
# Create validator and method extractor
self.validator = TestValidator()
self.method_extractor = TestMethodExtractor()
self.detailed_history = {
"iterations": [],
"coverage_trend": [],
"bug_discoveries": [],
"runtime_stats": [],
"best_coverage_points": []
}
# 记录初始状态
if initial_coverage > 0:
self.detailed_history["coverage_trend"].append({
"iteration": 0,
"coverage": initial_coverage,
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
})
self.detailed_history["best_coverage_points"].append({
"iteration": 0,
"coverage": initial_coverage,
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
})
# Create initial state and evaluate
initial_state = TestState(
initial_test_code,
class_name,
package_name,
project_dir,
source_code,
project_type
)
# Initialize all bug tracking variables first
self.all_bug_finding_tests = []
self.bug_finding_methods = []
self.verified_bug_methods = []
# Track different test variants
self.test_variants = {
"overall": {"code": initial_test_code, "reward": 0},
"coverage": {"code": initial_test_code, "coverage": initial_state.coverage},
"bug_finding": {"code": None, "bug_count": 0},
"critical_bug": {"code": None, "found": False},
"verified_bug": {"code": None, "verified_count": 0}
}
# Track test performance metrics
self.best_overall_test = initial_test_code
self.best_coverage_test = initial_test_code
self.best_bug_finding_test = None
self.best_compilable_test = initial_test_code
self.best_verified_bug_test = None
# Explicitly evaluate initial state with bug detection
logger.info("Evaluating initial test state with bug detection")
initial_state.evaluate(self.validator, verify_bugs_mode == "immediate")
self.root = AdaptiveMCTSNode(initial_state)
# Update metrics after evaluation
self.best_reward = self.calculate_reward(initial_state)
self.best_coverage = initial_state.coverage
self.best_bug_count = len(initial_state.detected_bugs)
self.best_verified_bug_count = initial_state.count_verified_bugs()
# Update test variants with initial evaluation results
self.test_variants["overall"]["reward"] = self.best_reward
self.test_variants["coverage"]["coverage"] = initial_state.coverage
# Collect bug methods from initial test
if initial_state.detected_bugs:
logger.info(f"Initial test detected {len(initial_state.detected_bugs)} potential bugs")
bug_methods = initial_state.get_bug_finding_test_methods()
if bug_methods:
self.bug_finding_methods = bug_methods
logger.info(f"Extracted {len(bug_methods)} bug-finding methods from initial test")
# Get verified bug methods
verified_methods = initial_state.get_logical_bug_finding_methods()
if verified_methods:
self.verified_bug_methods = verified_methods
logger.info(f"Found {len(verified_methods)} verified bug methods in initial test")
initial_bug_info = {
"test_code": initial_test_code,
"bug_count": len(initial_state.detected_bugs),
"verified_bug_count": initial_state.count_verified_bugs(),
"coverage": initial_state.coverage,
"iteration": 0, # Mark as initial iteration
"bugs": initial_state.detected_bugs,
"execution_time": initial_state.execution_time,
"methods": [m["code"] for m in self.bug_finding_methods] if self.bug_finding_methods else []
}
self.all_bug_finding_tests.append(initial_bug_info)
logger.info(f"Added initial test to bug-finding tests collection")
# Update best bug-finding test data
if self.best_bug_finding_test is None:
self.best_bug_finding_test = initial_test_code
self.test_variants["bug_finding"]["code"] = initial_test_code
self.test_variants["bug_finding"]["bug_count"] = len(initial_state.detected_bugs)
# Update verified bug test data
if verified_methods and not self.best_verified_bug_test:
self.best_verified_bug_test = initial_test_code
self.best_verified_bug_count = len(verified_methods)
self.test_variants["verified_bug"]["code"] = initial_test_code
self.test_variants["verified_bug"]["verified_count"] = len(verified_methods)
# Check for critical bugs
has_critical_bug = any(
bug.get("type") == "critical_exception" or
bug.get("severity", "") == "critical" or
bug.get("severity", "") == "high"
for bug in initial_state.detected_bugs
)
if has_critical_bug:
self.test_variants["critical_bug"]["code"] = initial_test_code
self.test_variants["critical_bug"]["found"] = True
logger.info("Initial test contains critical bugs")
else:
self.bug_finding_methods = []
self.verified_bug_methods = []
# Test complexity metrics
self.method_count = 0
self.assertion_count = 0
self.line_count = 0
# Additional metrics for adaptive exploration
self.state_complexity = 0
self.potential_score = 0
# Method library for reuse
self.method_library = {}
# Uncovered code information
self.uncovered_data = self.analyze_uncovered_code()
# Track progress history
self.history = []
# Cache for successful prompts and responses
self.prompt_cache = {}
def analyze_uncovered_code(self):
"""Analyze source code to extract uncovered methods and regions"""
if not self.source_code:
return {}
# Simple analysis to find method definitions
method_pattern = r'(?:public|protected|private)\s+\w+\s+(\w+)\s*\([^)]*\)\s*(?:throws\s+[\w.]+(?:\s*,\s*[\w.]+)*\s*)?\{'
methods = re.findall(method_pattern, self.source_code)