|
@@ -21,9 +21,13 @@ package org.apache.hadoop.io;
|
|
|
import static org.junit.Assert.assertEquals;
|
|
|
import static org.junit.Assert.fail;
|
|
|
|
|
|
+import java.io.File;
|
|
|
import java.io.IOException;
|
|
|
import java.io.InputStream;
|
|
|
import java.io.OutputStream;
|
|
|
+import java.io.RandomAccessFile;
|
|
|
+import java.nio.ByteBuffer;
|
|
|
+import java.nio.channels.FileChannel;
|
|
|
|
|
|
import org.junit.Test;
|
|
|
import org.mockito.Mockito;
|
|
@@ -32,7 +36,8 @@ import org.mockito.Mockito;
|
|
|
* Test cases for IOUtils.java
|
|
|
*/
|
|
|
public class TestIOUtils {
|
|
|
-
|
|
|
+ private static final String TEST_FILE_NAME = "test_file";
|
|
|
+
|
|
|
@Test
|
|
|
public void testCopyBytesShouldCloseStreamsWhenCloseIsTrue() throws Exception {
|
|
|
InputStream inputStream = Mockito.mock(InputStream.class);
|
|
@@ -110,4 +115,41 @@ public class TestIOUtils {
|
|
|
Mockito.verify(outputStream, Mockito.atLeastOnce()).close();
|
|
|
}
|
|
|
|
|
|
+ @Test
|
|
|
+ public void testWriteFully() throws IOException {
|
|
|
+ final int INPUT_BUFFER_LEN = 10000;
|
|
|
+ final int HALFWAY = 1 + (INPUT_BUFFER_LEN / 2);
|
|
|
+ byte[] input = new byte[INPUT_BUFFER_LEN];
|
|
|
+ for (int i = 0; i < input.length; i++) {
|
|
|
+ input[i] = (byte)(i & 0xff);
|
|
|
+ }
|
|
|
+ byte[] output = new byte[input.length];
|
|
|
+
|
|
|
+ try {
|
|
|
+ RandomAccessFile raf = new RandomAccessFile(TEST_FILE_NAME, "rw");
|
|
|
+ FileChannel fc = raf.getChannel();
|
|
|
+ ByteBuffer buf = ByteBuffer.wrap(input);
|
|
|
+ IOUtils.writeFully(fc, buf);
|
|
|
+ raf.seek(0);
|
|
|
+ raf.read(output);
|
|
|
+ for (int i = 0; i < input.length; i++) {
|
|
|
+ assertEquals(input[i], output[i]);
|
|
|
+ }
|
|
|
+ buf.rewind();
|
|
|
+ IOUtils.writeFully(fc, buf, HALFWAY);
|
|
|
+ for (int i = 0; i < HALFWAY; i++) {
|
|
|
+ assertEquals(input[i], output[i]);
|
|
|
+ }
|
|
|
+ raf.seek(0);
|
|
|
+ raf.read(output);
|
|
|
+ for (int i = HALFWAY; i < input.length; i++) {
|
|
|
+ assertEquals(input[i - HALFWAY], output[i]);
|
|
|
+ }
|
|
|
+ } finally {
|
|
|
+ File f = new File(TEST_FILE_NAME);
|
|
|
+ if (f.exists()) {
|
|
|
+ f.delete();
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
}
|