View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   * http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.commons.compress.utils;
20  
21  import static org.junit.Assert.assertArrayEquals;
22  import static org.junit.Assert.assertEquals;
23  
24  import java.io.ByteArrayInputStream;
25  import java.io.ByteArrayOutputStream;
26  
27  import org.junit.Test;
28  
29  public class CountingStreamTest {
30  
31      @Test
32      public void output() throws Exception {
33          // I don't like "test all at once" tests either, but the class
34          // is so trivial
35          ByteArrayOutputStream bos = new ByteArrayOutputStream();
36          CountingOutputStream o = new CountingOutputStream(bos);
37          o.write(1);
38          assertEquals(1, o.getBytesWritten());
39          o.write(new byte[] { 2, 3 });
40          assertEquals(3, o.getBytesWritten());
41          o.write(new byte[] { 2, 3, 4, 5, }, 2, 1);
42          assertEquals(4, o.getBytesWritten());
43          o.count(-1);
44          assertEquals(4, o.getBytesWritten());
45          o.count(-2);
46          assertEquals(2, o.getBytesWritten());
47          o.close();
48          assertArrayEquals(new byte[] { 1, 2, 3, 4 }, bos.toByteArray());
49      }
50  
51      @Test
52      public void input() throws Exception {
53          // I don't like "test all at once" tests either, but the class
54          // is so trivial
55          ByteArrayInputStream bis =
56              new ByteArrayInputStream(new byte[] { 1, 2, 3, 4 });
57          CountingInputStream i = new CountingInputStream(bis);
58          assertEquals(1, i.read());
59          assertEquals(1, i.getBytesRead());
60          byte[] b = new byte[2];
61          i.read(b);
62          assertEquals(3, i.getBytesRead());
63          assertArrayEquals(new byte[] { 2, 3 }, b);
64          b = new byte[3];
65          i.read(b, 1, 1);
66          assertArrayEquals(new byte[] { 0, 4, 0 }, b);
67          assertEquals(4, i.getBytesRead());
68          i.count(-1);
69          assertEquals(4, i.getBytesRead());
70          i.count(-2);
71          assertEquals(2, i.getBytesRead());
72          i.close();
73      }
74  
75  }