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