/**
 * LOGICAL-PARADOX.ORG
 * Copyright (C)2004 satoshi akabane(akabane@logical-paradox.org)
 *
 */
package org.logical_paradox.common.io;

import java.io.IOException;
import java.io.EOFException;

import junit.framework.TestCase;

/**
 * MemoryMappedRandomAccessFileのテストクラス
 * 
 * @author satoshi akabane@logical-paradox.org
 * @version 1.0
 */
public class MemoryMappedRandomAccessFileTest extends TestCase {

	/**
	 * Constructor for MemoryMappedRandomAccessFileTest.
	 * @param arg0
	 */
	public MemoryMappedRandomAccessFileTest(String arg0) {
		super(arg0);
	}
	/**
	 * 読み書きのテスト
	 * @throws Exception
	 */
	public void testReadAndWrite() throws Exception {
		MemoryMappedRandomAccessFile file = new MemoryMappedRandomAccessFile();
		
		// 書き込む
		assertEquals(0, file.length());
		file.write(new String("123456789").getBytes());
		assertEquals(9, file.length());

		file.seek(0);
		byte[] b1 = new byte["123456789".length()];
		file.read(b1);
		assertEquals("123456789", new String(b1));
	}
	/**
	 * クローズのテスト
	 * @throws Exception
	 */
	public void testClose() throws Exception {
		MemoryMappedRandomAccessFile file = new MemoryMappedRandomAccessFile();
		file.close();
		
		try {
			file.close();
			fail("一度クローズしたのにまたクローズできた");
		} catch(IOException ioe) {
		}
	}
	/**
	 * シークのテスト
	 * @throws Exception
	 */
	public void testSeek() throws Exception {
		MemoryMappedRandomAccessFile file = new MemoryMappedRandomAccessFile();
		file.write(new String("1234567890").getBytes());

		try {
			file.seek(10);
		} catch(IOException i1) {
			fail("おかしい1");
		}
		try {
			file.seek(11);
			fail("10バイトでseek(11)はエラーになるはず");
		} catch(IOException i2) {}
		try {
			file.seek(-1);
			fail("seek(-1)はエラーのはず");
		} catch(IOException i3) {}
	}
	/**
	 * intの読み書きテスト
	 * @throws Exception
	 */
	public void testReadAndWriteByInt() throws Exception {
		MemoryMappedRandomAccessFile file = new MemoryMappedRandomAccessFile();
		byte[] b2 = new byte[3];
		b2[0] = 100;
		b2[1] = 127;
		b2[2] = 5;
		
		file.write(b2);
		try {
			file.seek(0);
			int i2 = file.readInt();
			fail("EOFExceptionが発生するはず");
		} catch(EOFException eof) {}

		byte[] b = new byte[4];
		b[0] = 100;
		b[1] = 127;
		b[2] = 21;
		b[3] = 21;
		
		file.write(b);

		// 読み込み - 成功の場合
		file.seek(0);
		int i = file.readInt();
	}
}
