1 16 17 package org.apache.commons.io.output; 18 19 import java.io.IOException ; 20 21 import junit.framework.TestCase; 22 23 28 public class ByteArrayOutputStreamTestCase extends TestCase { 29 30 private static final byte[] DATA; 31 32 static { 33 DATA = new byte[64]; 34 for (byte i = 0; i < 64; i++) { 35 DATA[i] = i; 36 } 37 } 38 39 public ByteArrayOutputStreamTestCase(String name) { 40 super(name); 41 } 42 43 private int writeData(ByteArrayOutputStream baout, 44 java.io.ByteArrayOutputStream ref, 45 int count) throws IOException { 46 if (count > DATA.length) { 47 throw new IllegalArgumentException ("Requesting too many bytes"); 48 } 49 if (count == 0) { 50 baout.write(100); 51 ref.write(100); 52 return 1; 53 } else { 54 baout.write(DATA, 0, count); 55 ref.write(DATA, 0, count); 56 return count; 57 } 58 } 59 60 private int writeData(ByteArrayOutputStream baout, 61 java.io.ByteArrayOutputStream ref, 62 int[] instructions) throws IOException { 63 int written = 0; 64 for (int i = 0; i < instructions.length; i++) { 65 written += writeData(baout, ref, instructions[i]); 66 } 67 return written; 68 } 69 70 private static boolean byteCmp(byte[] src, byte[] cmp) { 71 for (int i = 0; i < cmp.length; i++) { 72 if (src[i] != cmp[i]) { 73 return false; 74 } 75 } 76 return true; 77 } 78 79 private void checkByteArrays(byte[] expected, byte[] actual) { 80 if (expected.length != actual.length) { 81 fail("Resulting byte arrays are not equally long"); 82 } 83 if (!byteCmp(expected, actual)) { 84 fail("Resulting byte arrays are not equal"); 85 } 86 } 87 88 private void checkStreams( 89 ByteArrayOutputStream actual, 90 java.io.ByteArrayOutputStream expected) { 91 assertEquals("Sizes are not equal", expected.size(), actual.size()); 92 byte[] buf = actual.toByteArray(); 93 byte[] refbuf = expected.toByteArray(); 94 checkByteArrays(buf, refbuf); 95 } 96 97 public void testStream() throws Exception { 98 int written; 99 100 ByteArrayOutputStream baout = new ByteArrayOutputStream(32); 103 java.io.ByteArrayOutputStream ref = new java.io.ByteArrayOutputStream (); 104 105 written = writeData(baout, ref, new int[] {4, 10, 22}); 107 checkStreams(baout, ref); 108 109 written = writeData(baout, ref, new int[] {20, 12}); 111 checkStreams(baout, ref); 112 113 baout.reset(); 115 ref.reset(); 116 117 written = writeData(baout, ref, new int[] {5, 47, 33, 60, 1, 0, 8}); 119 checkStreams(baout, ref); 120 121 ByteArrayOutputStream baout1 = new ByteArrayOutputStream(32); 124 ref.writeTo(baout1); 125 java.io.ByteArrayOutputStream ref1 = new java.io.ByteArrayOutputStream (); 126 baout.writeTo(ref1); 127 checkStreams(baout1, ref1); 128 129 String baoutString = baout.toString("ASCII"); 131 String refString = ref.toString("ASCII"); 132 assertEquals("ASCII decoded String must be equal", refString, baoutString); 133 } 134 } 135 136 | Popular Tags |