Initial version.

This commit is contained in:
2020-07-09 16:58:28 +02:00
commit e5a0270937
14 changed files with 1483 additions and 0 deletions
+11
View File
@@ -0,0 +1,11 @@
# Ignore Gradle project-specific cache directory
.gradle
# Eclipse
.classpath
.settings
.project
bin/
# Ignore Gradle build output directory
build
+36
View File
@@ -0,0 +1,36 @@
# Testator
This project contains a piece of code to run Jack tests locally using the more advanced ECJ compiler that can also
generate classes, if there are compile errors. To build and execute the project you can simply execute gradle run
with the associated arguments as follows:
´´´
./gradlew run --args="-i <jack_zip> -t <test_zip> -c <class1,class2,...>"
´´´
To successfully execute the Testator, you need to pass the following arguments:
´´´
-c,--classes <arg> Comma-separated list of classes with tests.
-i,--input <arg> Path name of zip with student code (exported with
the first option, by id and time).
-t,--test <arg> Path name of zip with testing code (without
framework, annotations and abstract base classes).
´´´
The final output will be a comma-separated list of student ids (first column), maximum task results and total points
(last column).
## Workflow
The Testator will identify student ids and uploads from the jack_zip. For each upload from each student the tool will
generate a folder that will contain the files in the test_zip and the associated uploaded student code (student files
will overwrite existing test files). The output will be generated in a "temp" directory that is in the same directory
as the jack_zip. Once unpacked, the Testator uses the Eclipse Compiler for Java to compile the code and run the
individual test files. It is assumed that the individual methods in each test class finish within 15 seconds. If this
is not the case, they will be forcefully aborted (by stopping the Thread) since we assume that the student has produced
an infinite loop. This should be more or less safe (although it is obviously ugly).
## Important
This project requires Java 1.8 since the ecj BatchCompiler must be able to find the rt.jar to work correctly.
+23
View File
@@ -0,0 +1,23 @@
plugins {
id 'java'
id 'application'
}
repositories {
jcenter()
}
java {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
dependencies {
implementation 'commons-cli:commons-cli:1.4'
implementation 'org.eclipse.jdt.core.compiler:ecj:4.6.1'
testImplementation 'junit:junit:4.12'
}
application {
mainClassName = 'de.uni_due.nes.testator.Main'
}
Binary file not shown.
+5
View File
@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.5.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+188
View File
@@ -0,0 +1,188 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"
Vendored
+100
View File
@@ -0,0 +1,100 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+10
View File
@@ -0,0 +1,10 @@
/*
* This file was generated by the Gradle 'init' task.
*
* The settings file is used to specify which projects to include in your build.
*
* Detailed information about configuring a multi-project build in Gradle can be found
* in the user manual at https://docs.gradle.org/5.5.1/userguide/multi_project_builds.html
*/
rootProject.name = 'testator'
@@ -0,0 +1,264 @@
package de.uni_due.nes.jack;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import de.uni_due.s3.jack2.backend.checkers.tracingchecker.framework.TracingFramework.Test;
/**
* An abstract base class for test cases. How to use it:
*
* <ol>
* <li> Create a subclass with arbitrary name (e.g. TestCase).</li>
* <li> Create a method and annotate it with {@link de.uni_due.s3.jack2.backend.checkers.tracingchecker.framework.TracingFramework.Test}. </li>
* <li> Within the method call <code>addPoints(x)</code> to assign points.
* <li> Create a main method that executes: <code>runAll(new TestCase())</code></li>
* </ol>
*
* <ul>
* <li><b>Note:</b> this class assumes that each test case calls addPoints <b>exactly once</b>. It will
* report all methods when executing them locally that do not conform to this constraint.</li>
* <li><b>Deployment:</b> to use the class on the jack server, you can either:
* <ol>
* <li> add its source code to the <i>source files</i></li>
* <li> add a jar containing the compiled class to the <i>library files</i></li>
* </ol>
* </li>
* </ul>
*
* @author Marcus
*/
public abstract class AbstractTest {
/**
* An output stream to capture system out.
*
* @author Marcus
*/
private class CaptureStream extends OutputStream {
/**
* The bytes written since the start of the capuring process.
*/
List<Byte> bytes = new ArrayList<>();
/**
* Creates a new stream.
*/
public CaptureStream() {
super();
}
@Override
public void write(int b) throws IOException {
bytes.add((byte)(b & 0xff));
}
/**
* Returns an utf-8 string of the captured output.
*
* @return The output interpreted as utf-8 encoding.
*/
@Override
public String toString() {
return toString("UTF-8");
}
/**
* Returns the output interpreted with the specified encoding.
*
* @param encoding The encoding.
* @return The output interpreted with the encoding.
*/
public String toString(String encoding) {
byte[] data = new byte[bytes.size()];
for (int i = 0; i < data.length; i++) {
data[i] = bytes.get(i);
}
try {
return new String(data, encoding);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Unsupported encoding: UTF-8");
}
}
}
/**
* The system out while capturing.
*/
private PrintStream systemOut;
/**
* The capture out while capturing.
*/
private CaptureStream captureOut;
/**
* The points of each test case.
*/
private List<Integer> points = new ArrayList<>();
/**
* This method will be called by jack after all
* test have been executed to get the resulting
* points.
*
* @return The points resulting from the test.
*/
public int getResult() {
int sum = 0;
for (Integer p: points) {
sum += p;
}
return sum;
}
/**
* Adds points for a test case. This class assumes
* that the method is called <b>exactly</b> once
* per test case.
*
* @param value The points to add.
*/
protected void addPoints(int value) {
points.add(value);
}
/**
* This method is called by the jack framework after the
* class has been instantiated. Subclasses may override
* this to perform expensive initializations.
*/
public void init() {
// does nothing
}
/**
* A utility method to execute any test driver class extending
* abstract test locally without going through Jack.
*
* @param test The test driver to execute.
* @throws Exception Thrown if something fails.
*/
public static void runAll(AbstractTest test) throws Exception {
runAll(test, 60000);
}
/**
* A utility method to execute any test driver class extending
* abstract test locally without going through Jack.
*
* @param test The test driver to execute.
* @param timeout The timeout to wait for the thread.
* @throws Exception Thrown if something fails.
*/
@SuppressWarnings("deprecation")
public static void runAll(AbstractTest test, long timeout) throws Exception {
System.out.println(test.getClass().getName());
System.out.println();
for (Method method : test.getClass().getMethods()) {
if (method.isAnnotationPresent(Test.class)) {
int size = test.points.size();
long now = System.currentTimeMillis();
long deadline = now + timeout;
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("Begin: " + method.getAnnotation(Test.class).name());
method.invoke(test);
if (test.points.size() != size + 1) {
System.err.println("Der Test " + method.getAnnotation(Test.class).name() + " lieferte kein oder mehrere Ergebnisse.");
} else {
System.out.println("Punkte: " + test.points.get(test.points.size() - 1) + " (" + method.getAnnotation(Test.class).name() + ")");
}
} catch (Exception e) {
System.err.println("Der Test " + method.getAnnotation(Test.class).name() + " lieferte ein Exception.");
e.printStackTrace();
}
System.out.println("Finish: " + method.getAnnotation(Test.class).name());
}
});
t.start();
while (deadline - now > 0 && t.isAlive()) {
try {
t.join(deadline - now);
} catch (InterruptedException e) {
break;
}
now = System.currentTimeMillis();
}
if (t.isAlive()) {
System.out.println("Stopping thread due to timeout.");
t.stop(); // this is the only way to stop infinite student loops
}
}
}
System.out.println();
System.out.println("Summe: " + test.getResult());
}
/**
* Determines whether we are capturing system out.
*
* @return True if system out is captured, false otherwise.
*/
public boolean isCapturing() {
return systemOut != null || captureOut != null;
}
/**
* Begins capturing system out. The captured code should
* run in a try-finally block that disables capturing to
* ensure that capturing is disabled properly even if tests
* fail.
*/
public void beginCapture() {
if (isCapturing()) throw new RuntimeException("Cannot start capturing while capture has started.");
try {
systemOut = System.out;
captureOut = new CaptureStream();
System.setOut(new PrintStream(captureOut));
} catch (Exception e) {
systemOut = null;
captureOut = null;
throw new RuntimeException(e);
}
}
/**
* Returns the string written to system out since the capturing started.
*
* @return The string written on system out.
*/
public String getCapture() {
if (captureOut == null) throw new RuntimeException("Cannot get capture while capture has started.");
else return captureOut.toString();
}
/**
* Ends the capuring that has been started.
*/
public void endCapture() {
if (! isCapturing()) throw new RuntimeException("Cannot end capturing while capture has not started.");
try {
System.setOut(systemOut);
captureOut = null;
systemOut = null;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@@ -0,0 +1,237 @@
package de.uni_due.nes.jack;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotations to generate xml files with
* static checks.
*
* @author Marcus
*/
public class Annotations {
/**
* An enum to associate check annotations
* with output files.
*
* @author Marcus
*
*/
@SuppressWarnings("javadoc")
public enum CheckGroup {
DEFAULT, G1, G2, G3, G4, G5, G6, G7, G8, G9
};
/**
* Checks whether a particular type is in the default package.
*
* @author Marcus
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface CheckIsDefaultPackage {
/**
* The points for the rule.
*
* @return The points for the rule.
*/
int points() default 0;
/**
* The check group used to combine multiple
* rules.
*
* @return The group.
*/
CheckGroup group() default CheckGroup.DEFAULT;
}
/**
* Checks common style rules.
*
* @author Marcus
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface CheckJavaStyle {
/**
* The check group used to combine multiple
* rules.
*
* @return The group.
*/
CheckGroup group() default CheckGroup.DEFAULT;
}
/**
* Checks that there is no for in a method.
*
* @author Marcus
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CheckNoFor {
/**
* The points for the rule.
*
* @return The points for the rule.
*/
int points() default 0;
/**
* The check group used to combine multiple
* rules.
*
* @return The group.
*/
CheckGroup group() default CheckGroup.DEFAULT;
}
/**
* Checks that there is no if in a method.
*
* @author Marcus
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CheckNoIf {
/**
* The points for the rule.
*
* @return The points for the rule.
*/
int points() default 0;
/**
* The check group used to combine multiple
* rules.
*
* @return The group.
*/
CheckGroup group() default CheckGroup.DEFAULT;
}
/**
* Checks that there is switch for in a method.
*
* @author Marcus
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CheckNoSwitch {
/**
* The points for the rule.
*
* @return The points for the rule.
*/
int points() default 0;
/**
* The check group used to combine multiple
* rules.
*
* @return The group.
*/
CheckGroup group() default CheckGroup.DEFAULT;
}
/**
* Checks that there is no system exit in a type.
*
* @author Marcus
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface CheckNoSystemExit {
/**
* The points for the rule.
*
* @return The points for the rule.
*/
int points() default 0;
/**
* The check group used to combine multiple
* rules.
*
* @return The group.
*/
CheckGroup group() default CheckGroup.DEFAULT;
}
/**
* Checks that there is no while in a method.
*
* @author Marcus
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CheckNoWhile {
/**
* The points for the rule.
*
* @return The points for the rule.
*/
int points() default 0;
/**
* The check group used to combine multiple
* rules.
*
* @return The group.
*/
CheckGroup group() default CheckGroup.DEFAULT;
}
/**
* Checks that a specific method exists.
*
* @author Marcus
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CheckSignatureExists {
/**
* The points for the rule.
*
* @return The points for the rule.
*/
int points() default 0;
/**
* The check group used to combine multiple
* rules.
*
* @return The group.
*/
CheckGroup group() default CheckGroup.DEFAULT;
}
/**
* Checks that a method performs direct or indirect recursion.
* Note that matching is based solely on the name (!). So the
* name must be unique.
*
* @author Marcus
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CheckRequireRecursion {
/**
* The points for the rule.
*
* @return The points for the rule.
*/
int points() default 0;
/**
* The check group used to combine multiple
* rules.
*
* @return The group.
*/
CheckGroup group() default CheckGroup.DEFAULT;
}
}
@@ -0,0 +1,109 @@
package de.uni_due.nes.testator;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
/**
* The main class to test a testat.
*
* @author Marcus
*
*/
public class Main {
/**
* Runs the program with three options:
* -i The path name of the zip with the student code downloaded from jack.
* -t The code for the test cases plus any un-modifiable classes supplied the the students.
* -c A comma-separated list of classes containing tests.
*
* @param args
*/
public static void main(String[] args) {
Options options = new Options();
Option inputZip = new Option("i", "input", true, "Path name of zip with student code (exported with the first option, by id and time).");
inputZip.setRequired(true);
options.addOption(inputZip);
Option testZip = new Option("t", "test", true, "Path name of zip with testing code (without framework, annotations and abstract base classes).");
testZip.setRequired(true);
options.addOption(testZip);
Option testClasses = new Option("c", "classes", true, "Comma-separated list of classes with tests.");
testClasses.setRequired(true);
options.addOption(testClasses);
try {
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args);
File input = new File(cmd.getOptionValue(inputZip.getOpt()));
if (!input.exists()) throw new IllegalArgumentException(String.format("Input file %s does not exist.", input.getAbsolutePath()));
File test = new File(cmd.getOptionValue(testZip.getOpt()));
if (!input.exists()) throw new IllegalArgumentException(String.format("Test file %s does not exist.", test.getAbsolutePath()));
List<String> classes = new ArrayList<>();
for (String c: cmd.getOptionValue(testClasses.getOpt()).split(",")) {
c = c.trim();
if (c.length() > 0)
classes.add(c);
}
if (classes.isEmpty()) throw new IllegalArgumentException("No valid class specification found.");
SortedMap<Long, SortedMap<String, Integer>> results = new TreeMap<>();
// run all test cases
Testator testator = new Testator(input, test, classes);
for (Long id : testator.getStudents()) {
SortedMap<String, Integer> result = new TreeMap<>();
for (String submission: testator.getSubmissions(id)) {
testator.unpack(id, submission);
testator.compile(id, submission);
}
for (String cls: testator.getClasses()) {
int points = 0;
for (String submission: testator.getSubmissions(id)) {
points = Math.max(points,testator.execute(id, submission, cls));
}
result.put(cls, points);
}
results.put(id, result);
}
// print result
for (Long student: results.keySet()) {
System.out.print(student);
int total = 0;
for (String cls: results.get(student).keySet()) {
int task = results.get(student).get(cls);
System.out.print(",");
System.out.print(Integer.toString(task));
total += task;
}
System.out.print(",");
System.out.println(Integer.toString(total));
}
} catch (ParseException e) {
System.out.println(e.getMessage());
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("java " + Main.class.getName(), options);
System.exit(1);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
System.exit(1);
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
@@ -0,0 +1,71 @@
package de.uni_due.nes.testator;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* A class loader to load student code seperately for each test.
*
* @author Marcus
*
*/
public class TestClassLoader extends ClassLoader {
/**
* The folder with the student code.
*/
private File folder;
/**
* Creates a new class loader with the specified parent
* that searches the specified folder.
*
* @param parent The parent loader.
* @param folder The folder to search for class files.
*/
public TestClassLoader(ClassLoader parent, File folder) {
super(parent);
this.folder = folder;
}
@Override
public Class<?> findClass(String name) throws ClassNotFoundException {
try {
byte[] b = loadClassFromFile(name);
return defineClass(name, b, 0, b.length);
} catch (IOException e) {
throw new ClassNotFoundException(String.format("Failed to find class %s.", name), e);
}
}
/**
* Loads a class file from a file.
*
* @param name The name of the class.
* @return The bytes for the class file.
* @throws IOException Thrown if something fails.
*/
private byte[] loadClassFromFile(String name) throws IOException {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
try (InputStream inputStream = new FileInputStream(new File(folder, getClassFile(name)))) {
int nextValue = 0;
while ( (nextValue = inputStream.read()) != -1 ) {
byteStream.write(nextValue);
}
}
return byteStream.toByteArray();
}
/**
* Returns the file name for the class.
*
* @param name The file name for the class.
* @return The file name for the class.
*/
private String getClassFile(String name) {
return name.replace('.', File.separatorChar) + ".class";
}
}
@@ -0,0 +1,339 @@
package de.uni_due.nes.testator;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.eclipse.jdt.core.compiler.batch.BatchCompiler;
import de.uni_due.nes.jack.AbstractTest;
/**
* This class unzips and compiles the student files and runs the test cases.
*
* @author Marcus
*/
public class Testator {
/**
* The logger to generate output.
*/
private Logger log = Logger.getLogger(getClass().getName());
/**
* The buffer to copy files.
*/
private byte[] buffer = new byte[8196];
/**
* The input file.
*/
private File input;
/**
* The test file.
*/
private File test;
/**
* The classes.
*/
private List<String> classes;
/**
* Creates a new testator.
*
* @param input The input zip file with student code.
* @param test The tests.
* @param classes The class names containing tests.
*/
public Testator(File input, File test, List<String> classes) {
this.input = input;
this.test = test;
this.classes = classes;
}
/**
* Returns the test classes.
*
* @return The test classes.
*/
public List<String> getClasses() {
return classes;
}
/**
* Returns the student ids contained in the zip.
*
* @return The student ids.
* @throws IOException Thrown if something fails.
*/
public SortedSet<Long> getStudents() throws IOException {
SortedSet<Long> result = new TreeSet<>();
Set<String> ignored = new HashSet<>();
try (ZipFile zip = new ZipFile(input)) {
Enumeration<? extends ZipEntry> es = zip.entries();
while (es.hasMoreElements()) {
ZipEntry e = es.nextElement();
String name = e.getName();
if (name.contains("/")) {
name = name.substring(0, name.indexOf('/'));
}
try {
result.add(Long.parseLong(name));
} catch (NumberFormatException ex) {
ignored.add(name);
}
}
}
for (String s: ignored) {
log.log(Level.INFO, String.format("Ignoring user %s.", s));
}
return result;
}
/**
* Returns the submissions of the student.
*
* @param student The student.
* @return The submissions.
* @throws IOException Thrown if something fails.
*/
public SortedSet<String> getSubmissions(Long student) throws IOException {
SortedSet<String> result = new TreeSet<>();
try (ZipFile zip = new ZipFile(input)) {
Enumeration<? extends ZipEntry> es = zip.entries();
while (es.hasMoreElements()) {
ZipEntry e = es.nextElement();
String prefix = student + "/";
String name = e.getName();
if (name.startsWith(prefix) && name.indexOf('/', prefix.length()) != -1) {
name = name.substring(prefix.length(), name.indexOf('/', prefix.length()));
result.add(name);
}
}
}
return result;
}
/**
* Unpacks the student submission.
*
* @param student The student.
* @param submission The submission name.
* @throws IOException Thrown if something fails.
*/
public void unpack(Long student, String submission) throws IOException {
File target = getTarget(student, submission);
createDirectory(input.getParentFile(), target);
unpack(test, target, "");
unpack(input, target, String.format("%d/%s/", student, submission));
}
/**
* Compiles the student submission.
*
* @param student The student.
* @param submission The submission.
* @throws IOException Thrown if something fails.
*/
public void compile(Long student, String submission) throws IOException {
File target = getTarget(student, submission);
List<String> options = new ArrayList<>();
options.add("-sourcepath");
options.add(target.getAbsolutePath());
options.add("-d");
options.add(target.getAbsolutePath());
options.add("-cp");
options.add("rt.jar;" + System.getProperty("java.class.path"));
options.add("-1.8");
options.add("-warn:none");
options.add("-proceedOnError");
for (String c: classes) {
options.add(new File(target, getJavaFile(c)).getAbsolutePath());
}
log.log(Level.INFO, String.format("Calling batch compile using: %s", options.toString()));
BatchCompiler.compile(options.toArray(new String[options.size()]), new PrintWriter(System.out), new PrintWriter(System.err), null);
}
/**
* Runs the test case for the student submission.
*
* @param student The student.
* @param submission The submission.
* @param cls The class to test.
* @return The number of points from the test.
* @throws IOException Thrown if the test cases are broken.
*/
public int execute(Long student, String submission, String cls) throws IOException {
try {
TestClassLoader loader = new TestClassLoader(Thread.currentThread().getContextClassLoader(), getTarget(student, submission));
Class<?> clazz = loader.loadClass(cls);
Object instance = clazz.newInstance();
if (instance instanceof AbstractTest) {
AbstractTest test = (AbstractTest)instance;
AbstractTest.runAll(test, 15000);
return test.getResult();
} else {
log.log(Level.SEVERE, String.format("%s does not extend AbstractTest.", cls));
return 0;
}
} catch (ClassNotFoundException e) {
throw new IOException(String.format("Could not load test class %s.", cls), e);
} catch (IllegalAccessException e) {
throw new IOException(String.format("Could not create test class %s.", cls), e);
} catch (InstantiationException e) {
throw new IOException(String.format("Could not instantiate test class %s.", cls), e);
} catch (Exception e) {
throw new IOException(String.format("Failed to execute test class %s.", cls), e);
}
}
/**
* Returns the java file name for the class.
*
* @param cls The class.
* @return The java file name.
*/
private String getJavaFile(String cls) {
return cls.replace(".", "/") + ".java";
}
/**
* Returns the folder where the we will run our tests.
*
* @param student The id of the student.
* @param submission The name of the submission.
* @return The folder with the tests.
*/
public File getTarget(Long student, String submission) {
String shortName = submission.split(" ")[0];
return new File(input.getParentFile(), String.format("temp/%d - %s", student, shortName));
}
/**
* Unpacks the contents of the file into the folder.
*
* @param file The zip file.
* @param prefix The prefix to select and ignore.
* @param folder The folder.
* @throws IOException Thrown by the underlying streams.
*/
private void unpack(File file, File folder, String prefix) throws IOException {
try (ZipFile zip = new ZipFile(file)) {
Enumeration<? extends ZipEntry> entries = zip.entries();
while (entries.hasMoreElements()) {
ZipEntry next = entries.nextElement();
if (next.getName().startsWith(prefix)) {
log.log(Level.INFO, String.format("Processing file %s.", next.getName()));
} else {
log.log(Level.FINER, String.format("Skipping file %s.", next.getName()));
continue;
}
File target = new File(folder, next.getName().substring(prefix.length()));
if (next.isDirectory()) {
createDirectory(folder, target);
} else {
createDirectory(folder, target.getParentFile());
try (InputStream stream = zip.getInputStream(next)) {
int size = copy(stream, target);
log.log(Level.FINE, String.format("Extracted file %s with %d bytes.", target.getAbsolutePath(), size));
}
}
}
}
}
/**
* Creates a child directory inside of a parent directory.
*
* @param parent The parent.
* @param child The child directory.
* @throws IOException Thrown if the child is not inside the parent
* or if the directory cannot be created.
*/
private void createDirectory(File parent, File child) throws IOException {
if (!isParent(parent, child))
throw new IOException(String.format("Cannot create %s, since it is outside of %s.",
child.getAbsolutePath(), parent.getAbsolutePath()));
if (child.exists()) return;
List<File> files = new ArrayList<>();
files.add(child);
while (true) {
File file = files.get(0).getParentFile();
if (file.equals(parent) || file.exists()) break;
files.add(0, file);
}
for (File file: files) {
log.log(Level.FINE, String.format("Creating folder %s.", file.getAbsolutePath()));
if (!file.mkdir()) {
throw new IOException(String.format("Failed to create folder %s.", file.getAbsolutePath()));
}
}
}
/**
* Determines whether the child is actually a child of the parent.
*
* @param parent The parent.
* @param child The child.
* @return True if the parent is a parent of the child.
*/
private boolean isParent(File parent, File child) {
File next = child;
while (next != null) {
if (parent.equals(next)) return true;
next = next.getParentFile();
}
return false;
}
/**
* Copies all contents of the input stream to the destination
* using the specified buffer.
*
* @param buffer The buffer to copy.
* @param stream The stream to copy.
* @param destination The destination.
* @return The number of bytes read.
* @throws IOException Thrown by the underlying streams.
*/
private int copy(InputStream stream, File destination) throws IOException {
int total = 0;
try (OutputStream os = new FileOutputStream(destination)) {
int read;
while ((read = stream.read(buffer)) >= 0) {
if (read > 0) {
total += read;
os.write(buffer, 0, read);
}
}
} finally {
stream.close();
}
return total;
}
}
@@ -0,0 +1,90 @@
package de.uni_due.s3.jack2.backend.checkers.tracingchecker.framework;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
/**
* A stub for the tracing framework that enables test execution without
* going through the jack server.<br><br>
*
* Note: A different implementation of this class will be available
* on the jack server, so it should <b>not be uploaded</b>.
*
* @author Marcus
*/
public class TracingFramework {
/**
* An annotation to mark test cases. Only the methods containing
* this annotation will be executed by jack.
*
* @author Marcus
*/
@Retention(RetentionPolicy.RUNTIME)
public static @interface Test {
/**
* The name of the test case that will be used as part
* of the error reporting.
*
* @return The name of the test case.
*/
String name();
}
/**
* Prints an error.
*
* @param details The error details to print.
*/
public static void printError(String details) {
printDetailedError("", details);
}
/**
* Prints an error consisting of name and details.
*
* @param name The name.
* @param details The details.
*/
public static void printDetailedError(String name, String details) {
System.err.println("ERR: " + name + ": " + details);
}
/**
* Prints a warning consisting of name and details.
*
* @param name The name.
* @param details The details.
*/
public static void printWarning(String name, String details) {
System.err.println("WRN: " + name + ": " + details);
}
/**
* Disables tracing to save resources.
*/
public static void switchOffTracing() {
System.err.println("TRACING OFF");
}
/**
* Enables tracing to log calls.
*/
public static void switchOnTracing() {
System.err.println("TRACING ON");
}
/**
* Prints a throwable.
*
* @param m The method under test?
* @param t The throwable to print.
* @param s Error details.
* @deprecated This should probably not be used.
*/
public static void printThrowable(Method m, Throwable t, String s) {
System.err.println("THR: " + m + " " + s + " " + t);
}
}