Path: blob/master/test/jdk/java/lang/ProcessBuilder/PipelineTest.java
41149 views
/*1* Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223import java.io.File;24import java.io.FileReader;25import java.io.FileWriter;26import java.io.IOException;27import java.io.InputStream;28import java.io.OutputStream;29import java.io.Reader;30import java.io.Writer;31import java.util.Arrays;32import java.util.List;3334/*35* @test PipelineTest36* @bug 821184437* @summary Tests for ProcessBuilder.startPipeline38*/3940public class PipelineTest {4142private static void realMain(String[] args) throws Throwable {43t1_simplePipeline();44t2_translatePipeline();45t3_redirectErrorStream();46t4_failStartPipeline();47}4849/**50* Return a list of the varargs arguments.51* @param args elements to include in the list52* @param <T> the type of the elements53* @return a {@code List<T>} of the arguments54*/55@SafeVarargs56@SuppressWarnings("varargs")57static <T> List<T> asList(T... args) {58return Arrays.asList(args);59}6061/**62* T1 - simple copy between two processes63*/64static void t1_simplePipeline() {65try {66String s1 = "Now is the time to check!";67verify(s1, s1,68asList(new ProcessBuilder("cat")));69verify(s1, s1,70asList(new ProcessBuilder("cat"),71new ProcessBuilder("cat")));72verify(s1, s1,73asList(new ProcessBuilder("cat"),74new ProcessBuilder("cat"),75new ProcessBuilder("cat")));76} catch (Throwable t) {77unexpected(t);78}79}8081/**82* Pipeline that modifies the content.83*/84static void t2_translatePipeline() {85try {86String s2 = "Now is the time to check!";87String r2 = s2.replace('e', 'E').replace('o', 'O');88verify(s2, r2,89asList(new ProcessBuilder("tr", "e", "E"),90new ProcessBuilder("tr", "o", "O")));91} catch (Throwable t) {92unexpected(t);93}94}9596/**97* Test that redirectErrorStream sends standard error of the first process98* to the standard output. The standard error of the first process should be empty.99* The standard output of the 2nd should contain the error message including the bad file name.100*/101static void t3_redirectErrorStream() {102try {103File p1err = new File("p1-test.err");104File p2out = new File("p2-test.out");105106List<Process> processes = ProcessBuilder.startPipeline(107asList(new ProcessBuilder("cat", "NON-EXISTENT-FILE")108.redirectErrorStream(true)109.redirectError(p1err),110new ProcessBuilder("cat").redirectOutput(p2out)));111waitForAll(processes);112113check("".equals(fileContents(p1err)), "The first process standard error should be empty");114String p2contents = fileContents(p2out);115check(p2contents.contains("NON-EXISTENT-FILE"),116"The error from the first process should be in the output of the second: " + p2contents);117} catch (Throwable t) {118unexpected(t);119}120}121122/**123* Test that no processes are left after a failed startPipeline.124* Test illegal combinations of redirects.125*/126static void t4_failStartPipeline() {127File p1err = new File("p1-test.err");128File p2out = new File("p2-test.out");129130THROWS(IllegalArgumentException.class,131() -> {132// Test that output redirect != PIPE throws IAE133List<Process> processes = ProcessBuilder.startPipeline(134asList(new ProcessBuilder("cat", "NON-EXISTENT-FILE1")135.redirectOutput(p1err),136new ProcessBuilder("cat")));137},138() -> {139// Test that input redirect != PIPE throws IAE140List<Process> processes = ProcessBuilder.startPipeline(141asList(new ProcessBuilder("cat", "NON-EXISTENT-FILE2"),142new ProcessBuilder("cat").redirectInput(p2out)));143}144);145146THROWS(NullPointerException.class,147() -> {148List<Process> processes = ProcessBuilder.startPipeline(149asList(new ProcessBuilder("cat", "a"), null));150},151() -> {152List<Process> processes = ProcessBuilder.startPipeline(153asList(null, new ProcessBuilder("cat", "b")));154}155);156157THROWS(IOException.class,158() -> {159List<Process> processes = ProcessBuilder.startPipeline(160asList(new ProcessBuilder("cat", "c"),161new ProcessBuilder("NON-EXISTENT-COMMAND")));162});163164// Check no subprocess are left behind165ProcessHandle.current().children().forEach(PipelineTest::print);166ProcessHandle.current().children()167.filter(p -> p.info().command().orElse("").contains("cat"))168.forEach(p -> fail("process should have been destroyed: " + p));169}170171static void verify(String input, String expected, List<ProcessBuilder> builders) throws IOException {172File infile = new File("test.in");173File outfile = new File("test.out");174setFileContents(infile, input);175for (int i = 0; i < builders.size(); i++) {176ProcessBuilder b = builders.get(i);177if (i == 0) {178b.redirectInput(infile);179}180if (i == builders.size() - 1) {181b.redirectOutput(outfile);182}183}184List<Process> processes = ProcessBuilder.startPipeline(builders);185verifyProcesses(processes);186waitForAll(processes);187String result = fileContents(outfile);188check(result.equals(expected),189"result not as expected: " + result + ", expected: " + expected);190}191192/**193* Wait for each of the processes to be done.194*195* @param processes the list of processes to check196*/197static void waitForAll(List<Process> processes) {198processes.forEach(p -> {199try {200int status = p.waitFor();201} catch (InterruptedException ie) {202unexpected(ie);203}204});205}206207static void print(ProcessBuilder pb) {208if (pb != null) {209System.out.printf(" pb: %s%n", pb);210System.out.printf(" cmd: %s%n", pb.command());211}212}213214static void print(ProcessHandle p) {215System.out.printf("process: pid: %d, info: %s%n",216p.pid(), p.info());217}218219// Check various aspects of the processes220static void verifyProcesses(List<Process> processes) {221for (int i = 0; i < processes.size(); i++) {222Process p = processes.get(i);223224if (i != 0) {225verifyNullStream(p.getOutputStream(), "getOutputStream");226}227if (i <= processes.size() - 1) {228verifyNullStream(p.getInputStream(), "getInputStream");229}230if (i == processes.size() - 1) {231verifyNullStream(p.getErrorStream(), "getErrorStream");232}233}234}235236static void verifyNullStream(OutputStream s, String msg) {237try {238s.write(0xff);239fail("Stream should have been a NullStream: " + msg);240} catch (IOException ie) {241// expected242}243}244245static void verifyNullStream(InputStream s, String msg) {246try {247int len = s.read();248check(len == -1, "Stream should have been a NullStream: " + msg);249} catch (IOException ie) {250// expected251}252}253254static void setFileContents(File file, String contents) {255try {256Writer w = new FileWriter(file);257w.write(contents);258w.close();259} catch (Throwable t) { unexpected(t); }260}261262static String fileContents(File file) {263try {264Reader r = new FileReader(file);265StringBuilder sb = new StringBuilder();266char[] buffer = new char[1024];267int n;268while ((n = r.read(buffer)) != -1)269sb.append(buffer,0,n);270r.close();271return new String(sb);272} catch (Throwable t) { unexpected(t); return ""; }273}274275//--------------------- Infrastructure ---------------------------276static volatile int passed = 0, failed = 0;277static void pass() {passed++;}278static void fail() {failed++; new Exception("Stack trace").printStackTrace(System.out);}279static void fail(String msg) {280System.out.println(msg); failed++;281new Exception("Stack trace: " + msg).printStackTrace(System.out);282}283static void unexpected(Throwable t) {failed++; t.printStackTrace(System.out);}284static void check(boolean cond) {if (cond) pass(); else fail();}285static void check(boolean cond, String m) {if (cond) pass(); else fail(m);}286static void equal(Object x, Object y) {287if (x == null ? y == null : x.equals(y)) pass();288else fail(">'" + x + "'<" + " not equal to " + "'" + y + "'");289}290291public static void main(String[] args) throws Throwable {292try {realMain(args);} catch (Throwable t) {unexpected(t);}293System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);294if (failed > 0) throw new AssertionError("Some tests failed");295}296interface Fun {void f() throws Throwable;}297static void THROWS(Class<? extends Throwable> k, Fun... fs) {298for (Fun f : fs)299try { f.f(); fail("Expected " + k.getName() + " not thrown"); }300catch (Throwable t) {301if (k.isAssignableFrom(t.getClass())) pass();302else unexpected(t);}303}304305}306307308