View Javadoc
1   /*
2    * Copyright (C) 2020, Michael Dardis. and others
3    *
4    * This program and the accompanying materials are made available under the
5    * terms of the Eclipse Distribution License v. 1.0 which is available at
6    * https://www.eclipse.org/org/documents/edl-v10.php.
7    *
8    * SPDX-License-Identifier: BSD-3-Clause
9    */
10  package org.eclipse.jgit.util.io;
11  
12  import static org.junit.Assert.assertArrayEquals;
13  import static org.junit.Assert.assertFalse;
14  import static org.junit.Assert.assertTrue;
15  
16  import java.io.ByteArrayOutputStream;
17  import java.io.IOException;
18  
19  import org.eclipse.jgit.lib.Constants;
20  import org.junit.Test;
21  
22  public class TeeOutputStreamTest {
23  
24  	@Test
25  	public void test() throws IOException {
26  		byte[] data = Constants.encode("Hello World");
27  
28  		TestOutput first = new TestOutput();
29  		TestOutput second = new TestOutput();
30  		try (TeeOutputStream tee = new TeeOutputStream(first, second)) {
31  			tee.write(data);
32  			assertArrayEquals("Stream output must match", first.toByteArray(),
33  					second.toByteArray());
34  
35  			tee.write(1);
36  			assertArrayEquals("Stream output must match", first.toByteArray(),
37  					second.toByteArray());
38  
39  			tee.write(data, 1, 4); // Test partial write methods
40  			assertArrayEquals("Stream output must match", first.toByteArray(),
41  					second.toByteArray());
42  		}
43  		assertTrue("First stream should be closed", first.closed);
44  		assertTrue("Second stream should be closed", second.closed);
45  	}
46  
47  	@Test
48  	public void testCloseException() {
49  		TestOutput first = new TestOutput() {
50  			@Override
51  			public void close() throws IOException {
52  				throw new IOException();
53  			}
54  
55  		};
56  		TestOutput second = new TestOutput();
57  
58  		@SuppressWarnings("resource")
59  		TeeOutputStream tee = new TeeOutputStream(first, second);
60  		try {
61  			tee.close();
62  		} catch (IOException ex) {
63  			// Expected from first closed
64  		}
65  		assertFalse("First stream should not be closed", first.closed);
66  		assertTrue("Second stream should still be closed if first close failed",
67  				second.closed);
68  	}
69  
70  	private static class TestOutput extends ByteArrayOutputStream {
71  
72  		private boolean closed;
73  
74  		@Override
75  		public void close() throws IOException {
76  			closed = true;
77  			super.close();
78  		}
79  	}
80  
81  }