fix hanging on AllData with large file
[jFCPlib.git] / src / test / java / net / pterodactylus / fcp / TempInputStreamTest.java
1 package net.pterodactylus.fcp;\r
2 \r
3 import org.junit.Test;\r
4 \r
5 import java.io.ByteArrayInputStream;\r
6 import java.io.IOException;\r
7 import java.io.InputStream;\r
8 import java.util.Arrays;\r
9 \r
10 import static org.hamcrest.MatcherAssert.assertThat;\r
11 import static org.hamcrest.Matchers.is;\r
12 import static org.junit.Assert.assertArrayEquals;\r
13 \r
14 \r
15 public class TempInputStreamTest {\r
16 \r
17     private byte[] prepareArrayOfNBytes(int n) {\r
18         byte[] data = new byte[n];\r
19         for (int i = 0;  i < n;  ++i) {\r
20             data[i] = (byte)i;\r
21         }\r
22         return data;\r
23     }\r
24 \r
25     private void checkTempInputStreamStoresPartOfAnotherStream(int length, int maxMemoryLength) throws IOException {\r
26         byte[] originalData = prepareArrayOfNBytes(length + 1);\r
27         InputStream anotherStream = new ByteArrayInputStream(originalData);\r
28         FcpUtils.TempInputStream cut = new FcpUtils.TempInputStream(anotherStream, length, maxMemoryLength);\r
29 \r
30         // check length bytes are read from anotherStream and are accessible from cut\r
31         byte[] buffer = new byte[length];\r
32         int n = cut.read(buffer);\r
33         assertThat(n, is(length));\r
34         assertArrayEquals(Arrays.copyOf(originalData, length), buffer);\r
35         assertThat(cut.read(), is(-1)); // check end of cut stream\r
36 \r
37         // check the rest of data in anotherStream is still there\r
38         n = anotherStream.read(buffer);\r
39         assertThat(n, is(1));\r
40         assertThat(buffer[0], is(originalData[originalData.length - 1]));\r
41         assertThat(anotherStream.read(), is(-1)); // check end of another stream\r
42     }\r
43 \r
44     @Test\r
45     public void tempInputStreamShouldCorrectlyStorePartOfAnotherStreamInMemory() throws IOException  {\r
46         checkTempInputStreamStoresPartOfAnotherStream(1, 1);\r
47     }\r
48 \r
49     @Test\r
50     public void tempInputStreamShouldCorrectlyStorePartOfAnotherStreamInFile() throws IOException  {\r
51         checkTempInputStreamStoresPartOfAnotherStream(2, 1);\r
52     }\r
53 \r
54 }\r