1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.io.input;
18
19 import static org.junit.jupiter.api.Assertions.assertArrayEquals;
20 import static org.junit.jupiter.api.Assertions.assertEquals;
21 import static org.junit.jupiter.api.Assertions.assertThrows;
22
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.util.Arrays;
26
27 import org.apache.commons.io.IOUtils;
28 import org.junit.jupiter.api.Test;
29
30
31
32
33 public class CircularInputStreamTest {
34
35 private void assertStreamOutput(final byte[] toCycle, final byte[] expected) throws IOException {
36 final byte[] actual = new byte[expected.length];
37
38 try (InputStream infStream = createInputStream(toCycle, -1)) {
39 final int actualReadBytes = infStream.read(actual);
40
41 assertArrayEquals(expected, actual);
42 assertEquals(expected.length, actualReadBytes);
43 }
44 }
45
46 private InputStream createInputStream(final byte[] repeatContent, final long targetByteCount) {
47 return new CircularInputStream(repeatContent, targetByteCount);
48 }
49
50 @Test
51 public void testContainsEofInputSize0() {
52 assertThrows(IllegalArgumentException.class, () -> createInputStream(new byte[] { -1 }, 0));
53 }
54
55 @Test
56 public void testCount0() throws IOException {
57 try (InputStream in = createInputStream(new byte[] { 1, 2 }, 0)) {
58 assertEquals(IOUtils.EOF, in.read());
59 }
60 }
61
62 @Test
63 public void testCount0InputSize0() {
64 assertThrows(IllegalArgumentException.class, () -> createInputStream(new byte[] {}, 0));
65 }
66
67 @Test
68 public void testCount0InputSize1() throws IOException {
69 try (InputStream in = createInputStream(new byte[] { 1 }, 0)) {
70 assertEquals(IOUtils.EOF, in.read());
71 }
72 }
73
74 @Test
75 public void testCount1InputSize1() throws IOException {
76 try (InputStream in = createInputStream(new byte[] { 1 }, 1)) {
77 assertEquals(1, in.read());
78 assertEquals(IOUtils.EOF, in.read());
79 }
80 }
81
82 @Test
83 public void testCycleBytes() throws IOException {
84 final byte[] input = { 1, 2 };
85 final byte[] expected = { 1, 2, 1, 2, 1 };
86
87 assertStreamOutput(input, expected);
88 }
89
90 @Test
91 public void testNullInputSize0() {
92 assertThrows(NullPointerException.class, () -> createInputStream(null, 0));
93 }
94
95 @Test
96 public void testWholeRangeOfBytes() throws IOException {
97 final int size = Byte.MAX_VALUE - Byte.MIN_VALUE + 1;
98 final byte[] contentToCycle = new byte[size];
99 byte value = Byte.MIN_VALUE;
100 for (int i = 0; i < contentToCycle.length; i++) {
101 contentToCycle[i] = value == IOUtils.EOF ? 0 : value;
102 value++;
103 }
104
105 final byte[] expectedOutput = Arrays.copyOf(contentToCycle, size);
106
107 assertStreamOutput(contentToCycle, expectedOutput);
108 }
109
110 }