File: PipelineTest.java

package info (click to toggle)
openjdk-11 11.0.4%2B11-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 757,028 kB
  • sloc: java: 5,016,041; xml: 1,191,974; cpp: 934,731; ansic: 555,697; sh: 24,299; objc: 12,703; python: 3,602; asm: 3,415; makefile: 2,772; awk: 351; sed: 172; perl: 114; jsp: 24; csh: 3
file content (298 lines) | stat: -rw-r--r-- 11,012 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
/*
 * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.util.Arrays;
import java.util.List;

/*
 * @test PipelineTest
 */

public class PipelineTest {

    private static void realMain(String[] args) throws Throwable {
        t1_simplePipeline();
        t2_translatePipeline();
        t3_redirectErrorStream();
        t4_failStartPipeline();
    }

    /**
     * Return a list of the varargs arguments.
     * @param args elements to include in the list
     * @param <T> the type of the elements
     * @return a {@code List<T>} of the arguments
     */
    @SafeVarargs
    @SuppressWarnings("varargs")
    static <T> List<T> asList(T... args) {
        return Arrays.asList(args);
    }

    /**
     * T1 - simple copy between two processes
     */
    static void t1_simplePipeline() {
        try {
            String s1 = "Now is the time to check!";
            verify(s1, s1,
                    asList(new ProcessBuilder("cat")));
            verify(s1, s1,
                    asList(new ProcessBuilder("cat"),
                            new ProcessBuilder("cat")));
            verify(s1, s1,
                    asList(new ProcessBuilder("cat"),
                            new ProcessBuilder("cat"),
                            new ProcessBuilder("cat")));
        } catch (Throwable t) {
            unexpected(t);
        }
    }

    /**
     * Pipeline that modifies the content.
     */
    static void t2_translatePipeline() {
        try {
            String s2 = "Now is the time to check!";
            String r2 = s2.replace('e', 'E').replace('o', 'O');
            verify(s2, r2,
                    asList(new ProcessBuilder("tr", "e", "E"),
                            new ProcessBuilder("tr", "o", "O")));
        } catch (Throwable t) {
            unexpected(t);
        }
    }

    /**
     * Test that redirectErrorStream sends standard error of the first process
     * to the standard output. The standard error of the first process should be empty.
     * The standard output of the 2nd should contain the error message including the bad file name.
     */
    static void t3_redirectErrorStream() {
        try {
            File p1err = new File("p1-test.err");
            File p2out = new File("p2-test.out");

            List<Process> processes = ProcessBuilder.startPipeline(
                    asList(new ProcessBuilder("cat", "NON-EXISTENT-FILE")
                                    .redirectErrorStream(true)
                                    .redirectError(p1err),
                            new ProcessBuilder("cat").redirectOutput(p2out)));
            waitForAll(processes);

            check("".equals(fileContents(p1err)), "The first process standard error should be empty");
            String p2contents = fileContents(p2out);
            check(p2contents.contains("NON-EXISTENT-FILE"),
                    "The error from the first process should be in the output of the second: " + p2contents);
        } catch (Throwable t) {
            unexpected(t);
        }
    }

    /**
     * Test that no processes are left after a failed startPipeline.
     * Test illegal combinations of redirects.
     */
    static void t4_failStartPipeline() {
        File p1err = new File("p1-test.err");
        File p2out = new File("p2-test.out");

        THROWS(IllegalArgumentException.class,
                () -> {
                    // Test that output redirect != PIPE throws IAE
                    List<Process> processes = ProcessBuilder.startPipeline(
                            asList(new ProcessBuilder("cat", "NON-EXISTENT-FILE1")
                                            .redirectOutput(p1err),
                                    new ProcessBuilder("cat")));
                },
                () -> {
                    // Test that input redirect != PIPE throws IAE
                    List<Process> processes = ProcessBuilder.startPipeline(
                            asList(new ProcessBuilder("cat", "NON-EXISTENT-FILE2"),
                                    new ProcessBuilder("cat").redirectInput(p2out)));
                }
        );

        THROWS(NullPointerException.class,
                () -> {
                    List<Process> processes = ProcessBuilder.startPipeline(
                            asList(new ProcessBuilder("cat", "a"), null));
                },
                () -> {
                    List<Process> processes = ProcessBuilder.startPipeline(
                            asList(null, new ProcessBuilder("cat", "b")));
                }
        );

        THROWS(IOException.class,
                () -> {
                    List<Process> processes = ProcessBuilder.startPipeline(
                            asList(new ProcessBuilder("cat", "c"),
                                    new ProcessBuilder("NON-EXISTENT-COMMAND")));
                });

        // Check no subprocess are left behind
        ProcessHandle.current().children().forEach(PipelineTest::print);
        ProcessHandle.current().children()
                .filter(p -> p.info().command().orElse("").contains("cat"))
                .forEach(p -> fail("process should have been destroyed: " + p));
    }

    static void verify(String input, String expected, List<ProcessBuilder> builders) throws IOException {
        File infile = new File("test.in");
        File outfile = new File("test.out");
        setFileContents(infile, expected);
        for (int i = 0; i < builders.size(); i++) {
            ProcessBuilder b = builders.get(i);
            if (i == 0) {
                b.redirectInput(infile);
            }
            if (i == builders.size() - 1) {
                b.redirectOutput(outfile);
            }
        }
        List<Process> processes = ProcessBuilder.startPipeline(builders);
        verifyProcesses(processes);
        waitForAll(processes);
        String result = fileContents(outfile);
        System.out.printf(" in: %s%nout: %s%n", input, expected);
        check(result.equals(expected), "result not as expected");
    }

    /**
     * Wait for each of the processes to be done.
     *
     * @param processes the list  of processes to check
     */
    static void waitForAll(List<Process> processes) {
        processes.forEach(p -> {
            try {
                int status = p.waitFor();
            } catch (InterruptedException ie) {
                unexpected(ie);
            }
        });
    }

    static void print(ProcessBuilder pb) {
        if (pb != null) {
            System.out.printf(" pb: %s%n", pb);
            System.out.printf("    cmd: %s%n", pb.command());
        }
    }

    static void print(ProcessHandle p) {
        System.out.printf("process: pid: %d, info: %s%n",
                p.pid(), p.info());
    }

    // Check various aspects of the processes
    static void verifyProcesses(List<Process> processes) {
        for (int i = 0; i < processes.size(); i++) {
            Process p = processes.get(i);
            if (i != 0) {
                verifyNullStream(p.getOutputStream(), "getOutputStream");
            }
            if (i == processes.size() - 1) {
                verifyNullStream(p.getInputStream(), "getInputStream");
                verifyNullStream(p.getErrorStream(), "getErrorStream");
            }
        }
    }

    static void verifyNullStream(OutputStream s, String msg) {
        try {
            s.write(0xff);
            fail("Stream should have been a NullStream" + msg);
        } catch (IOException ie) {
            // expected
        }
    }

    static void verifyNullStream(InputStream s, String msg) {
        try {
            int len = s.read();
            check(len == -1, "Stream should have been a NullStream" + msg);
        } catch (IOException ie) {
            // expected
        }
    }

    static void setFileContents(File file, String contents) {
        try {
            Writer w = new FileWriter(file);
            w.write(contents);
            w.close();
        } catch (Throwable t) { unexpected(t); }
    }

    static String fileContents(File file) {
        try {
            Reader r = new FileReader(file);
            StringBuilder sb = new StringBuilder();
            char[] buffer = new char[1024];
            int n;
            while ((n = r.read(buffer)) != -1)
                sb.append(buffer,0,n);
            r.close();
            return new String(sb);
        } catch (Throwable t) { unexpected(t); return ""; }
    }

    //--------------------- Infrastructure ---------------------------
    static volatile int passed = 0, failed = 0;
    static void pass() {passed++;}
    static void fail() {failed++; Thread.dumpStack();}
    static void fail(String msg) {System.err.println(msg); fail();}
    static void unexpected(Throwable t) {failed++; t.printStackTrace();}
    static void check(boolean cond) {if (cond) pass(); else fail();}
    static void check(boolean cond, String m) {if (cond) pass(); else fail(m);}
    static void equal(Object x, Object y) {
        if (x == null ? y == null : x.equals(y)) pass();
        else fail(">'" + x + "'<" + " not equal to " + "'" + y + "'");
    }

    public static void main(String[] args) throws Throwable {
        try {realMain(args);} catch (Throwable t) {unexpected(t);}
        System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
        if (failed > 0) throw new AssertionError("Some tests failed");
    }
    interface Fun {void f() throws Throwable;}
    static void THROWS(Class<? extends Throwable> k, Fun... fs) {
        for (Fun f : fs)
            try { f.f(); fail("Expected " + k.getName() + " not thrown"); }
            catch (Throwable t) {
                if (k.isAssignableFrom(t.getClass())) pass();
                else unexpected(t);}
    }

}