Skip to content

Instantly share code, notes, and snippets.

@johanneswseitz
Created May 12, 2016 10:52
Show Gist options
  • Save johanneswseitz/f55e74cd6b610d387771e76fbd6e8b2b to your computer and use it in GitHub Desktop.
Save johanneswseitz/f55e74cd6b610d387771e76fbd6e8b2b to your computer and use it in GitHub Desktop.
Junit Rule for running Vagrant VMs in JUnit Tests
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.TimeUnit;
import org.junit.rules.ExternalResource;
import de.db.flexfit.conditional.Condition;
import de.db.flexfit.conditional.Waiter;
public class VagrantRule extends ExternalResource {
private final File workingDirectory;
private Process vagrantUpProcess;
private Process vagrantDestroyProcess;
public VagrantRule(String workingDirectory) {
Path path = Paths.get(workingDirectory);
this.workingDirectory = path.toAbsolutePath().normalize().toFile();
}
@Override
protected void before() throws Throwable {
try {
ProcessBuilder processBuilder = new ProcessBuilder("CMD", "/C", "vagrant up");
vagrantUpProcess = processBuilder.directory(workingDirectory).inheritIO().start();
boolean success = vagrantUpProcess.waitFor(10, TimeUnit.MINUTES);
if (!success) {
throw new RuntimeException("Vagrant did not launch");
}
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
@Override
protected void after() {
try {
ProcessBuilder processBuilder = new ProcessBuilder("CMD", "/C", "vagrant destroy -f");
vagrantDestroyProcess = processBuilder.directory(workingDirectory).inheritIO().start();
vagrantDestroyProcess.waitFor(10, TimeUnit.MINUTES);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
vagrantUpProcess.destroyForcibly();
vagrantDestroyProcess.destroyForcibly();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment