-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbug_verifier.py
More file actions
1856 lines (1545 loc) · 79.2 KB
/
Copy pathbug_verifier.py
File metadata and controls
1856 lines (1545 loc) · 79.2 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
"""
Bug Verifier
This module extends bug verification capabilities with specialized analysis
for bugs. It provides more sophisticated verification of bugs
using pattern matching, code context analysis, and LLM-based verification.
"""
import os
import re
import json
import logging
import traceback
from collections import defaultdict
# Import from base bug verification
from verify_bug_with_llm import verify_bug_with_llm
# Import for API access
from feedback import call_anthropic_api, call_gpt_api, call_deepseek_api, extract_java_code
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("bug_verifier")
class BugVerifier:
"""
Provides specialized verification for bugs with enhanced
analysis of properties, boundary conditions, and code context.
"""
def __init__(self, source_code, class_name, package_name):
"""
Initialize with source code to analyze
Parameters:
source_code (str): Source code to analyze
class_name (str): Class name
package_name (str): Package name
"""
self.source_code = source_code
self.class_name = class_name
self.package_name = package_name
# Logic bug patterns with verification strategies
# self.logic_bug_categories = {
# "incorrect_value": {
# "verify_method": self._verify_incorrect_value,
# "confidence_threshold": 0.7
# },
# "incorrect_boolean": {
# "verify_method": self._verify_incorrect_boolean,
# "confidence_threshold": 0.8
# },
# "empty_null_handling": {
# "verify_method": self._verify_empty_null_handling,
# "confidence_threshold": 0.6
# },
# "index_error": {
# "verify_method": self._verify_index_error,
# "confidence_threshold": 0.8
# },
# "string_index_error": { # 添加新的字符串索引错误验证
# "verify_method": self._verify_string_index_error,
# "confidence_threshold": 0.8
# },
# "array_index_error": { # 添加新的数组索引错误验证
# "verify_method": self._verify_array_index_error,
# "confidence_threshold": 0.8
# },
# "null_reference": {
# "verify_method": self._verify_null_reference,
# "confidence_threshold": 0.7
# },
# "boundary_error": {
# "verify_method": self._verify_boundary_error,
# "confidence_threshold": 0.8
# },
# "operator_logic": {
# "verify_method": self._verify_operator_bug,
# "confidence_threshold": 0.8
# },
# "boolean_bug": {
# "verify_method": self._verify_boolean_bug,
# "confidence_threshold": 0.7
# },
# "infinite_loop": {
# "verify_method": self._verify_infinite_loop,
# "confidence_threshold": 0.9
# },
# "resource_leak": {
# "verify_method": self._verify_resource_leak,
# "confidence_threshold": 0.8
# },
# "resource_management": {
# "verify_method": self._verify_resource_management,
# "confidence_threshold": 0.7
# },
# "use_after_close": {
# "verify_method": self._verify_use_after_close,
# "confidence_threshold": 0.8
# },
# "data_operation": {
# "verify_method": self._verify_data_operation,
# "confidence_threshold": 0.7
# },
# "integer_truncation": {
# "verify_method": self._verify_integer_truncation,
# "confidence_threshold": 0.8
# },
# "precision_loss": {
# "verify_method": self._verify_precision_loss,
# "confidence_threshold": 0.7
# },
# "exception_handling": {
# "verify_method": self._verify_exception_handling,
# "confidence_threshold": 0.7
# },
# "swallowed_exception": {
# "verify_method": self._verify_swallowed_exception,
# "confidence_threshold": 0.8
# },
# "validation": {
# "verify_method": self._verify_validation,
# "confidence_threshold": 0.7
# },
# "concurrency": {
# "verify_method": self._verify_concurrency,
# "confidence_threshold": 0.8
# },
# "security": {
# "verify_method": self._verify_security,
# "confidence_threshold": 0.8
# }
# }
# Counter for verification results
self.verification_results = defaultdict(int)
def verify_bugs(self, bug_methods):
"""
verify a list of bug test methods, ensuring no duplicate counting of the same bug
Parameters:
bug_methods (list): the list of bug test methods to verify
Returns:
list: the list of verified bug test methods
"""
import hashlib
# use a dictionary to deduplicate
verified_methods_dict = {}
if not bug_methods:
return []
logger.info(f"using failure-aware verification for {len(bug_methods)} bug methods")
# reset the verification counter
self.verification_results = defaultdict(int)
try:
# process each bug method
for method in bug_methods:
if not isinstance(method, dict) or "code" not in method:
continue
# get or create the bug signature
bug_signature = method.get("bug_signature")
if not bug_signature:
# create the signature
method_name = method.get("method_name", "unknown")
error = method.get("error", "")
bug_signature = f"{method_name}:{hashlib.md5(error.encode()).hexdigest()[:12]}"
# if the signature has been processed, skip
if bug_signature in verified_methods_dict:
logger.info(f"skipping verified bug signature: {bug_signature}")
continue
# extract the method information
# print("--------------------------------")
# print(method)
# print("--------------------------------")
method_code = method.get("code", "")
bug_type = method['bug_info'][0].get("bug_type", "unknown")
method_name = method.get("method_name", "unknown")
logger.info(f"verifying method '{method_name}', bug type: {bug_type}")
# use LLM to verify the bug
verification_result = verify_bug_with_llm(
method, method_code, self.source_code, self.class_name
)
# explicitly set is_real_bug, not relying on the default value
is_real_bug = verification_result.get("is_real_bug", False)
# merge the verification results into the method
method_result = {
**method,
"verified": True,
"is_real_bug": is_real_bug,
"verification_confidence": verification_result.get("confidence", 0.5),
"verification_reasoning": verification_result.get("reasoning", "逻辑bug验证")
}
# add to the result dictionary
verified_methods_dict[bug_signature] = method_result
# track the verification results
if is_real_bug:
self.verification_results["true_positive"] += 1
else:
self.verification_results["false_positive"] += 1
# convert back to a list
verified_methods = list(verified_methods_dict.values())
# record the verification summary
total_verified = len(verified_methods)
true_positives = self.verification_results["true_positive"]
false_positives = self.verification_results["false_positive"]
# record the verification summary
logger.info(f"验证完成: " +
f"{true_positives} 真实bug, " +
f"{false_positives} 误报, " +
f"{total_verified} 总方法数")
return verified_methods
except Exception as e:
logger.error(f"验证bug时出错: {str(e)}")
logger.error(traceback.format_exc())
return []
def _standard_verification(self, method_code, method_info):
"""
Standard verification using base LLM verification
Parameters:
method_code (str): Method code to verify
method_info (dict): Method information
Returns:
dict: Verification result
"""
try:
return verify_bug_with_llm(method_info, method_code, self.source_code, self.class_name)
except Exception as e:
logger.error(f"Error in standard verification: {str(e)}")
# Return conservative result (assume it might be a bug but with low confidence)
return {
"is_real_bug": method_info.get("confidence", 0.0) > 0.7,
"confidence": 0.5,
"reasoning": f"Verification failed with error: {str(e)}"
}
def _verify_business_logic(self, method_code, method_info):
"""
Verify business logic bugs using business logic analyzer
Parameters:
method_code (str): Method code to verify
method_info (dict): Method information
Returns:
dict: Verification result
"""
# Import business logic analyzer
from business_logic_analyzer import BusinessLogicAnalyzer
# Extract method name
method_name = method_info.get("method_name", "unknown")
# Get related source code for the method being tested
source_context = self._extract_related_source_code(method_name)
# Create an instance of business logic analyzer
analyzer = BusinessLogicAnalyzer(self.source_code, self.class_name)
# Analyze the method's business logic
analysis = analyzer.analyze_code_for_logic_bugs(
source_code=self.source_code,
class_name=self.class_name,
method_name=method_name
)
# If analysis failed, fall back to standard verification
if "error" in analysis:
logger.warning(f"Business logic analysis failed: {analysis['error']}")
return self._standard_verification(method_code, method_info)
# Extract validation and confidence from analysis
validation = analysis.get("validation", {})
confidence = validation.get("overall_confidence", 0.0)
is_bug_real = validation.get("is_bug_real", False)
# Get potential bugs and explanation
potential_bugs = analysis.get("potential_bugs", [])
explanation = analysis.get("llm_analysis", {}).get("explanation", "")
# If confidence is high enough and bug is considered real
if confidence >= 0.7 and is_bug_real and potential_bugs:
return {
"is_real_bug": True,
"confidence": confidence,
"reasoning": f"Business logic analysis found {len(potential_bugs)} potential bugs. {explanation}"
}
elif confidence >= 0.6:
# Medium confidence - could be a bug but not certain
return {
"is_real_bug": is_bug_real,
"confidence": confidence,
"reasoning": f"Business logic analysis with medium confidence: {explanation}"
}
else:
# Low confidence - fall back to standard verification
return self._enhanced_llm_verification(
method_code,
method_info,
"business_logic",
f"Business logic analysis was inconclusive with confidence {confidence:.2f}. {explanation}"
)
def _verify_incorrect_value(self, method_code, method_info):
"""
Verify an incorrect value bug with specialized analysis
Parameters:
method_code (str): Method code to verify
method_info (dict): Method information
Returns:
dict: Verification result
"""
# Look for assertion with expected vs actual values
expected_actual_match = re.search(r'expected:.*?<([^>]+)>.*?but was:.*?<([^>]+)>', method_code)
if expected_actual_match:
expected = expected_actual_match.group(1)
actual = expected_actual_match.group(2)
# Check for empty/null values
if expected == "" and actual == "null" or expected == "null" and actual == "":
# Common false positive - different representations of empty
return {
"is_real_bug": False,
"confidence": 0.8,
"reasoning": "Empty string vs null is likely not a real bug, but a test expectation issue"
}
# Check for boolean confusions
if (expected.lower() == "true" and actual.lower() == "false") or \
(expected.lower() == "false" and actual.lower() == "true"):
# Likely a real logic bug
return {
"is_real_bug": True,
"confidence": 0.8,
"reasoning": "Boolean value mismatch often indicates a logical bug in conditional logic"
}
# Check for off-by-one situations
try:
if expected.isdigit() and actual.isdigit():
expected_num = int(expected)
actual_num = int(actual)
if abs(expected_num - actual_num) == 1:
# Classic off-by-one error
return {
"is_real_bug": True,
"confidence": 0.9,
"reasoning": "Off-by-one difference between expected and actual numeric values"
}
except:
pass
# Use LLM for deeper analysis
return self._enhanced_llm_verification(method_code, method_info, "incorrect_value")
def _verify_incorrect_boolean(self, method_code, method_info):
"""
Verify a boolean logic bug with specialized analysis
Parameters:
method_code (str): Method code to verify
method_info (dict): Method information
Returns:
dict: Verification result
"""
# Look for pattern of boolean test failure
boolean_failure = re.search(r'expected:.*?<(true|false)>.*?but was:.*?<(true|false)>', method_code, re.IGNORECASE)
if boolean_failure:
expected = boolean_failure.group(1).lower()
actual = boolean_failure.group(2).lower()
if expected != actual:
# Extract the assertion context
assertion_context = self._extract_assertion_context(method_code)
# Check for negation or complex conditions
if "!" in assertion_context or "&&" in assertion_context or "||" in assertion_context:
# Likely a real bug in boolean expression
return {
"is_real_bug": True,
"confidence": 0.9,
"reasoning": "Boolean condition failure with complex expression or negation"
}
# Use LLM for deeper analysis
return self._enhanced_llm_verification(method_code, method_info, "boolean_bug")
def _verify_empty_null_handling(self, method_code, method_info):
"""
Verify empty/null handling bug with specialized analysis
Parameters:
method_code (str): Method code to verify
method_info (dict): Method information
Returns:
dict: Verification result
"""
# Look for null-related assertions
null_check = re.search(r'assert(?:Equals|Null|NotNull)\s*\([^,]*null', method_code)
empty_check = re.search(r'assert(?:Equals|True|False)\s*\([^,]*(?:""|isEmpty\(\))', method_code)
if null_check or empty_check:
# Look for specific null handling in source code
method_name = method_info.get("method_name", "unknown")
source_context = self._extract_related_source_code(method_name)
# Check if source code has null checks
if "!= null" in source_context or "== null" in source_context:
# Source has null checks, test might have found a real issue
return {
"is_real_bug": True,
"confidence": 0.7,
"reasoning": "Source code contains null checks, test failure could indicate mishandling"
}
# Check for empty string handling
if '""' in source_context or "isEmpty()" in source_context:
# Source handles empty strings, test might have found a real issue
return {
"is_real_bug": True,
"confidence": 0.7,
"reasoning": "Source code contains empty string handling, test failure could indicate issue"
}
# Use LLM for deeper analysis
return self._enhanced_llm_verification(method_code, method_info, "empty_null_handling")
def _verify_string_index_error(self, method_code, method_info):
"""
Verify string index error bugs with specialized analysis
Parameters:
method_code (str): Method code to verify
method_info (dict): Method information
Returns:
dict: Verification result
"""
# Check for StringIndexOutOfBoundsException
string_exception = re.search(r'StringIndexOutOfBounds', method_code)
if string_exception:
# High confidence if explicitly testing for this exception
if re.search(r'assertThrows\s*\(\s*.*StringIndexOutOfBoundsException', method_code):
return {
"is_real_bug": True,
"confidence": 0.95,
"reasoning": "Test explicitly checks for StringIndexOutOfBoundsException, almost certainly a real issue"
}
return {
"is_real_bug": True,
"confidence": 0.9,
"reasoning": "StringIndexOutOfBoundsException mentioned in test, likely a real bug"
}
# Look for string operations
charAt_usage = re.search(r'(\w+)\.charAt\s*\(\s*([^)]+)\s*\)', method_code)
substring_usage = re.search(r'(\w+)\.substring\s*\(\s*([^,)]+)(?:\s*,\s*([^)]+))?\s*\)', method_code)
if charAt_usage or substring_usage:
# Extract usage info
if charAt_usage:
string_var = charAt_usage.group(1)
index_expr = charAt_usage.group(2)
else: # substring_usage
string_var = substring_usage.group(1)
index_expr = substring_usage.group(2)
# Check if test creates edge cases
edge_cases = re.search(r'length\(\s*\)\s*[+-]\s*1|empty string|""', method_code)
if edge_cases:
# Test is likely checking edge cases for string operations
method_name = method_info.get("method_name", "unknown")
source_context = self._extract_related_source_code(method_name)
# Check source for length validations before index access
if not re.search(fr'if\s*\([^)]*{string_var}\.length\(\)[^)]*\)', source_context):
return {
"is_real_bug": True,
"confidence": 0.85,
"reasoning": "Test checks edge cases for string operations but source lacks length validation"
}
# Check for explicit string index validation in test
if re.search(r'(assertEquals|assertTrue|assertFalse)[^;]*StringIndexOutOfBounds', method_code):
# Test is explicitly checking for index validation
return {
"is_real_bug": True,
"confidence": 0.9,
"reasoning": "Test explicitly checks string index validation behavior"
}
# Look for test cases with empty strings
empty_strings = re.search(r'(?:String\s+\w+\s*=\s*""|=\s*new\s+String\s*\(\s*\))', method_code)
if empty_strings and (charAt_usage or substring_usage):
return {
"is_real_bug": True,
"confidence": 0.8,
"reasoning": "Test uses empty strings with string operations that could cause index errors"
}
# Use LLM for deeper analysis
return self._enhanced_llm_verification(method_code, method_info, "string_index_error",
"This test may be checking for StringIndexOutOfBoundsException issues.")
def _verify_index_error(self, method_code, method_info):
"""
Verify index error bug with specialized analysis
Parameters:
method_code (str): Method code to verify
method_info (dict): Method information
Returns:
dict: Verification result
"""
# Check for index-related exceptions
index_exception = re.search(r'IndexOutOfBoundsException|ArrayIndexOutOfBoundsException|StringIndexOutOfBoundsException', method_code)
if index_exception:
# If we see specific array or string exceptions, delegate to specialized verifiers
if "ArrayIndexOutOfBoundsException" in method_code:
return self._verify_array_index_error(method_code, method_info)
elif "StringIndexOutOfBoundsException" in method_code:
return self._verify_string_index_error(method_code, method_info)
# Generic IndexOutOfBoundsException - high confidence
return {
"is_real_bug": True,
"confidence": 0.9,
"reasoning": "Index out of bounds exceptions are almost always real bugs"
}
# Look for array index patterns
array_access = re.search(r'(\w+)\s*\[\s*([^]]+)\s*\]', method_code)
if array_access:
array_name = array_access.group(1)
index_expr = array_access.group(2)
# Check if index looks like a boundary case
if index_expr.isdigit() or ".length" in index_expr or "-1" in index_expr:
method_name = method_info.get("method_name", "unknown")
source_context = self._extract_related_source_code(method_name)
# Check source for boundary checks
if re.search(r'if\s*\([^)]*(?:<|>|<=|>=)[^)]*(?:length|size)', source_context):
# Source has boundary checks, test might have found a real issue
return {
"is_real_bug": True,
"confidence": 0.8,
"reasoning": "Source code contains boundary checks, index issue might be real"
}
# Look for collection access patterns (List.get(), etc.)
collection_access = re.search(r'(\w+)\.(?:get|set|remove)\s*\(\s*([^,)]+)\s*[,)]', method_code)
if collection_access:
collection_name = collection_access.group(1)
index_expr = collection_access.group(2)
# Check for boundary validation
method_name = method_info.get("method_name", "unknown")
source_context = self._extract_related_source_code(method_name)
if not re.search(fr'{collection_name}\.size\(\)', source_context):
return {
"is_real_bug": True,
"confidence": 0.75,
"reasoning": "Collection access without size validation in source code"
}
# Use LLM for deeper analysis
return self._enhanced_llm_verification(method_code, method_info, "index_error")
def _verify_null_reference(self, method_code, method_info):
"""
Verify null reference bug with specialized analysis
Parameters:
method_code (str): Method code to verify
method_info (dict): Method information
Returns:
dict: Verification result
"""
# Check for NullPointerException
null_exception = re.search(r'NullPointerException', method_code)
if null_exception:
# Extract test setup to find potential null values
setup_section = re.search(r'(?:void\s+\w+\s*\([^)]*\)\s*\{)(.*?)(?:assert)', method_code, re.DOTALL)
if setup_section:
setup_code = setup_section.group(1)
# Check if test explicitly sets null values
if "= null" in setup_code:
# Test explicitly sets null, likely testing null handling
return {
"is_real_bug": True,
"confidence": 0.8,
"reasoning": "Test explicitly sets null values and triggers NullPointerException"
}
# Check source for null checks
method_name = method_info.get("method_name", "unknown")
source_context = self._extract_related_source_code(method_name)
if "== null" not in source_context and "!= null" not in source_context:
# Source doesn't have null checks, likely a real issue
return {
"is_real_bug": True,
"confidence": 0.9,
"reasoning": "Source code doesn't check for null values but should"
}
# Use LLM for deeper analysis
return self._enhanced_llm_verification(method_code, method_info, "null_reference")
def _verify_boundary_error(self, method_code, method_info):
"""
Verify boundary error bug with specialized analysis
Parameters:
method_code (str): Method code to verify
method_info (dict): Method information
Returns:
dict: Verification result
"""
# Extract boundary value tests
boundary_tests = re.findall(r'assert(?:True|False|Equals)\s*\(\s*[^<>=!]+\s*([<>=!]+)\s*([^,\)]+)', method_code)
boundary_contexts = []
for op, value in boundary_tests:
boundary_contexts.append(f"Testing boundary with {op} {value.strip()}")
# Look for typical boundary error patterns
if ">=" in method_code and "<=" in method_code:
# Test is checking both upper and lower bounds, likely a boundary test
# Check source for boundary checks
method_name = method_info.get("method_name", "unknown")
source_context = self._extract_related_source_code(method_name)
if re.search(r'if\s*\([^)]*(?:<|>|<=|>=)[^)]*\)', source_context):
# Source has boundary checks, test might have found a real issue
return {
"is_real_bug": True,
"confidence": 0.8,
"reasoning": "Source code contains boundary checks, boundary test may have found real issue"
}
# Check for off-by-one patterns
if "-1" in method_code or "+1" in method_code:
# Test is using -1/+1 adjustments, likely testing boundaries
# Check for assertion failures
if self._has_assertion_failure(method_info):
# Failed assertion with boundary test is likely a real bug
return {
"is_real_bug": True,
"confidence": 0.7,
"reasoning": "Off-by-one test with assertion failure indicates boundary issue"
}
# Use LLM for deeper analysis with boundary contexts
return self._enhanced_llm_verification(method_code, method_info, "boundary_error",
additional_context="\n".join(boundary_contexts))
def _verify_array_index_error(self, method_code, method_info):
"""
Verify array index error bugs with specialized analysis
Parameters:
method_code (str): Method code to verify
method_info (dict): Method information
Returns:
dict: Verification result
"""
# Check for ArrayIndexOutOfBoundsException
array_exception = re.search(r'ArrayIndexOutOfBoundsException', method_code)
if array_exception:
# High confidence if explicitly testing for this exception
if re.search(r'assertThrows\s*\(\s*.*ArrayIndexOutOfBoundsException', method_code):
return {
"is_real_bug": True,
"confidence": 0.95,
"reasoning": "Test explicitly checks for ArrayIndexOutOfBoundsException, almost certainly a real issue"
}
return {
"is_real_bug": True,
"confidence": 0.9,
"reasoning": "ArrayIndexOutOfBoundsException mentioned in test, likely a real bug"
}
# Look for array accesses with indices that could be problematic
array_patterns = [
r'(\w+)\s*\[\s*(-\d+)\s*\]', # Negative index
r'(\w+)\s*\[\s*(\w+)\.length\s*\]', # Index at length (should be length-1)
r'(\w+)\s*\[\s*(\w+\s*(?:\+\+|--|\+=|-=).*?)\s*\]', # Modified index in access
r'for\s*\([^;]*;\s*\w+\s*<=\s*(\w+)\.length\s*;[^{]*\{\s*[^}]*\1\s*\[\s*(\w+)\s*\]' # Loop with <= length
]
for pattern in array_patterns:
matches = re.finditer(pattern, method_code)
for match in matches:
# We found a potentially problematic array access pattern
# Check if the test is verifying correct behavior or finding bugs
method_name = method_info.get("method_name", "unknown")
source_context = self._extract_related_source_code(method_name)
# Look for validation in source code
has_validation = re.search(r'if\s*\([^)]*<\s*\w+\.length', source_context)
if not has_validation:
return {
"is_real_bug": True,
"confidence": 0.85,
"reasoning": "Test appears to identify array access without proper bounds checking in source code"
}
# Check for multi-dimensional array accesses in tests
multi_dim_array = re.search(r'(\w+)\s*\[\s*([^]]+)\s*\]\s*\[\s*([^]]+)\s*\]', method_code)
if multi_dim_array:
array_name = multi_dim_array.group(1)
first_idx = multi_dim_array.group(2)
second_idx = multi_dim_array.group(3)
# Check source code for validation of both dimensions
method_name = method_info.get("method_name", "unknown")
source_context = self._extract_related_source_code(method_name)
first_dim_check = re.search(fr'if\s*\([^)]*{array_name}\.length', source_context)
second_dim_check = re.search(fr'if\s*\([^)]*{array_name}\[\s*[^\]]+\s*\]\.length', source_context)
if not (first_dim_check and second_dim_check):
return {
"is_real_bug": True,
"confidence": 0.8,
"reasoning": "Test with multi-dimensional array access, but source lacks complete boundary checks"
}
# Check for tests with edge cases like empty arrays or boundary indices
empty_array_test = re.search(r'new\s+\w+\s*\[\s*0\s*\]|emptyArray', method_code, re.IGNORECASE)
boundary_test = re.search(r'\.length\s*-\s*1|\[\s*0\s*\]', method_code)
if (empty_array_test or boundary_test) and "assertThrows" in method_code:
return {
"is_real_bug": True,
"confidence": 0.85,
"reasoning": "Test checks array boundary conditions with exception assertions"
}
# Check for off-by-one patterns in loops
off_by_one_loop = re.search(r'for\s*\([^;]*;\s*\w+\s*<=\s*\w+\.length', method_code)
if off_by_one_loop and re.search(r'ArrayIndexOutOfBoundsException|IndexOutOfBoundsException', method_code):
return {
"is_real_bug": True,
"confidence": 0.9,
"reasoning": "Test identifies off-by-one error in loop with <= array.length condition"
}
# Use LLM for deeper analysis
return self._enhanced_llm_verification(method_code, method_info, "array_index_error",
"This test may be checking for ArrayIndexOutOfBoundsException issues.")
def _verify_operator_bug(self, method_code, method_info):
"""
Verify operator bug with specialized analysis
Parameters:
method_code (str): Method code to verify
method_info (dict): Method information
Returns:
dict: Verification result
"""
# Look for complex expressions with multiple operators
complex_expr = re.search(r'assert.*?(?:&&|\|\|).*?(?:&&|\|\|)', method_code)
if complex_expr:
# Test contains complex boolean expressions
# Check for parentheses in expressions
has_parentheses = re.search(r'assert.*?\([^)]*(?:&&|\|\|)[^)]*\)', method_code)
# Extract source context
method_name = method_info.get("method_name", "unknown")
source_context = self._extract_related_source_code(method_name)
# Look for similar expressions in source
if "&&" in source_context and "||" in source_context:
# Source has complex expressions too
if self._has_assertion_failure(method_info):
# Failed assertion with complex expressions likely indicates operator precedence issue
return {
"is_real_bug": True,
"confidence": 0.8,
"reasoning": "Complex expressions with mixed operators may have precedence bugs"
}
# Check for bit operations vs logical operations
if re.search(r'[^&]&[^&]', method_code) or re.search(r'[^|]\|[^|]', method_code):
# Test uses bitwise operations, could be testing confusion between & and &&, | and ||
# Extract source context
method_name = method_info.get("method_name", "unknown")
source_context = self._extract_related_source_code(method_name)
if "&" in source_context and "&&" in source_context:
# Source mixes bitwise and logical AND
return {
"is_real_bug": True,
"confidence": 0.85,
"reasoning": "Code mixes bitwise (&) and logical (&&) operators, potential confusion"
}
if "|" in source_context and "||" in source_context:
# Source mixes bitwise and logical OR
return {
"is_real_bug": True,
"confidence": 0.85,
"reasoning": "Code mixes bitwise (|) and logical (||) operators, potential confusion"
}
# Use LLM for deeper analysis
return self._enhanced_llm_verification(method_code, method_info, "operator_logic")
def _verify_boolean_bug(self, method_code, method_info):
"""
Verify boolean bug with specialized analysis
Parameters:
method_code (str): Method code to verify
method_info (dict): Method information
Returns:
dict: Verification result
"""
# Check for boolean expression tests
boolean_expr_test = re.search(r'assert(?:True|False)\s*\(([^;]+)\)', method_code)
if boolean_expr_test:
expr = boolean_expr_test.group(1)
# Check for negation (!), likely testing boolean
if "!" in expr:
# Extract source context
method_name = method_info.get("method_name", "unknown")
source_context = self._extract_related_source_code(method_name)
# Look for negation in source too
if "!" in source_context and ("if" in source_context or "while" in source_context):
# Source uses negation in conditions
if self._has_assertion_failure(method_info):
# Failed assertion with negation likely indicates boolean bug
return {
"is_real_bug": True,
"confidence": 0.8,
"reasoning": "Boolean expression with negation fails"
}
# Check for DeMorgan's law testing
demorgan_test = re.search(r'assert.*?!\s*\([^)]*(?:&&|\|\|)[^)]*\)', method_code)
if demorgan_test:
# Test likely checking DeMorgan's law application
if self._has_assertion_failure(method_info):
# Failed assertion with DeMorgan pattern likely indicates boolean bug
return {
"is_real_bug": True,
"confidence": 0.9,
"reasoning": "Negated AND/OR expression fails, possible DeMorgan's Law error"
}
# Use LLM for deeper analysis
return self._enhanced_llm_verification(method_code, method_info, "boolean_bug")
def _verify_infinite_loop(self, method_code, method_info):
"""
Verify infinite loop bug with specialized analysis
Parameters:
method_code (str): Method code to verify
method_info (dict): Method information
Returns:
dict: Verification result
"""
# Check for timeout assertions
timeout_test = re.search(r'assertTimeout(?:Preemptively)?\s*\(', method_code)
if timeout_test:
# Test uses explicit timeout, likely testing against infinite loops
# Check for assertion failures
if self._has_assertion_failure(method_info):
# Failed timeout assertion is strong evidence of infinite loop
return {
"is_real_bug": True,
"confidence": 0.95,
"reasoning": "Timeout assertion failed, likely detected infinite loop"
}
# Check for long execution time
if method_info.get("error", "").lower().find("timeout") >= 0 or \
method_info.get("error", "").lower().find("timed out") >= 0:
# Test timed out, likely hit an infinite loop
return {
"is_real_bug": True,
"confidence": 0.9,
"reasoning": "Test execution timed out, likely encountered infinite loop"
}
# Use LLM for deeper analysis
return self._enhanced_llm_verification(method_code, method_info, "infinite_loop")
def _verify_resource_leak(self, method_code, method_info):
"""
Verify resource leak bug with specialized analysis
Parameters:
method_code (str): Method code to verify
method_info (dict): Method information
Returns:
dict: Verification result
"""
# Check for resource allocation patterns
resource_allocation = re.search(r'new\s+(FileInputStream|FileOutputStream|BufferedReader|Scanner|Connection)', method_code)
if resource_allocation:
resource_type = resource_allocation.group(1)
# Check for close method calls
has_close = ".close()" in method_code
# Check for try-with-resources
has_try_resources = re.search(r'try\s*\([^)]*' + resource_type, method_code) is not None
if not has_close and not has_try_resources:
# Test doesn't close resources, might be testing resource leaks
# Check source for close calls
method_name = method_info.get("method_name", "unknown")
source_context = self._extract_related_source_code(method_name)
if ".close()" not in source_context and "try (" not in source_context:
# Source doesn't close resources either, likely a real bug
return {
"is_real_bug": True,
"confidence": 0.85,
"reasoning": f"Resource {resource_type} not closed in either test or source code"
}
# Use LLM for deeper analysis
return self._enhanced_llm_verification(method_code, method_info, "resource_leak")
def _verify_resource_management(self, method_code, method_info):
"""
Verify resource management issues like improper cleanup
Parameters:
method_code (str): Test method code