package cs132.webServer; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.util.regex.Matcher; import java.util.regex.Pattern; import junit.framework.TestCase; public class WebServerTest extends TestCase { public void testGetIndexHtml() throws Throwable { Server server = new Server(); WebServerThread t = new WebServerThread(server); t.start(); try { t.shouldBeRunning(); int p = t.getPort(); String response = getResponseAsString(p, "/index.html"); checkStatusCode(response, "200"); assertTrue("expected text/html", response.indexOf("text/html") > 0); assertTrue("expected \n\n", response.indexOf("\n\n") > 0 || response.indexOf("\r\n\r\n") > 0); assertTrue("missing expected content", response .indexOf("My CMSC 132 Web Server") > 0); t.shouldBeRunning(); String response2 = getResponseAsString(p, "/index.html"); checkStatusCode(response2, "200"); assertTrue("expected text/html", response2.indexOf("text/html") > 0); assertTrue("missing expected content", response2 .indexOf("My CMSC 132 Web Server") > 0); t.shouldBeRunning(); String response3 = getResponseAsString(p, "/quit"); checkStatusCode(response3, "503"); t.shouldBeFinished(); } finally { t.cleanup(); } } private static final Pattern p = Pattern.compile("^HTTP/1.[0-1] ([0-9]*)"); void checkStatusCode(String response, String code) { Matcher m = p.matcher(response); boolean b = m.find(); assertTrue("HTTP response starts with HTTP", b); assertEquals(code, m.group(1)); } String getResponseAsString(int port, String url) throws UnknownHostException, IOException { ByteArrayOutputStream b = new ByteArrayOutputStream(); Socket s = new Socket(InetAddress.getByName("localhost"), port); try { PrintWriter out = new PrintWriter(new OutputStreamWriter(s .getOutputStream())); out.println("GET " + url + " HTTP/1.0"); out.println(); out.flush(); InputStream in = s.getInputStream(); byte buf[] = new byte[1024]; int sz; while ((sz = in.read(buf)) >= 0) { b.write(buf, 0, sz); } } finally { s.close(); } return b.toString(); } }