Do output encapsulation in a try/with

Move the shell output encapsulation so that we don't double-wrap on a
premature exit.

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=219136896
This commit is contained in:
mmuller 2018-10-29 09:05:03 -07:00 committed by jianglai
parent c375b0d5f4
commit a76300f76c
2 changed files with 115 additions and 68 deletions

View file

@ -53,6 +53,9 @@ public class ShellCommandTest {
PrintStream orgStdout;
PrintStream orgStderr;
ByteArrayOutputStream stdout;
ByteArrayOutputStream stderr;
public ShellCommandTest() {}
@Before
@ -269,14 +272,7 @@ public class ShellCommandTest {
@Test
public void testEncapsulatedOutput_command() throws Exception {
RegistryToolEnvironment.ALPHA.setup();
// capture output (have to do this before the shell command is created)
ByteArrayOutputStream stdout = new ByteArrayOutputStream();
ByteArrayOutputStream stderr = new ByteArrayOutputStream();
System.setOut(new PrintStream(stdout));
System.setErr(new PrintStream(stderr));
System.setIn(new ByteArrayInputStream("command1\n".getBytes(UTF_8)));
captureOutput();
ShellCommand shellCommand =
new ShellCommand(
args -> {
@ -296,6 +292,33 @@ public class ShellCommandTest {
+ "SUCCESS\n");
}
@Test
public void testEncapsulatedOutput_noCommand() throws Exception {
captureOutput();
ShellCommand shellCommand =
createShellCommand(
args -> {
System.out.println("first line");
},
Duration.ZERO,
"",
"do something");
shellCommand.encapsulateOutput = true;
shellCommand.run();
assertThat(stderr.toString()).isEmpty();
assertThat(stdout.toString())
.isEqualTo("out: first line\nSUCCESS\n");
}
void captureOutput() {
// capture output (have to do this before the shell command is created)
stdout = new ByteArrayOutputStream();
stderr = new ByteArrayOutputStream();
System.setOut(new PrintStream(stdout));
System.setErr(new PrintStream(stderr));
System.setIn(new ByteArrayInputStream("command1\n".getBytes(UTF_8)));
}
@Parameters(commandDescription = "Test command")
static class TestCommand implements Command {
enum OrgType {