1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.io.output;
18
19 import static org.junit.jupiter.api.Assertions.assertEquals;
20 import static org.junit.jupiter.api.Assertions.assertThrows;
21
22 import java.io.ByteArrayOutputStream;
23 import java.io.IOException;
24
25 import org.apache.commons.io.IOUtils;
26 import org.apache.commons.io.input.NullInputStream;
27 import org.junit.jupiter.api.Test;
28
29
30
31
32 public class CountingOutputStreamTest {
33
34 private void assertByteArrayEquals(final String msg, final byte[] array, final int start, final int end) {
35 for (int i = start; i < end; i++) {
36 assertEquals(array[i], i-start, msg+": array[" + i + "] mismatch");
37 }
38 }
39
40 @Test
41 public void testCounting() throws IOException {
42 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
43 try (CountingOutputStream cos = new CountingOutputStream(baos)) {
44
45 for (int i = 0; i < 20; i++) {
46 cos.write(i);
47 }
48 assertByteArrayEquals("CountingOutputStream.write(int)", baos.toByteArray(), 0, 20);
49 assertEquals(cos.getCount(), 20, "CountingOutputStream.getCount()");
50
51 final byte[] array = new byte[10];
52 for (int i = 20; i < 30; i++) {
53 array[i - 20] = (byte) i;
54 }
55 cos.write(array);
56 assertByteArrayEquals("CountingOutputStream.write(byte[])", baos.toByteArray(), 0, 30);
57 assertEquals(cos.getCount(), 30, "CountingOutputStream.getCount()");
58
59 for (int i = 25; i < 35; i++) {
60 array[i - 25] = (byte) i;
61 }
62 cos.write(array, 5, 5);
63 assertByteArrayEquals("CountingOutputStream.write(byte[], int, int)", baos.toByteArray(), 0, 35);
64 assertEquals(cos.getCount(), 35, "CountingOutputStream.getCount()");
65
66 final int count = cos.resetCount();
67 assertEquals(count, 35, "CountingOutputStream.resetCount()");
68
69 for (int i = 0; i < 10; i++) {
70 cos.write(i);
71 }
72 assertByteArrayEquals("CountingOutputStream.write(int)", baos.toByteArray(), 35, 45);
73 assertEquals(cos.getCount(), 10, "CountingOutputStream.getCount()");
74 }
75 }
76
77
78
79
80 @Test
81 public void testLargeFiles_IO84() throws Exception {
82 final long size = (long) Integer.MAX_VALUE + (long) 1;
83
84 final NullInputStream mock = new NullInputStream(size);
85 final CountingOutputStream cos = new CountingOutputStream(NullOutputStream.INSTANCE);
86
87
88 IOUtils.copyLarge(mock, cos);
89 assertThrows(ArithmeticException.class, () -> cos.getCount());
90 assertThrows(ArithmeticException.class, () -> cos.resetCount());
91
92 mock.close();
93
94
95 IOUtils.copyLarge(mock, cos);
96 assertEquals(size, cos.getByteCount(), "getByteCount()");
97 assertEquals(size, cos.resetByteCount(), "resetByteCount()");
98 }
99
100 }