Skip to content

Commit

Permalink
piped IO for processes in tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Osiris-Team committed Nov 5, 2022
1 parent ef44da3 commit 904ad12
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion src/test/java/io/github/fvarrui/javapackager/RealTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
import org.apache.maven.shared.invoker.*;
import org.junit.jupiter.api.Test;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Map;

Expand Down Expand Up @@ -90,7 +92,8 @@ public MyProcess(String... arguments) {

public MyProcess(ProcessBuilder builder) {
this.builder = builder;
builder.inheritIO();
builder.redirectError(ProcessBuilder.Redirect.PIPE);
builder.redirectInput(ProcessBuilder.Redirect.PIPE);
Map<String, String> environment = builder.environment();
setValueIgnoreCase(environment, "JAVA_HOME", System.getProperty("java.home"));
}
Expand All @@ -109,6 +112,31 @@ public void execNow() throws IOException, InterruptedException {
StackTraceElement stackEl = stackTrace[1];
System.out.println(stackEl.toString()+" -> "+commandToString());
Process p = builder.start();
// Inheriting IO doesn't work as good as doing the below:
new Thread(() -> {
try{
try(BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()))){
String line = null;
while ((line = reader.readLine()) != null){
System.out.println(line);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}).start();
new Thread(() -> {
try{
try(BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream()))){
String line = null;
while ((line = reader.readLine()) != null){
System.err.println(line);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}).start();
int result = p.waitFor();
if (result != 0)
throw new IOException("Process exited with " + result + " instead of 0! Something probably went wrong.");
Expand Down

0 comments on commit 904ad12

Please sign in to comment.