1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package net.sf.beep4j.internal.util;
17
18 import java.io.InputStream;
19 import java.nio.ByteBuffer;
20 import java.util.Arrays;
21
22 import junit.framework.TestCase;
23
24 public class ByteBufferInputStreamTest extends TestCase {
25
26 private ByteBuffer getTestBuffer() {
27 ByteBuffer buffer = ByteBuffer.allocate(50);
28 for (byte b = 25; b < 75; b++) {
29 buffer.put(b);
30 }
31 buffer.flip();
32 return buffer;
33 }
34
35 private void assertEndOfStream(InputStream stream) throws Exception {
36 assertEquals(-1, stream.read());
37 }
38
39 private void assertArrayEquals(byte[] a1, byte[] a2) {
40 assertTrue(Arrays.equals(a1, a2));
41 }
42
43 public void testReadEmpty() throws Exception {
44 InputStream stream = new ByteBufferInputStream(ByteBuffer.allocate(0));
45 assertEndOfStream(stream);
46 }
47
48 public void testRead() throws Exception {
49 InputStream stream = new ByteBufferInputStream(getTestBuffer());
50
51 for (int b = 25; b < 75; b++) {
52 assertEquals(b, stream.read());
53 assertEquals(74 - b, stream.available());
54 }
55
56 assertEndOfStream(stream);
57 }
58
59 public void testMarkReset() throws Exception {
60 InputStream stream = new ByteBufferInputStream(getTestBuffer());
61
62 for (byte b = 25; b < 30; b++) {
63 assertEquals(b, stream.read());
64 }
65
66 stream.mark(Integer.MAX_VALUE);
67
68 for (byte b = 30; b < 40; b++) {
69 assertEquals(b, stream.read());
70 }
71
72 stream.reset();
73 assertEquals(45, stream.available());
74
75 for (byte b = 30; b < 40; b++) {
76 assertEquals(b, stream.read());
77 }
78 }
79
80 public void testBulkReadEmpty() throws Exception {
81 InputStream stream = new ByteBufferInputStream(ByteBuffer.allocate(0));
82 assertEquals(-1, stream.read(new byte[10]));
83 }
84
85 public void testBulkRead() throws Exception {
86 InputStream stream = new ByteBufferInputStream(getTestBuffer());
87 byte[] buf = new byte[10];
88
89 assertEquals(10, stream.read(buf));
90 assertArrayEquals(new byte[] { 25, 26, 27, 28, 29, 30, 31, 32, 33, 34 }, buf);
91
92 assertEquals(7, stream.read(buf, 2, 7));
93 assertArrayEquals(new byte[] { 25, 26, 35, 36, 37, 38, 39, 40, 41, 34 }, buf);
94
95 assertEquals(8, stream.read(buf, 0, 8));
96 assertArrayEquals(new byte[] { 42, 43, 44, 45, 46, 47, 48, 49, 41, 34 }, buf);
97
98 assertEquals(25, stream.available());
99 assertEquals(25, stream.read(new byte[30]));
100 assertEndOfStream(stream);
101 }
102
103 }