/* 
 * E-XML Library:  For XML, XML-RPC, HTTP, and related.
 * Copyright (C) 2002-2008  Elias Ross
 * 
 * genman@noderunner.net
 * http://noderunner.net/~genman
 * 
 * 1025 NE 73RD ST
 * SEATTLE WA 98115
 * USA
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * $Id$
 */

package net.noderunner.http;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * This class is for unit testing LimitedOutputStream and LimitedInputStream.
 *
 * @author Elias Ross
 * @version 1.0
 */
public class LimitStreamTest
	extends junit.framework.TestCase
{
	public LimitStreamTest(String name) {
		super(name);
	}

	public static void main(String[] args) {
		junit.textui.TestRunner.run(LimitStreamTest.class);
	}

	static final byte stuff[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' };
	static byte dummy[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' };

	public void testLimitSmall()
		throws IOException
	{
		InputStream is = new ByteArrayInputStream(new byte[0]);
		LimitedInputStream lis = new LimitedInputStream(is, 5);
		assertEquals(-1, lis.read());
	}
	
	public void testInLimit()
		throws IOException
	{
		InputStream is = new ByteArrayInputStream(stuff);
		LimitedInputStream lis = new LimitedInputStream(is, 5);
		assertEquals(3, lis.read(dummy, 0, 3));
		assertEquals('d', lis.read());
		assertEquals(1, lis.read(dummy, 0, 2));
		assertEquals(-1, lis.read());
		assertEquals(-1, lis.read(dummy, 0, 3));
		try {
			new LimitedInputStream(null, 0);
			fail("IllegalArgumentException");
		} catch (IllegalArgumentException e) { }
		assertEquals(true, lis.markSupported());
		lis.mark(0);
		lis.reset();
		lis.toString();
		lis.close();
	}

	public void testOutLimit()
		throws IOException
	{
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		LimitedOutputStream los = new LimitedOutputStream(os, 5);
		los.write(stuff, 0, 2);
		los.write('a');
		los.write(stuff, 0, 3);
		los.write('a');
		los.write(stuff, 0, 2);
		byte result[] = os.toByteArray();
		assertEquals("Length ", 5, result.length);
		assertEquals("Length ", 'a', result[2]);
		assertEquals("Length ", 'b', result[4]);
		try {
			new LimitedOutputStream(null, 0);
			fail("IllegalArgumentException");
		} catch (IllegalArgumentException e) { }
		los.flush();
		los.close();
		los.toString();
	}


}
