package HelloAuto;
import java.io.File;
import junit.framework.TestCase;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.core.Launch;
import org.eclipse.debug.core.model.IProcess;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.launching.IVMInstall;
import org.eclipse.jdt.launching.IVMRunner;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jdt.launching.VMRunnerConfiguration;
import org.eclipse.ui.IEditorPart;
public class CreateAndRunTest extends TestCase {
protected void setUp() throws Exception {
}
public void testHi() throws Exception {
TestProject testProject = new TestProject();
IPackageFragment pack = testProject.createPackage("hi");
String contents = "package hi;" + System.getProperty("line.separator")
+ "public class Hi {" + System.getProperty("line.separator")
+ " public static void main(String[] args) {" + System.getProperty("line.separator")
+ " System.out.println(\"Hi!\");" + System.getProperty("line.separator")
+ " }" + System.getProperty("line.separator")
+ "}";
ICompilationUnit cu= pack.createCompilationUnit("Hi.java", contents, false, null);
IEditorPart part= EditorUtility.openInEditor(cu);
testProject.getProject().build(
IncrementalProjectBuilder.INCREMENTAL_BUILD, null);
IVMInstall vmInstall = JavaRuntime.getVMInstall(testProject
.getJavaProject());
if (vmInstall == null)
vmInstall = JavaRuntime.getDefaultVMInstall();
if (vmInstall != null) {
IVMRunner vmRunner = vmInstall.getVMRunner(ILaunchManager.RUN_MODE);
if (vmRunner != null) {
String[] classPath = null;
try {
classPath = JavaRuntime
.computeDefaultRuntimeClassPath(testProject
.getJavaProject());
} catch (Throwable e) {
}
if (classPath != null) {
VMRunnerConfiguration vmConfig = new VMRunnerConfiguration(
"hi.Hi", classPath);
File wdir = File.createTempFile("xxx", "yyy");
wdir.delete();
wdir.mkdir();
wdir.deleteOnExit();
vmConfig.setWorkingDirectory(wdir.getAbsolutePath());
ILaunch launch = new Launch(null, ILaunchManager.RUN_MODE,
null);
vmRunner.run(vmConfig, launch, null);
IProcess[] processes = launch.getProcesses();
assertEquals(1, processes.length);
int timeout = 60000;
final int tStep = 500;
while (timeout > 0) {
try {
assertEquals("Non-0 status code", 0, processes[0]
.getExitValue());
break;
} catch (DebugException e) {
timeout -= tStep;
try {
Thread.sleep(tStep);
} catch (InterruptedException ee) {
}
}
}
assertTrue("timed out", timeout > 0);
String out = processes[0].getStreamsProxy()
.getOutputStreamMonitor().getContents();
assertTrue(out.indexOf("Hi!") != -1);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
}
}
testProject.delete();
}
}