View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.io.input;
18  
19  import static org.junit.jupiter.api.Assertions.assertEquals;
20  import static org.junit.jupiter.api.Assertions.assertFalse;
21  import static org.junit.jupiter.api.Assertions.assertThrows;
22  import static org.junit.jupiter.api.Assertions.assertThrowsExactly;
23  import static org.junit.jupiter.api.Assertions.assertTrue;
24  
25  import java.io.ByteArrayInputStream;
26  import java.io.IOException;
27  import java.io.InputStream;
28  import java.nio.charset.StandardCharsets;
29  import java.util.concurrent.atomic.AtomicBoolean;
30  
31  import org.apache.commons.io.IOUtils;
32  import org.apache.commons.io.test.CustomIOException;
33  import org.junit.jupiter.api.BeforeEach;
34  import org.junit.jupiter.api.Test;
35  
36  /**
37   * Tests {@link AutoCloseInputStream}.
38   */
39  class AutoCloseInputStreamTest {
40  
41      private byte[] data;
42  
43      private AutoCloseInputStream stream;
44  
45      @SuppressWarnings("deprecation")
46      @BeforeEach
47      public void setUp() {
48          data = new byte[] { 'x', 'y', 'z' };
49          stream = new AutoCloseInputStream(new ByteArrayInputStream(data));
50      }
51  
52      @Test
53      void testAfterReadConsumer() throws Exception {
54          final byte[] hello = "Hello".getBytes(StandardCharsets.UTF_8);
55          final AtomicBoolean boolRef = new AtomicBoolean();
56          // @formatter:off
57          try (InputStream bounded = AutoCloseInputStream.builder()
58                  .setInputStream(new ByteArrayInputStream(hello))
59                  .setAfterRead(i -> boolRef.set(true))
60                  .get()) {
61              IOUtils.consume(bounded);
62          }
63          // @formatter:on
64          assertTrue(boolRef.get());
65          // Throwing
66          final String message = "test exception message";
67          // @formatter:off
68          try (InputStream bounded = AutoCloseInputStream.builder()
69                  .setInputStream(new ByteArrayInputStream(hello))
70                  .setAfterRead(i -> {
71                      throw new CustomIOException(message);
72                  })
73                  .get()) {
74              assertEquals(message, assertThrowsExactly(CustomIOException.class, () -> IOUtils.consume(bounded)).getMessage());
75          }
76          // @formatter:on
77      }
78  
79      @Test
80      void testAvailableAfterClose() throws IOException {
81          final InputStream shadow;
82          try (InputStream inputStream = new AutoCloseInputStream(new ByteArrayInputStream(data))) {
83              assertEquals(3, inputStream.available());
84              shadow = inputStream;
85          }
86          assertEquals(0, shadow.available());
87      }
88  
89      @Test
90      void testAvailableAll() throws IOException {
91          try (InputStream inputStream = new AutoCloseInputStream(new ByteArrayInputStream(data))) {
92              assertEquals(3, inputStream.available());
93              IOUtils.toByteArray(inputStream);
94              assertEquals(0, inputStream.available());
95          }
96      }
97  
98      @Test
99      void testAvailableNull() throws IOException {
100         try (InputStream inputStream = new AutoCloseInputStream(null)) {
101             assertEquals(0, inputStream.available());
102             assertEquals(0, inputStream.available());
103         }
104     }
105 
106     @Test
107     void testBuilderGet() {
108         // java.lang.IllegalStateException: origin == null
109         assertThrows(IllegalStateException.class, () -> AutoCloseInputStream.builder().get());
110     }
111 
112     @Test
113     void testClose() throws IOException {
114         stream.close();
115         assertTrue(stream.isClosed(), "closed");
116         assertEquals(-1, stream.read(), "read()");
117         assertTrue(stream.isClosed(), "closed");
118     }
119 
120     @Test
121     void testCloseHandleIOException() throws IOException {
122         ProxyInputStreamTest.testCloseHandleIOException(AutoCloseInputStream.builder());
123     }
124 
125     @Test
126     void testFinalize() throws Throwable {
127         stream.finalize();
128         assertTrue(stream.isClosed(), "closed");
129         assertEquals(-1, stream.read(), "read()");
130     }
131 
132     @Test
133     void testRead() throws IOException {
134         for (final byte element : data) {
135             assertEquals(element, stream.read(), "read()");
136             assertFalse(stream.isClosed(), "closed");
137         }
138         assertEquals(-1, stream.read(), "read()");
139         assertTrue(stream.isClosed(), "closed");
140     }
141 
142     @Test
143     void testReadBuffer() throws IOException {
144         final byte[] b = new byte[data.length * 2];
145         int total = 0;
146         for (int n = 0; n != -1; n = stream.read(b)) {
147             assertFalse(stream.isClosed(), "closed");
148             for (int i = 0; i < n; i++) {
149                 assertEquals(data[total + i], b[i], "read(b)");
150             }
151             total += n;
152         }
153         assertEquals(data.length, total, "read(b)");
154         assertTrue(stream.isClosed(), "closed");
155         assertEquals(-1, stream.read(b), "read(b)");
156     }
157 
158     @Test
159     void testReadBufferOffsetLength() throws IOException {
160         final byte[] b = new byte[data.length * 2];
161         int total = 0;
162         for (int n = 0; n != -1; n = stream.read(b, total, b.length - total)) {
163             assertFalse(stream.isClosed(), "closed");
164             total += n;
165         }
166         assertEquals(data.length, total, "read(b, off, len)");
167         for (int i = 0; i < data.length; i++) {
168             assertEquals(data[i], b[i], "read(b, off, len)");
169         }
170         assertTrue(stream.isClosed(), "closed");
171         assertEquals(-1, stream.read(b, 0, b.length), "read(b, off, len)");
172     }
173 
174     private void testResetBeforeEnd(final AutoCloseInputStream inputStream) throws IOException {
175         inputStream.mark(1);
176         assertEquals('1', inputStream.read());
177         inputStream.reset();
178         assertEquals('1', inputStream.read());
179         assertEquals('2', inputStream.read());
180         inputStream.reset();
181         assertEquals('1', inputStream.read());
182         assertEquals('2', inputStream.read());
183         assertEquals('3', inputStream.read());
184         inputStream.reset();
185         assertEquals('1', inputStream.read());
186         assertEquals('2', inputStream.read());
187         assertEquals('3', inputStream.read());
188         assertEquals('4', inputStream.read());
189         inputStream.reset();
190         assertEquals('1', inputStream.read());
191     }
192 
193     @Test
194     void testResetBeforeEndCtor() throws IOException {
195         try (AutoCloseInputStream inputStream = new AutoCloseInputStream(new ByteArrayInputStream("1234".getBytes()))) {
196             testResetBeforeEnd(inputStream);
197         }
198     }
199 
200     @Test
201     void testResetBeforeEndSetByteArray() throws IOException {
202         try (AutoCloseInputStream inputStream = AutoCloseInputStream.builder().setByteArray("1234".getBytes()).get()) {
203             testResetBeforeEnd(inputStream);
204         }
205     }
206 
207     @Test
208     void testResetBeforeEndSetCharSequence() throws IOException {
209         try (AutoCloseInputStream inputStream = AutoCloseInputStream.builder().setCharSequence("1234").get()) {
210             testResetBeforeEnd(inputStream);
211         }
212     }
213 
214     @Test
215     void testResetBeforeEndSetInputStream() throws IOException {
216         try (AutoCloseInputStream inputStream = AutoCloseInputStream.builder().setInputStream(new ByteArrayInputStream("1234".getBytes())).get()) {
217             testResetBeforeEnd(inputStream);
218         }
219     }
220 
221     @Test
222     void testrReadAfterClose() throws IOException {
223         final InputStream shadow;
224         try (InputStream inputStream = new AutoCloseInputStream(new ByteArrayInputStream(data))) {
225             assertEquals(3, inputStream.available());
226             shadow = inputStream;
227         }
228         assertEquals(IOUtils.EOF, shadow.read());
229     }
230 
231 }