-
Notifications
You must be signed in to change notification settings - Fork 4
/
RunHolmes.java
2119 lines (1523 loc) · 66.8 KB
/
RunHolmes.java
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
package org.holmes.plugin.actions;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.PumpStreamHandler;
import org.apache.commons.io.FileUtils;
import org.apache.commons.text.similarity.LevenshteinDetailedDistance;
import org.apache.commons.text.similarity.LevenshteinResults;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.ITypeRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.Assignment;
import org.eclipse.jdt.core.dom.BooleanLiteral;
import org.eclipse.jdt.core.dom.CastExpression;
import org.eclipse.jdt.core.dom.CharacterLiteral;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.NumberLiteral;
import org.eclipse.jdt.core.dom.ParenthesizedExpression;
import org.eclipse.jdt.core.dom.PrefixExpression;
import org.eclipse.jdt.core.dom.PrefixExpression.Operator;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.StringLiteral;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.core.dom.VariableDeclarationStatement;
import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.text.edits.TextEdit;
import org.eclipse.ui.IEditorActionDelegate;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.holmes.plugin.nodevisitor.GeneratedTestVisitor;
import org.holmes.plugin.nodevisitor.TestMethodVisitor;
import org.holmes.plugin.util.Test;
public class RunHolmes implements IEditorActionDelegate {
private IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
private IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
private IWorkbenchPage page = window.getActivePage();
public File workingDirectory = new File ("/Users/bjohnson/Documents/Research_2019-2020/causal_testing/Holmes/");
public String testGenJar = workingDirectory.getPath() + "/lib/evosuite-1.0.6.jar";
public String packageNameStart = "org";
public File inputFile;
public Object input;
File binInstrumentedTestDir;
File binInstrumentedDepDir;
IFile testFile;
Document testDocument;
ICompilationUnit icu;
AST ast;
CompilationUnit cu;
ASTParser parser;
// parameter from single method parameter call
Object currentParam;
// parameters from multi-parameter method call
List<Object> currentParams = new ArrayList<>();
boolean isMultiParam;
Test targetTest;
IProject targetProject;
String targetProjectName;
List<IFile> filesToExport = new ArrayList<>();
List<String> passingTests = new ArrayList<>();
List<String> failingTests = new ArrayList<>();
// store input closest to original found in generated tests
String closestGeneratedInput;
// store inputs closest to original for multi-param
// List<String> closestGeneratedInputs;
HashMap<String, List<String>> closestGeneratedInputs = new HashMap<>();
List<Object> executedInputs = new ArrayList<>();
List<String> fuzzedValues = new ArrayList<>();;
HashMap<String[], Integer> editDistances = new HashMap<String[], Integer>();
List<String> distanceResults = new ArrayList<String>();
String[] srcDirectory;
String[] classpath;
@Override
public void run(IAction arg0) {
// IViewPart view;
// try {
// view = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView("org.holmes.plugin.views.HolmesView");
// PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().hideView(view);
// } catch (PartInitException e2) {
// e2.printStackTrace();
// }
// File of interest
IEditorInput input = editor.getEditorInput();
testFile = ((IFileEditorInput)input).getFile();
// get selected method & line number
CompilationUnitEditor editor = (CompilationUnitEditor)this.editor;
ITextSelection selection = getSelection(editor);
int lineNo = selection.getStartLine() +1;
String selectedMethod = selection.getText();
System.out.println("Line number = " + lineNo);
System.out.println("The method under test is: " + selectedMethod);
// create test object
targetTest = new Test(testFile.getName());
targetProjectName = testFile.getProject().getName();
//if training defect, run the rest
if (targetProjectName.equals("Defect_0_Training")) {
runFullProcess(selection, lineNo, selectedMethod);
}
try {
IViewPart output = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView("org.holmes.plugin.views.HolmesView");
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().hideView(output);
TimeUnit.SECONDS.sleep(3);
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView("org.holmes.plugin.views.HolmesView");
}
catch (InterruptedException e) {
e.printStackTrace();
}
catch (PartInitException e) {
e.printStackTrace();
}
}
private void runFullProcess(ITextSelection selection, int lineNo, String selectedMethod) {
// create compilation unit from test file
icu = JavaCore.createCompilationUnitFrom(testFile);
// directory where source project is located (working directory for test generation)
File executorDirectory = new File(workingDirectory.getPath() + "/" + testFile.getProject().getName());
try {
// creation of document containing source code
String source = icu.getSource();
testDocument = new Document(source);
// find source directory
File baseClassDir;
if ((new File(executorDirectory.getPath() + "/bin/").exists())){
baseClassDir = new File(executorDirectory.getPath() + "/bin/");
} else {
baseClassDir = new File(executorDirectory.getPath() + "/target/classes");
}
File srcDir;
if ((new File(executorDirectory.getPath() + "/src").exists())) {
srcDir = new File(executorDirectory.getPath() + "/src/");
} else {
srcDir = new File(executorDirectory.getPath() + "/source/");
}
//get Java project for type bindings
IProject currentProject = testFile.getProject();
IJavaProject javaProject = JavaCore.create(currentProject);
if (javaProject.exists()) {
System.out.println("Java project found!");
classpath = getClasspath(javaProject);
srcDirectory = new String[] {srcDir.getPath()};
// create and set up ASTParser (with source directory and classpath)
updateASTParser();
} else {
System.out.println("No java projects found!");
}
// get parameter of interest
getParamOfInterest(selection, lineNo, selectedMethod, executorDirectory, source);
System.out.println("\nTest file: " + targetTest.getFilename());
System.out.println("Project: " + targetProjectName);
System.out.println("Test method: " + targetTest.getTestMethod());
System.out.println("Target method: " + targetTest.getTargetMethod());
if (targetTest.getOriginalParameter() == null) {
isMultiParam = true;
System.out.println("Original test parameters: ");
for (String s : targetTest.getOriginalParameters()) {
System.out.println(s);
}
} else {
isMultiParam = false;
System.out.println("Original test parameter: " + targetTest.getOriginalParameter());
}
System.out.println("Full test: " + targetTest.getFullTest() + "\n");
// write original test to file to pipe to view later
// writeOriginalTestToFile(workingDirectory.getPath()+"/holmes-output-original.txt");
writeOriginalTestToFile(workingDirectory.getAbsolutePath() + "/holmes-output-original.txt");
String testFile = this.testFile.getName();
String fileUnderTest = testFile.substring(0, testFile.indexOf("Test"));
String targetFilePackage = "";
String classDir = baseClassDir.getAbsolutePath();
// find file under test
boolean recursive = true;
Collection files = FileUtils.listFiles(srcDir, null, recursive);
for (Iterator i = files.iterator(); i.hasNext();) {
File f = (File) i.next();
// only check files that are java files
if (f.getName().contains(".java")) {
String className = f.getName().substring(0, f.getName().indexOf(".java"));
// check if target file; if so, store necessary information
if (className.equals(fileUnderTest)) {
System.out.println("Path to target file = " + f.getAbsolutePath());
File targetFileDir = new File (f.getAbsolutePath());
String pathToFile = targetFileDir.getAbsolutePath();
targetFilePackage = pathToFile.substring(pathToFile.indexOf("org"), pathToFile.length()-5).replace("/", ".");
String targetFileDirectory = targetFilePackage.substring(0, targetFilePackage.lastIndexOf("."));
classDir = baseClassDir + "/" + targetFileDirectory.replace(".", "/");
System.out.println("Working directory = " + executorDirectory.getPath());
System.out.println("File package = " + targetFilePackage);
System.out.println("Class file directory = " + classDir);
}
}
}
/*
* RUN EVOSUITE
*/
// runEvoSuite(executorDirectory, targetFilePackage, baseClassDir.getAbsolutePath());
/*
* PARSE TESTS FOR INPUTS
*/
List<String> evoGeneratedInputs = new ArrayList<>();
String targetMethod = targetTest.getTargetMethod();
System.out.println(targetMethod);
// directory with tests
targetFilePackage = targetFilePackage.substring(0, targetFilePackage.lastIndexOf("."));
File evoTestsDir = new File(executorDirectory.getAbsolutePath() + "/evosuite-tests/" + targetFilePackage.replace(".", "/"));
System.out.println(evoTestsDir.getAbsolutePath());
// find and parse files in directory
File[] testFiles = evoTestsDir.listFiles();
parseGeneratedTests(targetMethod, testFiles);
if (isMultiParam) {
System.out.println("\n Original parameters are --> " + targetTest.getOriginalParameters());
} else {
System.out.println("\n Original parameter is --> " + targetTest.getOriginalParameter());
}
/*
* RUN INPUT FUZZERS
*/
String cmdLineArg = "";
// Run fuzzers with original input(s)
// TODO update to iterate over currentParams (Literal, Decls, Assigns) not originalParameters (Strings)
if (isMultiParam) {
List<String> params = targetTest.getOriginalParameters();
for (int i=0; i < params.size(); i++) {
String param = params.get(i);
if (param.contains("=")) {
cmdLineArg = param.substring(param.indexOf("="), param.indexOf(";")).replaceAll("\"", "");
} else {
cmdLineArg = params.get(i).replaceAll("\"", "");
}
System.out.println("Input to fuzz --> " + cmdLineArg);
String fileId = Integer.toString(i);
runFuzzers(cmdLineArg, true, fileId);
}
} else {
cmdLineArg = targetTest.getOriginalParameter().replaceAll("\"", "");
System.out.println("Input to fuzz --> " + cmdLineArg);
runFuzzers(cmdLineArg, true, "1");
}
// Run fuzzers with generated input(s)
Iterator it = closestGeneratedInputs.entrySet().iterator();
// iterate over each parameter (will only be multiple iterations if multiple parameters)
int param_count = 0;
while (it.hasNext()) {
Map.Entry<String, List<String>> pair = (Map.Entry<String, List<String>>) it.next();
List<String> genParams = pair.getValue();
List<String> noDups = new ArrayList<>(new HashSet<>(genParams));
for (int i=0; i < noDups.size(); i++) {
cmdLineArg = noDups.get(i).replaceAll("\"", "");
System.out.println("Input to fuzz --> " + cmdLineArg);
String paramId = Integer.toString(param_count);
String fileId = Integer.toString(i);
runFuzzers(cmdLineArg, false, paramId+ "_"+ fileId);
}
param_count ++;
}
/*
* PARSE FUZZER OUTPUT & EXECUTE TESTS
*/
// parse original mutation files
if (isMultiParam) {
List<String> originalParams = targetTest.getOriginalParameters();
for (int i=0; i<originalParams.size(); i++) {
String fileId = Integer.toString(i);
File original_fuzzed = new File(workingDirectory.getPath() + "/fuzzers/fuzzer_results_original_" + fileId + ".txt");
if (original_fuzzed.exists()) {
BufferedReader br = new BufferedReader(new FileReader(original_fuzzed));
int threshold = 2;
int paramPlace = i;
updateAndRunTest(lineNo, executorDirectory, originalParams, i, br, threshold, paramPlace, false);
}
}
} else {
File original_fuzzed = new File(workingDirectory.getPath() + "/fuzzers/fuzzer_results_original_1.txt");
String original = targetTest.getOriginalParameter();
if (original_fuzzed.exists()) {
BufferedReader br = new BufferedReader(new FileReader(original_fuzzed));
int threshold = 2;
//create list to store original param for updateAndRunTest (TODO: refactor)
List<String> originalParams = new ArrayList<>();
originalParams.add(original);
updateAndRunTest(lineNo, executorDirectory, originalParams, 0, br, threshold, 0, false);
}
}
// parse generated mutation files
Iterator it2 = closestGeneratedInputs.entrySet().iterator();
// iterate over each parameter (will only be multiple iterations if multiple parameters)
int param_num = 0;
while (it.hasNext()) {
Map.Entry<String, List<String>> pair = (Map.Entry<String, List<String>>) it.next();
List<String> genParams = pair.getValue();
for (int i=0; i<genParams.size(); i++) {
String fileId = Integer.toString(i);
File generated_fuzzed = new File(workingDirectory.getPath() + "/fuzzers/fuzzer_results_generated_" + param_num + "_" + fileId);
if (generated_fuzzed.exists()) {
BufferedReader br = new BufferedReader(new FileReader(generated_fuzzed));
String line = "";
int threshold = 2;
int distance = 0;
int paramPlace = i;
updateAndRunTest(lineNo, executorDirectory, genParams, i, br, threshold, paramPlace, false);
}
}
param_num++;
}
writeOutputFile();
// Restore original parameter(s)
if (isMultiParam) {
// TODO
} else {
List<String> param = new ArrayList<>();
param.add(targetTest.getOriginalParameter());
updateAndRunTest(0, executorDirectory, param, 0, new BufferedReader(new FileReader(workingDirectory.getAbsolutePath() + "/holmes-output-original.txt")), 2, 0, true);
}
} catch (JavaModelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// catch (ExecuteException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void updateAndRunTest(int lineNo, File executorDirectory, List<String> originalParams, int i,
BufferedReader br, int threshold, int paramPlace, boolean last)
throws IOException, BadLocationException, JavaModelException, InterruptedException, ExecuteException {
String line;
int distance;
if (last) {
updateTestInput(0, originalParams.get(0));
savePage(page);
} else {
while ((line = br.readLine() )!= null) {
if ((failingTests.size() < 3 && passingTests.size() < 3)) {
// find inputs within threshold and run
if (isValidNumber(line)) {
Object oldNum = determineNumType(originalParams.get(i));
Object newNum = determineNumType(line);
// check if generated/fuzzed input same type as original (so compiles and runs)
if (oldNum instanceof Integer && newNum instanceof Integer) {
Integer originalNum = (Integer) oldNum;
Integer fuzzNum = (Integer) newNum;
// see how close fuzzed input is from original
distance = Math.abs(originalNum.intValue()-fuzzNum.intValue());
// if difference is within threshold, run test with that input
if (distance > 0 && distance <= threshold) {
executedInputs.add(fuzzNum);
// update and save page
updateTestInput(paramPlace, fuzzNum);
savePage(page);
// wait for build to finish before running test
TimeUnit.SECONDS.sleep(2);
// update AST parser
updateASTParser();
getMethodParameters(testDocument.get(), targetTest.getTargetMethod(), targetTest.getTestMethod(), false, lineNo);
// D4J compile
d4jCompile(executorDirectory);
// D4J test
d4jTest(executorDirectory);
}
} else if (oldNum instanceof Double && newNum instanceof Double) {
Double originalNum = (Double) oldNum;
Double fuzzNum = (Double) newNum;
distance = (int) Math.abs(originalNum.doubleValue()-fuzzNum.doubleValue());
if (distance > 0 && distance <= threshold) {
executedInputs.add(fuzzNum);
// update and save page
updateTestInput(paramPlace, fuzzNum);
savePage(page);
// wait for build to finish before running test
TimeUnit.SECONDS.sleep(2);
// update AST parser
updateASTParser();
getMethodParameters(testDocument.get(), targetTest.getTargetMethod(), targetTest.getTestMethod(), false, lineNo);
// D4J compile
d4jCompile(executorDirectory);
// D4J test
d4jTest(executorDirectory);
}
} else if (oldNum instanceof Float && newNum instanceof Float) {
Float originalNum = (Float) oldNum;
Float fuzzNum = (Float) newNum;
distance = (int) Math.abs(originalNum.floatValue()-fuzzNum.floatValue());
if (distance > 0 && distance <= threshold) {
executedInputs.add(fuzzNum);
// update and save page
updateTestInput(paramPlace, fuzzNum);
savePage(page);
// wait for build to finish before running test
TimeUnit.SECONDS.sleep(2);
// update AST parser
updateASTParser();
getMethodParameters(testDocument.get(), targetTest.getTargetMethod(), targetTest.getTestMethod(), false, lineNo);
// D4J compile
d4jCompile(executorDirectory);
// D4J test
d4jTest(executorDirectory);
}
} else if(oldNum instanceof Long && newNum instanceof Long) {
Long originalNum = (Long) oldNum;
Long fuzzNum = (Long) newNum;
distance = (int) Math.abs(originalNum.longValue()-fuzzNum.longValue());
if (distance > 0 && distance <= threshold) {
executedInputs.add(fuzzNum);
// update and save page
updateTestInput(paramPlace, fuzzNum);
savePage(page);
// wait for build to finish before running test
TimeUnit.SECONDS.sleep(2);
// update AST parser
updateASTParser();
getMethodParameters(testDocument.get(), targetTest.getTargetMethod(), targetTest.getTestMethod(), false, lineNo);
// D4J compile
d4jCompile(executorDirectory);
// D4J test
d4jTest(executorDirectory);
}
} else if (oldNum instanceof BigInteger && newNum instanceof BigInteger) {
BigInteger originalNum = (BigInteger) oldNum;
BigInteger fuzzNum = (BigInteger) newNum;
distance = Math.abs(originalNum.intValue()-fuzzNum.intValue());
if (distance > 0 && distance <= threshold) {
executedInputs.add(fuzzNum);
// update and save page
updateTestInput(paramPlace, fuzzNum);
savePage(page);
// wait for build to finish before running test
TimeUnit.SECONDS.sleep(2);
// update AST parser
updateASTParser();
getMethodParameters(testDocument.get(), targetTest.getTargetMethod(), targetTest.getTestMethod(), false, lineNo);
// D4J compile
d4jCompile(executorDirectory);
// D4J test
d4jTest(executorDirectory);
}
} else if (oldNum instanceof BigDecimal && newNum instanceof BigDecimal) {
BigDecimal originalNum = (BigDecimal) oldNum;
BigDecimal fuzzNum = (BigDecimal) newNum;
distance = (int) Math.abs(originalNum.floatValue()-fuzzNum.floatValue());
if (distance > 0 && distance <= threshold) {
executedInputs.add(fuzzNum);
// update and save page
updateTestInput(paramPlace, fuzzNum);
savePage(page);
// wait for build to finish before running test
TimeUnit.SECONDS.sleep(2);
// update AST parser
updateASTParser();
getMethodParameters(testDocument.get(), targetTest.getTargetMethod(), targetTest.getTestMethod(), false, lineNo);
// D4J compile
d4jCompile(executorDirectory);
// D4J test
d4jTest(executorDirectory);
}
}
} else {
if (!line.startsWith("FuzzManager")) {
String oldString = originalParams.get(i);
String fuzzString = line;
distance = levenshteinDistance(oldString, fuzzString);
if (distance > 0 && distance <= threshold) {
executedInputs.add(fuzzString);
// update and save page
updateTestInput(paramPlace, fuzzString);
savePage(page);
// wait for build to finish before running test
TimeUnit.SECONDS.sleep(2);
// update AST parser
updateASTParser();
getMethodParameters(testDocument.get(), targetTest.getTargetMethod(), targetTest.getTestMethod(), false, lineNo);
// D4J compile
d4jCompile(executorDirectory);
// D4J test
d4jTest(executorDirectory);
}
}
}
}
}
}
}
private String[] getClasspath(IJavaProject javaProject) throws JavaModelException {
IClasspathEntry[] rawClassPath = javaProject.getRawClasspath();
String[] classpathEntries = new String[rawClassPath.length];
for (int i=0; i < rawClassPath.length; i++) {
classpathEntries[i] = rawClassPath[i].toString();
}
IJavaElement element = JavaCore.create(testFile);
ICompilationUnit icu = (ICompilationUnit) element;
return classpathEntries;
}
private void getParamOfInterest(ITextSelection selection, int lineNo, String selectedMethod, File executorDirectory,
String source) throws JavaModelException {
boolean first = true;
// get test method of selected method
int selectionOffset = selection.getOffset();
ITypeRoot root = EditorUtility.getEditorInputJavaElement(this.editor, false);
IJavaElement selectedElement = root.getElementAt(selectionOffset);
String targetTestMethod = selectedElement.getElementName();
// pass target method into visitor to get test method and other relevant parts
getMethodParameters(source, selectedMethod, targetTestMethod, first, lineNo);
targetTest.setTargetMethod(selectedMethod);
}
private String updateTestInput(int paramPlace, Object param)
throws BadLocationException, JavaModelException {
// Creation of ASTRewrite
ASTRewrite rewrite = ASTRewrite.create(ast);
String newSource = null;
if (isMultiParam) {
for (int i=0; i<targetTest.getOriginalParameters().size(); i++) {
Object current = currentParams.get(i);
// see if original was a variable declaration or assignment so we know what to create/update
if (current instanceof VariableDeclarationStatement) {
VariableDeclarationStatement stmt = (VariableDeclarationStatement) current;
String type = stmt.getType().toString();
if (type.equals("boolean")) {
BooleanLiteral newParam;
if ((boolean) current) {
newParam = ast.newBooleanLiteral(false);
} else {
newParam = ast.newBooleanLiteral(true);
}
newSource = replaceVariableDeclaration(rewrite, newParam, type);
} else if (type.equals("String")) {
StringLiteral newParam = ast.newStringLiteral();
newSource = replaceVariableDeclaration(rewrite, newParam, type);
} else if (type.equals("int") || type.equals("float") || type.equals("double")|| type.equals("short")
|| type.equals("long")) {
NumberLiteral newParam = ast.newNumberLiteral();
newSource = replaceVariableDeclaration(rewrite, newParam, type);
}
} else if (current instanceof Assignment) {
// TODO
} else {
// Literals
newSource = replaceASTLiteral(rewrite, paramPlace, param);
}
}
} else {
if (currentParam instanceof VariableDeclarationStatement) {
VariableDeclarationStatement stmt = (VariableDeclarationStatement) currentParam;
String type = stmt.getType().toString();
if (type.equals("boolean")) {
BooleanLiteral newParam;
if ((boolean) currentParam) {
newParam = ast.newBooleanLiteral(false);
} else {
newParam = ast.newBooleanLiteral(true);
}
newSource = replaceVariableDeclaration(rewrite, newParam, type);
} else if (type.equals("String")) {
StringLiteral newParam = ast.newStringLiteral();
newSource = replaceVariableDeclaration(rewrite, newParam, type);
} else if (type.equals("int") || type.equals("float") || type.equals("double")|| type.equals("short")
|| type.equals("long")) {
NumberLiteral newParam = ast.newNumberLiteral();
newSource = replaceVariableDeclaration(rewrite, newParam, type);
}
} else if (currentParam instanceof Assignment) {
// TODO
} else {
newSource = replaceASTLiteral(rewrite, paramPlace, param);
}
}
return newSource;
}
private String replaceASTLiteral(ASTRewrite rewrite, int paramPlace, Object param)
throws BadLocationException, JavaModelException {
String newSource = "";
if (isMultiParam) {
// get current params
for (int i=0; i<currentParams.size(); i++) {
Object current = currentParams.get(i);
Expression oldParam = (Expression) current;
if (i == paramPlace) {
if (isValidNumber(param.toString())) {
NumberLiteral newParam = ast.newNumberLiteral();
newParam.setToken(param.toString());
rewrite.replace(oldParam, newParam, null);
} else if (param.toString().startsWith("-")) {
PrefixExpression newParam = ast.newPrefixExpression();
newParam.setOperator(Operator.MINUS);
if (isValidNumber(oldParam.toString())) {
NumberLiteral num = ast.newNumberLiteral();
String paramWithSign = param.toString();
String paramWOSign = paramWithSign.substring(1, paramWithSign.length());
num.setToken(paramWOSign);
newParam.setOperand(num);
rewrite.replace(oldParam, newParam, null);
}
} else if (param.toString().startsWith("(") && param.toString().endsWith(")")) {
ParenthesizedExpression newParam = ast.newParenthesizedExpression();
if (isValidNumber(oldParam.toString())) {
NumberLiteral num = ast.newNumberLiteral();
String paramWithParens = param.toString();
String paramWOParens = paramWithParens.substring(1,paramWithParens.length()-1);
num.setToken(paramWOParens);
rewrite.replace(oldParam, newParam, null);
}
} else if (current instanceof BooleanLiteral) {
} else if (current instanceof StringLiteral) {
StringLiteral newParam = ast.newStringLiteral();
newParam.setLiteralValue(param.toString());
rewrite.replace(oldParam, newParam, null);
} else if (current instanceof CharacterLiteral && param.toString().length()==1) {
CharacterLiteral newParam = ast.newCharacterLiteral();
char newChar = param.toString().charAt(0);
newParam.setCharValue(newChar);
rewrite.replace(oldParam, newParam, null);
}
}
}
} else {
// handle each primitive type / simple expression accordingly
Expression oldParam = (Expression) currentParam;
if (isValidNumber(param.toString())) {
NumberLiteral newParam = ast.newNumberLiteral();
newParam.setToken(param.toString());
rewrite.replace(oldParam, newParam, null);
} else if (param.toString().startsWith("-")) {
PrefixExpression newParam = ast.newPrefixExpression();
newParam.setOperator(Operator.MINUS);
if (isValidNumber(oldParam.toString())) {
NumberLiteral num = ast.newNumberLiteral();
String paramWithSign = param.toString();
String paramWOSign = paramWithSign.substring(1, paramWithSign.length());
num.setToken(paramWOSign);
newParam.setOperand(num);
rewrite.replace(oldParam, newParam, null);
}
} else if (param.toString().startsWith("(") && param.toString().endsWith(")")) {
ParenthesizedExpression newParam = ast.newParenthesizedExpression();
if (isValidNumber(oldParam.toString())) {
NumberLiteral num = ast.newNumberLiteral();
String paramWithParens = param.toString();
String paramWOParens = paramWithParens.substring(1,paramWithParens.length()-1);
num.setToken(paramWOParens);
rewrite.replace(oldParam, newParam, null);
}
} else if (currentParam instanceof StringLiteral){
StringLiteral newParam = ast.newStringLiteral();
newParam.setLiteralValue(param.toString());
rewrite.replace(oldParam, newParam, null);
} else if (currentParam instanceof BooleanLiteral) {
BooleanLiteral newParam;
if ((boolean) currentParam) {
newParam = ast.newBooleanLiteral(false);
} else {
newParam = ast.newBooleanLiteral(true);
}
} else if (currentParam instanceof CharacterLiteral && param.toString().length() == 1) {
CharacterLiteral newParam = ast.newCharacterLiteral();
newParam.setCharValue((char)param);
rewrite.replace(oldParam, newParam, null);
}
}
TextEdit edits = rewrite.rewriteAST(testDocument, JavaCore.getOptions());
edits.apply(testDocument);
newSource = testDocument.get();
icu.getBuffer().setContents(newSource);
return newSource;
}
private void runTests(IWorkbenchPage page, File executorDirectory, Object newParam, int lineNo)
throws BadLocationException, JavaModelException, InterruptedException, ExecuteException, IOException {
// update and save page