Created
May 12, 2016 10:52
-
-
Save johanneswseitz/f55e74cd6b610d387771e76fbd6e8b2b to your computer and use it in GitHub Desktop.
Junit Rule for running Vagrant VMs in JUnit Tests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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