1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.io.input.buffer;
19
20 import static org.junit.jupiter.api.Assertions.assertEquals;
21 import static org.junit.jupiter.api.Assertions.assertNotEquals;
22 import static org.junit.jupiter.api.Assertions.assertTrue;
23 import static org.junit.jupiter.api.Assertions.fail;
24
25 import java.io.ByteArrayInputStream;
26 import java.io.IOException;
27 import java.util.Random;
28
29 import org.junit.jupiter.api.Test;
30
31
32
33
34 class PeekableInputStreamTest {
35
36
37
38
39 private final Random random = new Random(1530960934483L);
40
41 void asssertNotEof(final int offset, final int res) {
42 assertNotEquals(-1, res, () -> "Unexpected EOF at offset " + offset);
43 }
44
45
46
47
48 private byte[] newInputBuffer() {
49 final byte[] buffer = new byte[16 * 512 + random.nextInt(512)];
50 random.nextBytes(buffer);
51 return buffer;
52 }
53
54 @Test
55 void testIO683() throws IOException {
56 final byte[] buffer = {0, 1, -2, -2, -1, 4};
57 try (ByteArrayInputStream bais = new ByteArrayInputStream(buffer); PeekableInputStream cbis = new PeekableInputStream(bais)) {
58 int b;
59 int i = 0;
60 while ((b = cbis.read()) != -1) {
61 assertEquals(buffer[i] & 0xFF, b, "byte at index " + i + " should be equal");
62 i++;
63 }
64 assertEquals(buffer.length, i, "Should have read all the bytes");
65 }
66 }
67
68 @Test
69 void testRandomRead() throws Exception {
70 final byte[] inputBuffer = newInputBuffer();
71 final byte[] bufferCopy = new byte[inputBuffer.length];
72 final ByteArrayInputStream bais = new ByteArrayInputStream(inputBuffer);
73 @SuppressWarnings("resource")
74 final PeekableInputStream cbis = new PeekableInputStream(bais, 253);
75 int offset = 0;
76 final byte[] readBuffer = new byte[256];
77 while (offset < bufferCopy.length) {
78 switch (random.nextInt(2)) {
79 case 0: {
80 final int res = cbis.read();
81 asssertNotEof(offset, res);
82
83 assertEquals(inputBuffer[offset], (byte) res, "Expected " + inputBuffer[offset] + " at offset " + offset + ", got " + res);
84 ++offset;
85 break;
86 }
87 case 1: {
88 final int res = cbis.read(readBuffer, 0, random.nextInt(readBuffer.length + 1));
89 asssertNotEof(offset, res);
90 assertNotEquals(0, res, "Unexpected zero-byte-result at offset " + offset);
91 for (int i = 0; i < res; i++) {
92 assertEquals(inputBuffer[offset], readBuffer[i], "Expected " + inputBuffer[offset] + " at offset " + offset + ", got " + readBuffer[i]);
93 ++offset;
94 }
95 break;
96 }
97 default:
98 fail("Unexpected random choice value");
99 }
100 }
101 assertTrue(true, "Test finished OK");
102 }
103 }