Ok, here's a slightly modified template to make it more generic. I've left in two template parameters for the name of the package and the student answer class, eg, {"package": "foobar", "class": "Foo"}. Basically I bailed on extracting this information from the student answer by trying to anticipate how students might construct their Java code file. Maybe later.
There's a limitation in that the student answer and supporting files must all be in the same package
import sys, os, shutil, subprocess
__student_answer__ = """{{ STUDENT_ANSWER | e('py') }}"""
# Make package directory, put support files into it
os.mkdir("{{ QUESTION.parameters.package }}")
[shutil.move(f, "{{ QUESTION.parameters.package }}") for f in os.listdir() if f.endswith(".java")]
# Put student answer class into package directory
with open("{{ QUESTION.parameters.package }}/{{ QUESTION.parameters.class}}.java", "w") as f:
print(__student_answer__, file=f)
# Build test class in package directory too
tester = """package {{ QUESTION.parameters.package }};
public class __Tester__ {
public static void main(String[] args) {
{{TEST.testcode}}
}
}
"""
with open("{{ QUESTION.parameters.package }}/__Tester__.java", "w") as f:
print(tester, file=f)
# Compile and run
if (subprocess.call(["javac", "{{ QUESTION.parameters.package }}/__Tester__.java"]) != 0 or
subprocess.call(["java", "{{ QUESTION.parameters.package }}/__Tester__"]) != 0):
print("** Further testing aborted **", file=sys.stderr)