1 package org.sapia.ubik.util; 2 3 import java.io.ByteArrayOutputStream ; 4 import java.io.IOException ; 5 import java.nio.ByteBuffer ; 6 7 import junit.framework.TestCase; 8 9 18 public class ByteVectorTest extends TestCase{ 19 20 private ByteVector _out; 21 22 public ByteVectorTest(String name){ 23 super(name); 24 } 25 26 29 protected void setUp() throws Exception { 30 _out = new ByteVector(5, 1); 31 } 32 33 public void testWrite(){ 34 byte[] bytes = byteArray(10); 35 _out.write(bytes); 36 super.assertEquals(_out.arrayCount(), 2); 37 } 38 39 public void testWriteByteBuffer(){ 40 ByteBuffer bytes = byteBuffer(10); 41 _out.write(bytes); 42 super.assertEquals(_out.arrayCount(), 2); 43 } 44 45 public void testRead(){ 46 byte[] bytes = byteArray(7); 47 _out.write(bytes); 48 byte[] read = byteArray(7); 49 _out.reset(); 50 super.assertEquals(7, _out.read(read , 0, read.length)); 51 for(int i = 0; i < read.length; i++){ 52 super.assertEquals((int)read[i], (int)bytes[i]); 53 } 54 _out.reset(); 55 super.assertEquals(3, _out.read(read , 0, 3)); 56 for(int i = 0; i < read.length; i++){ 57 super.assertEquals((int)read[i], (int)bytes[i]); 58 } 59 _out.reset(); 60 int i = _out.read(); 61 super.assertEquals(0, i); 62 } 63 64 public void testWriteReadOutputStream() throws IOException { 65 byte[] bytes = byteArray(7); 66 ByteArrayOutputStream out = new ByteArrayOutputStream (); 67 _out.write(bytes); 68 _out.reset(); 69 _out.read(out); 70 byte[] written = out.toByteArray(); 71 super.assertEquals(7, written.length); 72 for(int i = 0; i < written.length; i++){ 73 super.assertEquals((int)written[i], (int)bytes[i]); 74 } 75 } 76 77 public void testReadByteBuffer(){ 78 ByteBuffer bytes = byteBuffer(7); 79 _out.write(bytes); 80 ByteBuffer read = byteBuffer(7); 81 _out.reset(); 82 super.assertEquals(7, _out.read(read)); 83 read.flip(); 84 bytes.flip(); 85 super.assertEquals(7, read.remaining()); 86 super.assertEquals(7, bytes.remaining()); 87 for(; read.hasRemaining(); ){ 88 super.assertEquals((int)read.get(), (int)bytes.get()); 89 } 90 } 91 92 public void testMark(){ 93 byte[] bytes = byteArray(7); 94 _out.write(bytes); 95 _out.mark(4); 96 _out.reset(); 97 super.assertEquals(4, _out.read()); 98 _out.mark(6); 99 _out.reset(); 100 super.assertEquals(6, _out.read()); 101 } 102 103 public void testToByteArray(){ 104 byte[] bytes = byteArray(7); 105 _out.write(bytes); 106 byte[] read = _out.toByteArray(); 107 super.assertEquals(7, read.length); 108 } 109 110 private byte[] byteArray(int size){ 111 byte[] b = new byte[size]; 112 for(int i = 0; i < size; i++){ 113 b[i] = (byte)i; 114 } 115 return b; 116 } 117 118 private ByteBuffer byteBuffer(int size){ 119 ByteBuffer buffer = ByteBuffer.allocate(size); 120 for(int i = 0; i < size; i++){ 121 buffer.put((byte)i); 122 } 123 buffer.flip(); 124 return buffer; 125 } 126 127 } 128 | Popular Tags |