/* 
 * 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.servlet;

import java.io.BufferedReader;
import java.net.ServerSocket;
import java.net.URL;

import junit.framework.TestCase;
import net.noderunner.http.EasyHttpClient;
import net.noderunner.http.HttpException;
import net.noderunner.http.HttpUtil;
import net.noderunner.http.MessageHeader;
import net.noderunner.http.MessageHeaders;

public class ServletServerTest extends TestCase {
	
	HelloServlet servlet = new HelloServlet();

	public void testSimple() throws Exception {
    	ServletServer ss = new ServletServer(servlet);
    	ss.start();
    	URL url = new URL("http://localhost:" + ss.getPort());
    	EasyHttpClient ehc = new EasyHttpClient(url);
    	BufferedReader reader = ehc.doGet();
    	MessageHeaders headers = ehc.getLastResponse().getHeaders();
    	String string = HttpUtil.read(reader);
    	assertEquals("Hello, World!", string.trim());
    	String content = headers.getFieldContent(MessageHeader.FN_SERVER);
    	assertTrue(content, content.startsWith("ServletServer"));
    	
    	byte[] bs = HttpUtil.urlEncode(new String[] { "name", "Bob" });
    	reader = ehc.doPostUrlEncoded(bs);
    	string = HttpUtil.read(reader);
    	assertEquals("Hello, Bob!", string.trim());
    	
    	servlet.fail = true;
    	try {
        	reader = ehc.doGet();
        	fail("expect fail");
    	} catch (HttpException e) {}
    	
    	ehc.close();
    	
    	ss.close();
	}
	
	public void testSocketConstructor() throws Exception {
    	ServletServer ss = new ServletServer(servlet, new ServerSocket(0));
    	ss.start();
    	ss.close();
	}
	
}
