-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathAutograder.java
More file actions
2889 lines (2729 loc) · 120 KB
/
Autograder.java
File metadata and controls
2889 lines (2729 loc) · 120 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
import java.util.List;
import java.util.ArrayList;
//import java.util.Scanner;
import java.util.Random;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.OutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import javax.tools.ToolProvider;
import javax.tools.JavaCompiler;
import java.lang.reflect.Method;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.ProcessBuilder.Redirect;
import org.junit.runner.notification.RunListener;
import org.junit.runner.JUnitCore;
import java.util.concurrent.FutureTask;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.TimeUnit;
import java.lang.SecurityManager;
import java.lang.SecurityException;
import java.security.Permission;
import com.puppycrawl.tools.checkstyle.Main;
import jh61b.grader.TestResult;
import jh61b.grader.TestResultList;
import brandon.math.Math;
import brandon.convert.ClassConverter;
import brandon.convert.ClassConverterList;
//import brandon.util.Scanner;
/**
Classs representing an autograder.
It's main method is the running of the autograder
and instances can be made to store all important information.
@author Brandon Lax
*/
public class Autograder {
/**A checksum to ensure all additions of tests.*/
private long checksum;
/** The value of each test.*/
protected double maxScore;
/**The current test number we are on.*/
protected int diffNum;
/**The visibilty for the current gradescope test.*/
protected String visibility;
/**The list of all tests performed.*/
private TestResultList allTestResults;
/**The current junit test.*/
private TestResult currentJunitTestResult;
private static ClassConverterList conversions = new ClassConverterList();
/**The location of the checkstyle Jar.*/
public static final String CHECKSTYLE_JAR = "/autograder/source/checkstyle/checkstyle-8.28-all.jar";
/**The location of the checkstyle xml.*/
public static final String CHECKSTYLE_XML = "/autograder/source/checkstyle/check112.xml";
public static final String CHECKSTYLE_LISTEN_XML = "/autograder/source/checkstyle/check112listen.xml";
//public static final String CHECKSTYLE_LISTEN_XML = "checkstyle/check112listen.xml";
/**The amount of time to wait before timing out a test that runs student code.*/
private long waitTime = 1;
/**
The Autograder class constructor.
Initializes the list of all tests.
@param visible The visibility of the result to students see {@link #setVisibility(int) setvisibility}
@param score The amount of points a test is worth
*/
public Autograder(int visible, double score) {
Random r = new Random();
this.checksum = r.nextLong();
this.allTestResults = new TestResultList(this.checksum);
this.diffNum = 1;
this.setVisibility(visible);
this.setScore(score);
this.disableSystemExit();
}
private void disableSystemExit() {
SecurityManager securityManager = new StopExitSecurityManager();
System.setSecurityManager(securityManager) ;
}
private void enableSystemExit() {
SecurityManager mgr = System.getSecurityManager();
if ((mgr != null) && (mgr instanceof StopExitSecurityManager)) {
StopExitSecurityManager smgr = (StopExitSecurityManager)mgr;
System.setSecurityManager(smgr.getPreviousMgr());
}
else {
System.setSecurityManager(null);
}
}
/**
The Autograder class constructor.
Initializes the list of all tests.
Also sets the visibility to hidden and
the score to 0.1
*/
public Autograder() {
this(1, 0.1);
}
/** Method to add a seperately made test to the results.
This allows for people to make child classes of the autograder
if they need tests that dont currently exist that they would
prefer to avoid adding to this class. For an example see
{@link PictureAutograder}
@param t the test to be added to the output
*/
public void addTestResult(TestResult t) {
this.allTestResults.add(t, this.checksum);
}
/** Method to add a user written converter to the autograder.
Converters are used for the comp tests. This allows you
to make comp tests that work with parameters and returns
other than the base primitive types and string. A converter
takes a string of text and turns it into the desired object
and performs the reverse operation as well. See
{@link brandon.convert.ClassConverter}.
@param c The converter to add to the autograder
*/
public static void addConverter(ClassConverter c) {
Autograder.conversions.add(c);
}
/** This is the wrap-up code of the autograder.
<b>Must be the last line of the main method.</b> It
prints all of the results in a JSON format to
standard out.
@throws Exception fails to create json for a test
*/
public void testRunFinished() throws Exception {
this.enableSystemExit();
/* Dump allTestResults to StdOut in JSON format. */
ArrayList<String> objects = new ArrayList<String>();
for (TestResult tr : this.allTestResults.toArray(this.checksum)) {
objects.add(tr.toJSON());
}
String testsJSON = String.join(",", objects);
System.out.println("{" + String.join(",", new String[] {
String.format("\"tests\": [%s]", testsJSON)}) + "}");
System.exit(0);
}
/** This is the wrap-up code of the autograder.
<b>Must be the last line of the main method.</b> It
prints all of the results in a JSON format to
a specified file.
@param filename the file to write the output to
@throws Exception fails to create json for a test
*/
public void testRunFinished(String filename) throws Exception {
this.enableSystemExit();
/* Dump allTestResults to StdOut in JSON format. */
PrintWriter pw = new PrintWriter(filename);
ArrayList<String> objects = new ArrayList<String>();
for (TestResult tr : this.allTestResults.toArray(this.checksum)) {
objects.add(tr.toJSON());
}
String testsJSON = String.join(",", objects);
pw.println("{" + String.join(",", new String[] {
String.format("\"tests\": [%s]", testsJSON)}) + "}");
pw.close();
System.exit(0);
}
/**
* Test to check if source file exists.
* Will output whether the file exists as well as
* add a junit test for it.
* @param programName the program name (can include or not include the .java)
* @return whether or not the source exists
*/
public boolean testSourceExists(String programName) {
boolean sourceExists = false;
File source;
if (programName.indexOf(".") == -1) {
source = new File(programName + ".java");
} else {
source = new File(programName);
}
TestResult trSourceFile = new TestResult(programName +
" Source File Exists",
"Pre-Test",
this.maxScore,
this.visibility);
if (!source.exists() || source.isDirectory()) { // source not present
trSourceFile.setScore(0);
trSourceFile.addOutput("ERROR: file " + programName +
".java is not present!\n");
trSourceFile.addOutput("\tCheck the spelling of your file name.\n");
} else { // source present
trSourceFile.setScore(this.maxScore);
trSourceFile.addOutput("SUCCESS: file " + programName +
".java is present!\n");
sourceExists = true;
}
this.allTestResults.add(trSourceFile, this.checksum);
return sourceExists;
}
/**
Method to compile a java file for you.
NOTE: <b> This is not a test </b>
This just compiles a file. It is useful
for when you need a test file but dont want
to compile it until you know with certainty
that the base file compiles.
@param fileName The filename of the file to compile
@return the int result of the java compiler 0 for success, nonzero otherwise
*/
public int compile(String fileName) {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
return compiler.run(null, null, null, fileName);
}
/** Function to test if a class compiles.
Outputs whether the file compiles as well as
adds an additional gradescope test for it.
If the program fails due to unmappable characters,
the test will automatically be made visible as this is
a problem created on gradescope and might not be a problem
that a student will see on their own device.
@param programName the name of the java file to test (without the .java)
@return whether the class compiled
*/
public boolean testCompiles(String programName) {
boolean passed = false;
TestResult trCompilation = new TestResult(programName + " Compiles",
"Pre-Test", this.maxScore,
this.visibility);
String fileName = programName + ".java";
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayOutputStream err = new ByteArrayOutputStream();
int compilationResult = compiler.run(null, out, err, fileName);
if (compilationResult != 0) {
String output = new String(out.toByteArray());
String error = new String(err.toByteArray());
if (error.contains("unmappable character")) {
trCompilation = new TestResult(programName + " Compiles",
"Pre-Test", this.maxScore,
"visible");
}
trCompilation.setScore(0);
trCompilation.addOutput("ERROR: " + programName +
".java did not compile!\n");
trCompilation.addOutput("Output: " + output + "\n"
+ "Error: " + error);
}
else {
trCompilation.setScore(this.maxScore);
trCompilation.addOutput("SUCCESS: " + programName +
".java compiled successfully!\n");
passed = true;
}
this.allTestResults.add(trCompilation, this.checksum);
return passed;
}
/**
* Checks if checkstyle passed.
* Creates a gradescope test with the
* results from checkstyle and gives the
* output to the grader. Relies on having
* the checkstyle files (the jar and xml)
* in the location of CHECKSTYLE_JAR and
* CHECKSTYLE_XML. Please change those to
* match the location for your class.
* This also assumes that the java files
* is in the source folder of the
* autograder when uploaded to gradescope.
* @param programName the java class name (without the .java)
*/
public void testCheckstyle(String programName) {
TestResult trCheck = new TestResult(programName + "Checkstyle Compliant",
"Pre-Test",
this.maxScore, this.visibility);
String result;
try {
String proc = "java -jar " + CHECKSTYLE_JAR +
" -c " + CHECKSTYLE_XML + " /autograder/source/" +
programName + ".java";
Process check = Runtime.getRuntime().exec(proc);
check.waitFor();
java.util.Scanner s = new java.util.Scanner(check.getInputStream()).useDelimiter("\\A");
result = s.hasNext() ? s.next() : "";
//no problems reported in checkstylefile; it passed checkstyle
if (result.equals("Starting audit...\nAudit done.\n")) {
trCheck.setScore(this.maxScore);
trCheck.addOutput("SUCCESS: " + programName +
" passed checkstyle with no warnings\n");
}
else { //something in checkstylefile; it failed checkstyle
trCheck.setScore(0);
trCheck.addOutput("ERROR: " + programName +
" did not pass checkstyle." +
" Results are below:\n" + result);
}
} catch (IOException e) {
return;
} catch (InterruptedException e) {
return;
}
this.allTestResults.add(trCheck, this.checksum);
}
/**
A test that runs a checkstyle test sorting the output.
This test takes off for either each type of mistake or
each mistake that a student has.
It also formats the output for easy grading by hand. It
shows each type of error and all the lines on which that error occurs.
To use this test you need the CHECKSTYLE_LISTEN_XML to match the location
of the xml file you use and this xml file has to have the listener configured
as specified in the README.
@param programName the classname of the java file to run the test one
@param errValue the number of points lost per type of checkstyle error
@param perType true if taking off per type of mistake, false if per mistake
*/
public void testSortedCheckstyle(String programName, double errValue, boolean perType) {
PrintStream originalOut = System.out;
try {
GatewayCheckstyleListener.setDefaultValues(this.maxScore, errValue, this.visibility, perType);
System.setOut(new PrintStream(
new OutputStream() {
public void write(int b) {
}
}));
Main.main("-c", CHECKSTYLE_LISTEN_XML, programName + ".java");
} catch(ExitTrappedException e) {
//Ignore the exception
} catch (Exception e) {
System.err.println("Failed to run checkstyle on file: " + programName + "\n");
}
System.setOut(originalOut);
List<TestResult> all = GatewayCheckstyleListener.getResults();
this.allTestResults.addAll(all, this.checksum);
}
/**
Runs all the diff tests for a specific file.
This runs count diff tests each one using the naming
convetion on the next line for the name of the input file.
All input files are named: {Program_Name}_Diff_#.in
The diff test have the option of not using a sample program
and instead using already made output files. This approach
is good if there is a sample run created.
The expected output should be named:
{program_Name}_#.expected
@param name the name of the program to do diff tests on
@param count the number of diffs to perform
@param sampleFile true if using a sample program false if just comparing to a file.
@param ignoreWhitespace true if want to ignore whitespace false otherwise
*/
public void stdOutDiffTests(String name, int count, boolean sampleFile, boolean ignoreWhitespace) {
this.stdOutDiffTests(name, count, sampleFile, ignoreWhitespace, 0);
}
/**
Runs all the diff tests for a specific file.
This runs count diff tests each one using the naming
convetion on the next line for the name of the input file.
All input files are named: {Program_Name}_Diff_#.in
The diff test have the option of not using a sample program
and instead using already made output files. This approach
is good if there is a sample run created.
The expected output should be named:
{program_Name}_#.expected
This version allows for a certain amount to be forced to be
hidden.
@param name the name of the program to do diff tests on
@param count the number of diffs to perform
@param sampleFile true if using a sample program false if just comparing to a file.
@param ignoreWhitespace true if want to ignore whitespace false otherwise
@param numVisible The number of tests that should be visible instead of what visibility is set to (count - numVisible) = numHidden
*/
public void stdOutDiffTests(String name, int count, boolean sampleFile, boolean ignoreWhitespace, int numVisible) {
PrintStream originalOut = System.out;
InputStream originalIn = System.in;
if (sampleFile) {
this.compile(name+"Sample.java");
}
String visible = this.visibility;
this.setVisibility(0);
for (int i = 0; i < count; i++) {
Math.resetRandom();
if (i >= numVisible) {
this.visibility = visible;
}
TestResult trDiff = new TestResult(name + " Standard Output Diff Test #" + i,
"" + this.diffNum,
this.maxScore, this.visibility);
this.diffNum++;
String input = name + "_Diff_" + i + ".in";
String exOut = name + i + ".expected";
String acOut = name + "_" + i + ".out";
try {
File exfile = new File(exOut);
File infile = new File(input);
File acfile = new File(acOut);
File sample = new File(name + "Sample.java");
if (sampleFile && sample.exists() && !sample.isDirectory()) {
String[] procSample = {"java", name + "Sample"};
ProcessBuilder pbSample = new ProcessBuilder(procSample);
pbSample.redirectOutput(Redirect.to(exfile));
pbSample.redirectInput(Redirect.from(infile));
Process sampleProcess = pbSample.start();
sampleProcess.waitFor();
}
PrintStream out = new PrintStream(new FileOutputStream(acOut));
System.setOut(out);
System.setIn(new FileInputStream(input));
Class<?> act = Class.forName(name);
if (act == null) {
throw new ClassNotFoundException();
}
Method main = act.getMethod("main", String[].class);
if (main == null) {
throw new NoSuchMethodException();
}
String[] strings = new String[0];
this.runMethodWithTimeout(main, null, ((Object)strings));
out.flush();
out.close();
diffFiles(trDiff, name, exOut, acOut, ignoreWhitespace);
} catch (IOException e) {
trDiff.setScore(0);
trDiff.addOutput("ERROR: " + name +
" could not be found to run Diff Test");
} catch (InterruptedException e) {
trDiff.setScore(0);
trDiff.addOutput("ERROR: " + name +
" got interrupted");
} catch (ClassNotFoundException e) {
trDiff.setScore(0);
trDiff.addOutput("ERROR: " + name +
" could not be found to run Diff Test");
} catch (NoSuchMethodException e) {
trDiff.setScore(0);
trDiff.addOutput("ERROR: Students " +
name + " Main method not found");
} catch (IllegalAccessException e) {
trDiff.setScore(0);
trDiff.addOutput("ERROR: Students code not accessible");
} catch (InvocationTargetException e) {
Throwable et = e.getCause();
Exception es;
if(et instanceof Exception) {
es = (Exception) et;
} else {
es = e;
}
if (es instanceof ExitTrappedException) {
trDiff.setScore(0);
trDiff.addOutput("ERROR: Do not use System.exit() in your code"
+ " its bad practice and can cause the autograder" +
" to crash.");
} else {
String sStackTrace = stackTraceToString(es);
trDiff.setScore(0);
trDiff.addOutput("ERROR: Students code threw " +
es + "\n Stack Trace: " +
sStackTrace);
}
} catch (TimeoutException e) {
trDiff.setScore(0);
trDiff.addOutput("ERROR: Main Method Timed out after "+ waitTime + " Seconds");
} catch (ExecutionException e) {
Throwable et = e.getCause();
Exception es;
if(et instanceof Exception) {
es = (Exception) et;
} else {
es = e;
}
if (es instanceof InvocationTargetException) {
et = es.getCause();
if(et instanceof Exception) {
es = (Exception) et;
} else {
es = e;
}
}
if (es instanceof ExitTrappedException) {
diffFiles(trDiff, name, exOut, acOut, ignoreWhitespace);
} else {
String sStackTrace = stackTraceToString(es);
trDiff.setScore(0);
trDiff.addOutput("ERROR: Students code threw " +
es + "\n Stack Trace: " +
sStackTrace);
}
}
this.allTestResults.add(trDiff, this.checksum);
System.setOut(originalOut);
}
this.visibility = visible;
}
/**
Runs a diff test on the std output of a specific java program.
This test runs one diff test comparing the output of the java program
against either a sampole implementation or a hand written file.
These tests rely on redirecting input from a file to standard
input. These tests will not work as expected if the student
opens multiple Scanners to read from standard input. inFile
should be a filename without an extension. Thsi test auto-appends
extensions onto the filename. The input file should end in .in,
the expected output file should end in .expected and the program
will always create the students output file which will end in
.out.
@param name the name of the java program to do diff tests on
@param inFile the name of the test input file to use without an extension
@param sampleFile true if using a sample program false if just comparing to a file.
@param ignoreWhitespace true if want to ignore whitespace false otherwise
*/
public void stdOutDiffTest(String name, String inFile, boolean sampleFile, boolean ignoreWhitespace) {
PrintStream originalOut = System.out;
InputStream originalIn = System.in;
if (sampleFile) {
this.compile(name+"Sample.java");
}
Math.resetRandom();
TestResult trDiff = new TestResult(name + " Standard Output Diff Test For " + inFile,
"" + this.diffNum,
this.maxScore, this.visibility);
this.diffNum++;
String input = inFile + ".in";
String exOut = inFile + ".expected";
String acOut = inFile + ".out";
try {
File exfile = new File(exOut);
File infile = new File(input);
File acfile = new File(acOut);
File sample = new File(name + "Sample.java");
if (sampleFile && sample.exists() && !sample.isDirectory()) {
String[] procSample = {"java", name + "Sample"};
ProcessBuilder pbSample = new ProcessBuilder(procSample);
pbSample.redirectOutput(Redirect.to(exfile));
pbSample.redirectInput(Redirect.from(infile));
Process sampleProcess = pbSample.start();
sampleProcess.waitFor();
}
PrintStream out = new PrintStream(new FileOutputStream(acOut));
System.setOut(out);
System.setIn(new FileInputStream(input));
Class<?> act = Class.forName(name);
if (act == null) {
throw new ClassNotFoundException();
}
Method main = act.getMethod("main", String[].class);
if (main == null) {
throw new NoSuchMethodException();
}
String[] strings = new String[0];
this.runMethodWithTimeout(main, null, ((Object)strings));
out.flush();
out.close();
diffFiles(trDiff, name, exOut, acOut, ignoreWhitespace);
} catch (IOException e) {
trDiff.setScore(0);
trDiff.addOutput("ERROR: " + name +
" could not be found to run Diff Test");
} catch (InterruptedException e) {
trDiff.setScore(0);
trDiff.addOutput("ERROR: " + name +
" got interrupted");
} catch (ClassNotFoundException e) {
trDiff.setScore(0);
trDiff.addOutput("ERROR: " + name +
" could not be found to run Diff Test");
} catch (NoSuchMethodException e) {
trDiff.setScore(0);
trDiff.addOutput("ERROR: Students " +
name + " Main method not found");
} catch (IllegalAccessException e) {
trDiff.setScore(0);
trDiff.addOutput("ERROR: Students code not accessible");
} catch (InvocationTargetException e) {
Throwable et = e.getCause();
Exception es;
if(et instanceof Exception) {
es = (Exception) et;
} else {
es = e;
}
if (es instanceof ExitTrappedException) {
trDiff.setScore(0);
trDiff.addOutput("ERROR: Do not use System.exit() in your code"
+ " its bad practice and can cause the autograder" +
" to crash.");
} else {
String sStackTrace = stackTraceToString(es);
trDiff.setScore(0);
trDiff.addOutput("ERROR: Students code threw " +
es + "\n Stack Trace: " +
sStackTrace);
}
} catch (TimeoutException e) {
trDiff.setScore(0);
trDiff.addOutput("ERROR: Main Method Timed out after "+ waitTime + " Seconds");
} catch (ExecutionException e) {
Throwable et = e.getCause();
Exception es;
if(et instanceof Exception) {
es = (Exception) et;
} else {
es = e;
}
if (es instanceof InvocationTargetException) {
et = es.getCause();
if(et instanceof Exception) {
es = (Exception) et;
} else {
es = e;
}
}
if (es instanceof ExitTrappedException) {
diffFiles(trDiff, name, exOut, acOut, ignoreWhitespace);
} else {
String sStackTrace = stackTraceToString(es);
trDiff.setScore(0);
trDiff.addOutput("ERROR: Students code threw " +
es + "\n Stack Trace: " +
sStackTrace);
}
}
this.allTestResults.add(trDiff, this.checksum);
System.setOut(originalOut);
}
/**
Runs all the diff tests for a specific java program comparing resulting file output.
This runs count diff tests each one using the naming
convetion on the next line for the name of the input file.
All input files are named: {Program_Name}_Diff_#.in
For this method to work correctly, the sample implementation
and the student submission should always write to the same file.
If you need different filenames for each run, you should use
{@link #logFileDiffTest(String, String, String, String, boolean) logFileDiffTest}
with a loop to modify the filename before calling each run.
@param name the name of the program to do diff tests on
@param count the number of diffs to perform
@param logFile the filename of the file the students code writes to and should be compared
@param sampleLogFile the filename that the sample code writes to and should be used for comparison
@param ignoreWhitespace true if want to ignore whitespace false otherwise
*/
public void logFileDiffTests(String name, int count, String logFile,
String sampleLogFile, boolean ignoreWhitespace) {
this.logFileDiffTests(name, count, 0, logFile, sampleLogFile, ignoreWhitespace);
}
/**
Runs all the diff tests for a specific java program comparing resulting file output.
This runs count diff tests each one using the naming
convetion on the next line for the name of the input file.
All input files are named: {Program_Name}_Diff_#.in
For this method to work correctly, the sample implementation
and the student submission should always write to the same file.
If you need different filenames for each run, you should use
{@link #logFileDiffTest(String, String, String, String, boolean) logFileDiffTest}
with a loop to modify the filename before calling each run.
@param name the name of the program to do diff tests on
@param count the number of diffs to perform
@param numVisible The number of tests that should be shown to students (count - numVisible) = numHidden
@param logFile the filename of the file the students code writes to and should be compared
@param sampleLogFile the filename that the sample code writes to and should be used for comparison
@param ignoreWhitespace true if want to ignore whitespace false otherwise
*/
public void logFileDiffTests(String name, int count, int numVisible, String logFile,
String sampleLogFile, boolean ignoreWhitespace) {
PrintStream originalOut = System.out;
InputStream originalIn = System.in;
this.compile(name+"Sample.java");
String visible = this.visibility;
this.setVisibility(0);
for (int i = 0; i < count; i++) {
Math.resetRandom();
if (i >= numVisible) {
this.visibility = visible;
}
TestResult trDiff = new TestResult(name + " Log File Diff Test #" + i,
"" + this.diffNum,
this.maxScore, this.visibility);
this.diffNum++;
String input = name + "_Diff_" + i + ".in";
String exOut = name + i + ".expected";
String acOut = name + "_" + i + ".out";
try {
File exfile = new File(exOut);
File infile = new File(input);
File acfile = new File(acOut);
File sample = new File(name + "Sample.java");
if (sample.exists() && !sample.isDirectory()) {
String[] procSample = {"java", name + "Sample"};
ProcessBuilder pbSample = new ProcessBuilder(procSample);
pbSample.redirectOutput(Redirect.to(exfile));
pbSample.redirectInput(Redirect.from(infile));
Process sampleProcess = pbSample.start();
sampleProcess.waitFor();
}
PrintStream out = new PrintStream(new FileOutputStream(acOut));
System.setOut(out);
System.setIn(new FileInputStream(input));
Class<?> act = Class.forName(name);
if (act == null) {
throw new ClassNotFoundException();
}
Method main = act.getMethod("main", String[].class);
if (main == null) {
throw new NoSuchMethodException();
}
String[] strings = new String[0];
this.runMethodWithTimeout(main, null, ((Object)strings));
out.flush();
out.close();
diffFiles(trDiff, name, sampleLogFile, logFile, ignoreWhitespace);
} catch (IOException e) {
trDiff.setScore(0);
trDiff.addOutput("ERROR: " + name +
" could not be found to run Diff Test");
} catch (InterruptedException e) {
trDiff.setScore(0);
trDiff.addOutput("ERROR: " + name +
" got interrupted");
} catch (ClassNotFoundException e) {
trDiff.setScore(0);
trDiff.addOutput("ERROR: " + name +
" could not be found to run Diff Test");
} catch (NoSuchMethodException e) {
trDiff.setScore(0);
trDiff.addOutput("ERROR: Students " +
name + " Main method not found");
} catch (IllegalAccessException e) {
trDiff.setScore(0);
trDiff.addOutput("ERROR: Students code not accessible");
} catch (InvocationTargetException e) {
Throwable et = e.getCause();
Exception es;
if(et instanceof Exception) {
es = (Exception) et;
} else {
es = e;
}
if (es instanceof ExitTrappedException) {
trDiff.setScore(0);
trDiff.addOutput("ERROR: Do not use System.exit() in your code"
+ " its bad practice and can cause the autograder" +
" to crash.");
} else {
String sStackTrace = stackTraceToString(es);
trDiff.setScore(0);
trDiff.addOutput("ERROR: Students code threw " +
es + "\n Stack Trace: " +
sStackTrace);
}
} catch (TimeoutException e) {
trDiff.setScore(0);
trDiff.addOutput("ERROR: Main Method Timed out after "+ waitTime + " Seconds");
} catch (ExecutionException e) {
Throwable et = e.getCause();
Exception es;
if(et instanceof Exception) {
es = (Exception) et;
} else {
es = e;
}
if (es instanceof InvocationTargetException) {
et = es.getCause();
if(et instanceof Exception) {
es = (Exception) et;
} else {
es = e;
}
}
if (es instanceof ExitTrappedException) {
diffFiles(trDiff, name, sampleLogFile, logFile, ignoreWhitespace);
} else {
String sStackTrace = stackTraceToString(es);
trDiff.setScore(0);
trDiff.addOutput("ERROR: Students code threw " +
es + "\n Stack Trace: " +
sStackTrace);
}
}
this.allTestResults.add(trDiff, this.checksum);
System.setOut(originalOut);
}
this.visibility = visible;
}
/**
Runs a diff test for a specific java program comparing resulting file output.
This test runs a student and sample implementation then compares the results left
in specified output files. The parameter inFile should be the name of a file contianing
all the std input that needs to be passed to the program. This file name should be passed
without an extension. The program autoappends .in to the filename so all input files should be
named {inFile}.in.
@param name the name of the program to do diff tests on
@param logFile the filename of the file the students code writes to and should be compared
@param sampleLogFile the filename that the sample code writes to and should be used for comparison
@param inFile the name of the test input file to use without an extension
@param ignoreWhitespace true if want to ignore whitespace false otherwise
*/
public void logFileDiffTest(String name, String logFile, String sampleLogFile,
String inFile, boolean ignoreWhitespace) {
PrintStream originalOut = System.out;
InputStream originalIn = System.in;
this.compile(name+"Sample.java");
Math.resetRandom();
TestResult trDiff = new TestResult(name + " Log File Diff Test For " + inFile,
"" + this.diffNum,
this.maxScore, this.visibility);
this.diffNum++;
String input = inFile + ".in";
String exOut = inFile + ".expected";
String acOut = inFile + ".out";
try {
File exfile = new File(exOut);
File infile = new File(input);
File acfile = new File(acOut);
File sample = new File(name + "Sample.java");
if (sample.exists() && !sample.isDirectory()) {
String[] procSample = {"java", name + "Sample"};
ProcessBuilder pbSample = new ProcessBuilder(procSample);
pbSample.redirectOutput(Redirect.to(exfile));
pbSample.redirectInput(Redirect.from(infile));
Process sampleProcess = pbSample.start();
sampleProcess.waitFor();
}
PrintStream out = new PrintStream(new FileOutputStream(acOut));
System.setOut(out);
System.setIn(new FileInputStream(input));
Class<?> act = Class.forName(name);
if (act == null) {
throw new ClassNotFoundException();
}
Method main = act.getMethod("main", String[].class);
if (main == null) {
throw new NoSuchMethodException();
}
String[] strings = new String[0];
this.runMethodWithTimeout(main, null, ((Object)strings));
out.flush();
out.close();
diffFiles(trDiff, name, sampleLogFile, logFile, ignoreWhitespace);
} catch (IOException e) {
trDiff.setScore(0);
trDiff.addOutput("ERROR: " + name +
" could not be found to run Diff Test");
} catch (InterruptedException e) {
trDiff.setScore(0);
trDiff.addOutput("ERROR: " + name +
" got interrupted");
} catch (ClassNotFoundException e) {
trDiff.setScore(0);
trDiff.addOutput("ERROR: " + name +
" could not be found to run Diff Test");
} catch (NoSuchMethodException e) {
trDiff.setScore(0);
trDiff.addOutput("ERROR: Students " +
name + " Main method not found");
} catch (IllegalAccessException e) {
trDiff.setScore(0);
trDiff.addOutput("ERROR: Students code not accessible");
} catch (InvocationTargetException e) {
Throwable et = e.getCause();
Exception es;
if(et instanceof Exception) {
es = (Exception) et;
} else {
es = e;
}
if (es instanceof ExitTrappedException) {
trDiff.setScore(0);
trDiff.addOutput("ERROR: Do not use System.exit() in your code"
+ " its bad practice and can cause the autograder" +
" to crash.");
} else {
String sStackTrace = stackTraceToString(es);
trDiff.setScore(0);
trDiff.addOutput("ERROR: Students code threw " +
es + "\n Stack Trace: " +
sStackTrace);
}
} catch (TimeoutException e) {
trDiff.setScore(0);
trDiff.addOutput("ERROR: Main Method Timed out after "+ waitTime + " Seconds");
} catch (ExecutionException e) {
Throwable et = e.getCause();
Exception es;
if(et instanceof Exception) {
es = (Exception) et;
} else {
es = e;
}
if (es instanceof InvocationTargetException) {
et = es.getCause();
if(et instanceof Exception) {
es = (Exception) et;
} else {
es = e;
}
}
if (es instanceof ExitTrappedException) {
diffFiles(trDiff, name, sampleLogFile, logFile, ignoreWhitespace);
} else {
String sStackTrace = stackTraceToString(es);
trDiff.setScore(0);
trDiff.addOutput("ERROR: Students code threw " +
es + "\n Stack Trace: " +
sStackTrace);
}
}
this.allTestResults.add(trDiff, this.checksum);
System.setOut(originalOut);
}
private void diffFiles(TestResult test, String name, String exOut, String acOut, boolean ignoreWhitespace) {
try {
String[] procDiff;
//"-t" };
if (ignoreWhitespace) {
procDiff = new String[]{"diff", exOut, acOut, "-y", "-w",
"--width=175", "-t" };
} else {
procDiff = new String[]{"diff", exOut, acOut, "-y",
"--width=175", "-t" };
}
ProcessBuilder pbDiff = new ProcessBuilder(procDiff);
Process diffProcess = pbDiff.start();
StringBuilder sb = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(diffProcess.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line.replace(" \\ ", " \\\\ "));
sb.append("\n");
}
String result = sb.toString();
diffProcess.waitFor();
if (diffProcess.exitValue() == 0) {
test.setScore(this.maxScore);
test.addOutput("SUCCESS: " + name +
" passed this diff test");