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
20 import java.io.OutputStream;
21 import java.io.ByteArrayOutputStream;
22 import java.io.IOException;
23
24 import junit.framework.TestCase;
25 import org.apache.commons.io.IOUtils;
26 import org.apache.commons.io.input.NullInputStream;
27
28
29
30
31
32
33 public class CountingOutputStreamTest extends TestCase {
34
35 public CountingOutputStreamTest(String name) {
36 super(name);
37 }
38
39 public void testCounting() throws IOException {
40 ByteArrayOutputStream baos = new ByteArrayOutputStream();
41 CountingOutputStream cos = new CountingOutputStream(baos);
42
43 for(int i = 0; i < 20; i++) {
44 cos.write(i);
45 }
46 assertByteArrayEquals("CountingOutputStream.write(int)", baos.toByteArray(), 0, 20);
47 assertEquals("CountingOutputStream.getCount()", cos.getCount(), 20);
48
49 byte[] array = new byte[10];
50 for(int i = 20; i < 30; i++) {
51 array[i-20] = (byte)i;
52 }
53 cos.write(array);
54 assertByteArrayEquals("CountingOutputStream.write(byte[])", baos.toByteArray(), 0, 30);
55 assertEquals("CountingOutputStream.getCount()", cos.getCount(), 30);
56
57 for(int i = 25; i < 35; i++) {
58 array[i-25] = (byte)i;
59 }
60 cos.write(array, 5, 5);
61 assertByteArrayEquals("CountingOutputStream.write(byte[], int, int)", baos.toByteArray(), 0, 35);
62 assertEquals("CountingOutputStream.getCount()", cos.getCount(), 35);
63
64 int count = cos.resetCount();
65 assertEquals("CountingOutputStream.resetCount()", count, 35);
66
67 for(int i = 0; i < 10; i++) {
68 cos.write(i);
69 }
70 assertByteArrayEquals("CountingOutputStream.write(int)", baos.toByteArray(), 35, 45);
71 assertEquals("CountingOutputStream.getCount()", cos.getCount(), 10);
72
73 }
74
75
76
77
78 public void testLargeFiles_IO84() throws Exception {
79 long size = (long)Integer.MAX_VALUE + (long)1;
80
81 NullInputStream mock = new NullInputStream(size);
82 OutputStream nos = new NullOutputStream();
83 CountingOutputStream cos = new CountingOutputStream(nos);
84
85
86 IOUtils.copyLarge(mock, cos);
87 try {
88 cos.getCount();
89 fail("Expected getCount() to throw an ArithmeticException");
90 } catch (ArithmeticException ae) {
91
92 }
93 try {
94 cos.resetCount();
95 fail("Expected resetCount() to throw an ArithmeticException");
96 } catch (ArithmeticException ae) {
97
98 }
99
100 mock.close();
101
102
103 IOUtils.copyLarge(mock, cos);
104 assertEquals("getByteCount()", size, cos.getByteCount());
105 assertEquals("resetByteCount()", size, cos.resetByteCount());
106 }
107
108 private void assertByteArrayEquals(String msg, byte[] array, int start, int end) {
109 for (int i = start; i < end; i++) {
110 assertEquals(msg+": array[" + i + "] mismatch", array[i], i-start);
111 }
112 }
113
114 }