/*
 *  @author Ranides Atterwim <ranides@gmail.com>
 *  @copyright Ranides Atterwim
 *  @license WTFPL
 *  @url http://ranides.net/projects/assira
 */
package net.ranides.assira.io;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import net.ranides.assira.text.TextEncoding;
import net.ranides.assira.text.TextOutputStream;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author ranides
 */
public class MultiOutputStreamTest {
	
	@Test
	public void testTee() throws IOException {
		PrintStream prev = System.out;
		
		TextOutputStream stdout = new TextOutputStream();
		System.setOut(new PrintStream(stdout));
		
		OutputStream stream = MultiOutputStream.tee();
		System.out.print("Hello world.");
		assertEquals("Hello world.", stdout.toString());
		assertEquals("Hello world.", stream.toString());
		
		System.setOut(prev);
	}

	@Test
	public void testStream() throws IOException {
		OutputStream out1 = CheckedStream.wrap(new TextOutputStream());
		OutputStream out2 = CheckedStream.wrap(new TextOutputStream());
		OutputStream out3 = new TextOutputStream();
		
		MultiOutputStream ostream = new MultiOutputStream(out1, out2, out3);
		
		ostream.write("Hello".getBytes(TextEncoding.NIO_UTF8));
		ostream.write(' ');
		ostream.write(".world.".getBytes(TextEncoding.NIO_UTF8), 1, 5);
		ostream.flush();
		ostream.close();
		
		try {
			ostream.flush();
			fail("IOException expected");
		} catch(IOException ex) {
			assertEquals(2, ((IOExceptions)ex).getCauseList().size());
		}
		try {
			ostream.close();
			fail("IOException expected");
		} catch(IOException ex) {
			assertEquals(2, ((IOExceptions)ex).getCauseList().size());
		}
		try {
			ostream.write('!');
			fail("IOException expected");
		} catch(IOException ex) {
			assertEquals(2, ((IOExceptions)ex).getCauseList().size());
		}
		try {
			ostream.write(" end".getBytes(TextEncoding.NIO_UTF8));
			fail("IOException expected");
		} catch(IOException ex) {
			assertEquals(2, ((IOExceptions)ex).getCauseList().size());
		}
		try {
			ostream.write("- :)-".getBytes(TextEncoding.NIO_UTF8),1,3);
			fail("IOException expected");
		} catch(IOException ex) {
			assertEquals(2, ((IOExceptions)ex).getCauseList().size());
		}
		
		System.out.println( out1.toString() );
		System.out.println( out2.toString() );
		System.out.println( out3.toString() );
		
		assertTrue(true);
	}

}
