httpunit-commit Mailing List for httpunit (Page 74)
Brought to you by:
russgold
You can subscribe to this list here.
2000 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
(5) |
Sep
(31) |
Oct
(39) |
Nov
(18) |
Dec
(6) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2001 |
Jan
(8) |
Feb
(5) |
Mar
(8) |
Apr
(25) |
May
(20) |
Jun
(23) |
Jul
(28) |
Aug
(10) |
Sep
(3) |
Oct
(32) |
Nov
(61) |
Dec
(24) |
2002 |
Jan
(50) |
Feb
(34) |
Mar
(35) |
Apr
(3) |
May
(25) |
Jun
(25) |
Jul
(30) |
Aug
(146) |
Sep
(49) |
Oct
(156) |
Nov
(121) |
Dec
(54) |
2003 |
Jan
(12) |
Feb
(79) |
Mar
(88) |
Apr
(26) |
May
(67) |
Jun
(29) |
Jul
(8) |
Aug
(16) |
Sep
(20) |
Oct
(17) |
Nov
|
Dec
(5) |
2004 |
Jan
|
Feb
(40) |
Mar
(30) |
Apr
(5) |
May
|
Jun
(83) |
Jul
(34) |
Aug
(20) |
Sep
(44) |
Oct
(46) |
Nov
|
Dec
(14) |
2005 |
Jan
(4) |
Feb
|
Mar
(5) |
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
(4) |
Oct
|
Nov
|
Dec
(1) |
2006 |
Jan
|
Feb
|
Mar
(26) |
Apr
(8) |
May
(2) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
(5) |
Nov
|
Dec
|
2008 |
Jan
|
Feb
|
Mar
|
Apr
(36) |
May
(38) |
Jun
(1) |
Jul
(1) |
Aug
|
Sep
(4) |
Oct
|
Nov
(18) |
Dec
(4) |
2009 |
Jan
|
Feb
(2) |
Mar
(3) |
Apr
|
May
|
Jun
(2) |
Jul
|
Aug
(35) |
Sep
(1) |
Oct
|
Nov
|
Dec
(1) |
2010 |
Jan
|
Feb
|
Mar
|
Apr
|
May
(3) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
2011 |
Jan
(9) |
Feb
|
Mar
|
Apr
(1) |
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
(1) |
2012 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
(21) |
Oct
(18) |
Nov
(1) |
Dec
|
From: Russell G. <rus...@us...> - 2001-06-19 14:43:52
|
Update of /cvsroot/httpunit/httpunit/examples In directory usw-pr-cvs1:/tmp/cvs-serv672/examples Modified Files: NearWords.java Log Message: Minor documentation / example fixes Index: NearWords.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/examples/NearWords.java,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -u -r1.1.1.1 -r1.2 --- NearWords.java 2000/06/12 13:09:26 1.1.1.1 +++ NearWords.java 2001/06/19 14:43:49 1.2 @@ -52,6 +52,7 @@ WebForm lookupForm = getFormWithName( "dict" ); WebRequest request = lookupForm.getRequest(); request.setParameter( "va", pattern ); + request.setParameter( "book", "Dictionary" ); response = conversation.getResponse( request ); return getOptionsFromResponse(); |
From: Russell G. <rus...@us...> - 2001-06-18 21:02:25
|
Update of /cvsroot/httpunit/httpunit In directory usw-pr-cvs1:/tmp/cvs-serv23141 Modified Files: build.xml Log Message: Updated version ID Index: build.xml =================================================================== RCS file: /cvsroot/httpunit/httpunit/build.xml,v retrieving revision 1.27 retrieving revision 1.28 diff -u -r1.27 -r1.28 --- build.xml 2001/05/17 00:35:31 1.27 +++ build.xml 2001/06/18 21:02:23 1.28 @@ -5,8 +5,8 @@ <project name="httpunit" default="jar" basedir="."> <property name="name" value="httpunit" /> <property name="Name" value="HttpUnit" /> - <property name="version" value="1.2.4" /> - <property name="zip_version" value="1_2_4" /> + <property name="version" value="1.2.5" /> + <property name="zip_version" value="1_2_5" /> <property name="src.dir" value="src" /> <property name="tstsrc.dir" value="test" /> |
From: Russell G. <rus...@us...> - 2001-06-18 20:21:33
|
Update of /cvsroot/httpunit/httpunit/test/com/meterware/servletunit In directory usw-pr-cvs1:/tmp/cvs-serv14775/test/com/meterware/servletunit Modified Files: ConfigTest.java NavigationTest.java StatefulTest.java StatelessTest.java Log Message: Added tests and documentation for ServletUnit Index: ConfigTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/servletunit/ConfigTest.java,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- ConfigTest.java 2000/12/13 21:56:03 1.1 +++ ConfigTest.java 2001/06/18 20:21:30 1.2 @@ -2,7 +2,7 @@ /******************************************************************************************************************** * $Id$ * -* Copyright (c) 2000, Russell Gold +* Copyright (c) 2000-2001, Russell Gold * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation @@ -59,7 +59,7 @@ WebResponse response = wc.getResponse( "http://localhost/" + resourceName ); assertNotNull( "No response received", response ); assertEquals( "content type", "text/plain", response.getContentType() ); - assertEquals( "servlet name is " + ConfigServlet.class.getName(), response.toString() ); + assertEquals( "servlet name is " + ConfigServlet.class.getName(), response.getText() ); } Index: NavigationTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/servletunit/NavigationTest.java,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- NavigationTest.java 2000/12/13 21:56:03 1.1 +++ NavigationTest.java 2001/06/18 20:21:30 1.2 @@ -2,7 +2,7 @@ /******************************************************************************************************************** * $Id$ * -* Copyright (c) 2000, Russell Gold +* Copyright (c) 2000-2001, Russell Gold * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation @@ -58,7 +58,7 @@ WebClient wc = sr.newClient(); WebResponse response = wc.getResponse( "http://localhost/origin" ); assertNotNull( "No response received", response ); - assertEquals( "requested resource", TargetServlet.RESPONSE_TEXT, response.toString() ); + assertEquals( "requested resource", TargetServlet.RESPONSE_TEXT, response.getText() ); assertEquals( "Returned cookie count", 0, response.getNewCookieNames().length ); } Index: StatefulTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/servletunit/StatefulTest.java,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- StatefulTest.java 2000/11/21 20:44:59 1.1 +++ StatefulTest.java 2001/06/18 20:21:30 1.2 @@ -2,7 +2,7 @@ /******************************************************************************************************************** * $Id$ * -* Copyright (c) 2000, Russell Gold +* Copyright (c) 2000-2001, Russell Gold * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation @@ -56,11 +56,11 @@ ServletRunner sr = new ServletRunner(); sr.registerServlet( resourceName, StatefulServlet.class.getName() ); - WebRequest request = new PostMethodWebRequest( "http://localhost/" + resourceName ); + WebRequest request = new GetMethodWebRequest( "http://localhost/" + resourceName ); WebResponse response = sr.getResponse( request ); assertNotNull( "No response received", response ); assertEquals( "content type", "text/plain", response.getContentType() ); - assertEquals( "requested resource", "No session found", response.toString() ); + assertEquals( "requested resource", "No session found", response.getText() ); assertEquals( "Returned cookie count", 0, response.getNewCookieNames().length ); } @@ -71,7 +71,7 @@ ServletRunner sr = new ServletRunner(); sr.registerServlet( resourceName, StatefulServlet.class.getName() ); - WebRequest request = new GetMethodWebRequest( "http://localhost/" + resourceName ); + WebRequest request = new PostMethodWebRequest( "http://localhost/" + resourceName ); request.setParameter( "color", "red" ); WebResponse response = sr.getResponse( request ); assertNotNull( "No response received", response ); @@ -86,43 +86,120 @@ sr.registerServlet( resourceName, StatefulServlet.class.getName() ); WebClient wc = sr.newClient(); - WebRequest request = new GetMethodWebRequest( "http://localhost/" + resourceName ); + WebRequest request = new PostMethodWebRequest( "http://localhost/" + resourceName ); request.setParameter( "color", "red" ); WebResponse response = wc.getResponse( request ); assertNotNull( "No response received", response ); assertEquals( "content type", "text/plain", response.getContentType() ); - assertEquals( "requested resource", "You selected red", response.toString() ); + assertEquals( "requested resource", "You selected red", response.getText() ); - request = new PostMethodWebRequest( "http://localhost/" + resourceName ); + request = new GetMethodWebRequest( "http://localhost/" + resourceName ); response = wc.getResponse( request ); assertNotNull( "No response received", response ); assertEquals( "content type", "text/plain", response.getContentType() ); - assertEquals( "requested resource", "You posted red", response.toString() ); + assertEquals( "requested resource", "You posted red", response.getText() ); assertEquals( "Returned cookie count", 0, response.getNewCookieNames().length ); } + public void testInvocationContext() throws Exception { + final String resourceName = "something/interesting"; + + ServletRunner sr = new ServletRunner(); + sr.registerServlet( resourceName, StatefulServlet.class.getName() ); + ServletUnitClient suc = sr.newClient(); + + WebRequest request = new PostMethodWebRequest( "http://localhost/" + resourceName ); + request.setParameter( "color", "red" ); + + InvocationContext ic = suc.newInvocation( request ); + StatefulServlet ss = (StatefulServlet) ic.getServlet(); + assertNull( "A session already exists", ss.getColor( ic.getRequest() ) ); + + ss.setColor( ic.getRequest(), "blue" ); + assertEquals( "Color in session", "blue", ss.getColor( ic.getRequest() ) ); + } + + + public void testInvocationCompletion() throws Exception { + final String resourceName = "something/interesting"; + + ServletRunner sr = new ServletRunner(); + sr.registerServlet( resourceName, StatefulServlet.class.getName() ); + ServletUnitClient suc = sr.newClient(); + + WebRequest request = new PostMethodWebRequest( "http://localhost/" + resourceName ); + request.setParameter( "color", "red" ); + + InvocationContext ic = suc.newInvocation( request ); + StatefulServlet ss = (StatefulServlet) ic.getServlet(); + ss.setColor( ic.getRequest(), "blue" ); + ss.writeSelectMessage( "blue", ic.getResponse().getWriter() ); + + WebResponse response = ic.getServletResponse(); + assertEquals( "requested resource", "You selected blue", response.getText() ); + assertEquals( "Returned cookie count", 1, response.getNewCookieNames().length ); + } + + + public void testInvocationContextUpdate() throws Exception { + final String resourceName = "something/interesting"; + + ServletRunner sr = new ServletRunner(); + sr.registerServlet( resourceName, StatefulServlet.class.getName() ); + ServletUnitClient suc = sr.newClient(); + + WebRequest request = new PostMethodWebRequest( "http://localhost/" + resourceName ); + request.setParameter( "color", "red" ); + + InvocationContext ic = suc.newInvocation( request ); + StatefulServlet ss = (StatefulServlet) ic.getServlet(); + ss.setColor( ic.getRequest(), "blue" ); + suc.getResponse( ic ); + + WebResponse response = suc.getResponse( "http://localhost/" + resourceName ); + assertNotNull( "No response received", response ); + assertEquals( "content type", "text/plain", response.getContentType() ); + assertEquals( "requested resource", "You posted blue", response.getText() ); + assertEquals( "Returned cookie count", 0, response.getNewCookieNames().length ); + } + + static class StatefulServlet extends HttpServlet { static String RESPONSE_TEXT = "the desired content\r\n"; - protected void doGet( HttpServletRequest req, HttpServletResponse resp ) throws ServletException,IOException { + protected void doPost( HttpServletRequest req, HttpServletResponse resp ) throws ServletException,IOException { resp.setContentType( "text/plain" ); - PrintWriter pw = resp.getWriter(); - pw.print( "You selected " + req.getParameter( "color" ) ); - req.getSession().putValue( "color", req.getParameter( "color" ) ); - pw.close(); + writeSelectMessage( req.getParameter( "color" ), resp.getWriter() ); + setColor( req, req.getParameter( "color" ) ); } - - protected void doPost( HttpServletRequest req, HttpServletResponse resp ) throws ServletException,IOException { + + protected void doGet( HttpServletRequest req, HttpServletResponse resp ) throws ServletException,IOException { resp.setContentType( "text/plain" ); - HttpSession session = req.getSession( /* create */ false ); PrintWriter pw = resp.getWriter(); - if (session == null) { + String color = getColor( req ); + if (color == null) { pw.print( "No session found" ); } else { - pw.print( "You posted " + session.getValue( "color" ) ); + pw.print( "You posted " + color ); } pw.close(); + } + + protected void writeSelectMessage( String color, PrintWriter pw ) throws IOException { + pw.print( "You selected " + color ); + pw.close(); + } + + protected void setColor( HttpServletRequest req, String color ) throws ServletException { + req.getSession().setAttribute( "color", color ); + } + + + protected String getColor( HttpServletRequest req ) throws ServletException { + HttpSession session = req.getSession( /* create */ false ); + if (session == null) return null; + return (String) session.getAttribute( "color" ); } } Index: StatelessTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/servletunit/StatelessTest.java,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- StatelessTest.java 2000/11/21 20:44:59 1.1 +++ StatelessTest.java 2001/06/18 20:21:30 1.2 @@ -2,7 +2,7 @@ /******************************************************************************************************************** * $Id$ * -* Copyright (c) 2000, Russell Gold +* Copyright (c) 2000-2001, Russell Gold * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation @@ -74,7 +74,7 @@ WebResponse response = sr.getResponse( request ); assertNotNull( "No response received", response ); assertEquals( "content type", "text/html", response.getContentType() ); - assertEquals( "requested resource", SimpleGetServlet.RESPONSE_TEXT, response.toString() ); + assertEquals( "requested resource", SimpleGetServlet.RESPONSE_TEXT, response.getText() ); } @@ -89,7 +89,7 @@ WebResponse response = sr.getResponse( request ); assertNotNull( "No response received", response ); assertEquals( "content type", "text/plain", response.getContentType() ); - assertEquals( "requested resource", "You selected red", response.toString() ); + assertEquals( "requested resource", "You selected red", response.getText() ); } @@ -103,7 +103,7 @@ WebResponse response = sr.getResponse( request ); assertNotNull( "No response received", response ); assertEquals( "content type", "text/plain", response.getContentType() ); - assertEquals( "requested resource", "You selected red", response.toString() ); + assertEquals( "requested resource", "You selected red", response.getText() ); } public void testSimplePost() throws Exception { @@ -117,7 +117,7 @@ WebResponse response = sr.getResponse( request ); assertNotNull( "No response received", response ); assertEquals( "content type", "text/plain", response.getContentType() ); - assertEquals( "requested resource", "You posted red", response.toString() ); + assertEquals( "requested resource", "You posted red", response.getText() ); } |
From: Russell G. <rus...@us...> - 2001-06-18 20:21:33
|
Update of /cvsroot/httpunit/httpunit/src/com/meterware/servletunit In directory usw-pr-cvs1:/tmp/cvs-serv14775/src/com/meterware/servletunit Modified Files: ServletRunner.java ServletUnitServletContext.java Log Message: Added tests and documentation for ServletUnit Index: ServletRunner.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/servletunit/ServletRunner.java,v retrieving revision 1.4 retrieving revision 1.5 diff -u -r1.4 -r1.5 --- ServletRunner.java 2001/06/06 13:25:04 1.4 +++ ServletRunner.java 2001/06/18 20:21:30 1.5 @@ -68,7 +68,7 @@ /** * Creates and returns a new web client that communicates with this servlet runner. **/ - public WebClient newClient() { + public ServletUnitClient newClient() { return new ServletUnitClient( this ); } Index: ServletUnitServletContext.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/servletunit/ServletUnitServletContext.java,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- ServletUnitServletContext.java 2000/12/13 21:56:03 1.1 +++ ServletUnitServletContext.java 2001/06/18 20:21:30 1.2 @@ -2,7 +2,7 @@ /******************************************************************************************************************** * $Id$ * -* Copyright (c) 2000, Russell Gold +* Copyright (c) 2000-2001, Russell Gold * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation @@ -175,8 +175,7 @@ * Writes the specified message to a servlet log file, usually an event log. * The name and type of the servlet log file is specific to the servlet container. **/ - public void log( String message ) { - System.out.println( "log: " + message ); // XXX change this to use something testable + public void log( String message ) { // XXX change this to use something testable } |
From: Russell G. <rus...@us...> - 2001-06-18 20:21:33
|
Update of /cvsroot/httpunit/httpunit In directory usw-pr-cvs1:/tmp/cvs-serv14775 Modified Files: index.html Log Message: Added tests and documentation for ServletUnit Index: index.html =================================================================== RCS file: /cvsroot/httpunit/httpunit/index.html,v retrieving revision 1.15 retrieving revision 1.16 diff -u -r1.15 -r1.16 --- index.html 2001/04/02 19:07:35 1.15 +++ index.html 2001/06/18 20:21:30 1.16 @@ -15,6 +15,10 @@ form submission, basic <A HREF="ftp://ftp.isi.edu/in-notes/rfc2617.txt">http authentication</A>, cookies and automatic page redirection, and allows Java test code to examine returned pages as text, an XML DOM, or containers of forms, tables, and links.</P> +<P> +A companion framework, <A HREF="doc/servletunit-intro.html">ServletUnit</A> is included in the download. +</P> + <h2>What is it?</h2> <blockquote> |
From: Russell G. <rus...@us...> - 2001-06-18 20:21:33
|
Update of /cvsroot/httpunit/httpunit/doc In directory usw-pr-cvs1:/tmp/cvs-serv14775/doc Modified Files: faq.html release_notes.txt todo.txt Added Files: servletunit-intro.html sslfaq.html Log Message: Added tests and documentation for ServletUnit --- NEW FILE --- <HTML> <HEAD> <TITLE>ServletUnit Overview</TITLE> </HEAD> <BODY> <H1>ServletUnit</H1> <P>As a testing tool, HttpUnit is primarily designed for "black-box" testing of web sites. In many cases that may be all you need; however, if you are developing complex servlets, you may wish to test smaller pieces of your code. Sometimes you can isolate them into simple tests using only JUnit. In other cases, you will want to test in a servlet environment. At this point you have two basic approaches available. You can test in a real servlet container, using a tool such as <A HREF="http://jakarta.apache.org/commons/cactus">Apache Cactus</A>, which has you deploy your tests into the container along with your servlets. Or you can use a simulated servlet container. ServletUnit takes the latter approach.</P> <P>To test a servlet in ServletUnit, you first instantiate a <CODE>ServletRunner</CODE> (the simulated container), and register your servlet: <PRE><CODE> ServletRunner sr = new ServletRunner(); sr.registerServlet( "myServlet", StatefulServlet.class.getName() ); </CODE></PRE> Note that for complex tests, you can register multiple servlets in a single <CODE>ServletRunner</CODE>. You are now ready to begin. You need a <CODE>ServletUnitClient</CODE>, which performs much the same function as HttpUnit's <CODE>WebConversation</CODE> - in fact, they both extend the base class <CODE>WebClient</CODE>, so you can use it the same way, except of course that <CODE>ServletUnitClient</CODE> ignores the host portion of URLs in requests passed to it and goes directly to its <CODE>ServletRunner</CODE>. This means that you can invoke the servlet and handle its response in the same way you have been accustomed to in HttpUnit: <PRE><CODE> ServletUnitClient sc = sr.newClient(); WebRequest request = new PostMethodWebRequest( "http://test.meterware.com/myServlet" ); request.setParameter( "color", "red" ); WebResponse response = sc.getResponse( request ); assertNotNull( "No response received", response ); assertEquals( "content type", "text/plain", response.getContentType() ); assertEquals( "requested resource", "You selected red", response.getText() ); </CODE></PRE> Of course, this is still black-box testing. To really take advantage of the power of ServletUnit, you can handle your request in steps. To do this, instead of asking the client for the final response, you ask it for an invocation context: <PRE><CODE> ServletUnitClient sc = sr.newClient(); WebRequest request = new PostMethodWebRequest( "http://test.meterware.com/myServlet" ); request.setParameter( "color", "red" ); InvocationContext ic = sc.newInvocation( request ); </CODE></PRE> This invocation context provides access to the selected servlet, which has been initialized for you with the appropriate session information, as well as the request and response objects which the servlet will process. Now you can call methods on the servlet, on the servlet session, or on the request and response objects. For example, given the following servlet definition: <PRE><CODE> public class StatefulServlet extends HttpServlet { protected void doPost( HttpServletRequest req, HttpServletResponse resp ) throws ServletException,IOException { resp.setContentType( "text/plain" ); writeSelectMessage( req.getParameter( "color" ), resp.getWriter() ); setColor( req, req.getParameter( "color" ) ); } void writeSelectMessage( String color, PrintWriter pw ) throws IOException { pw.print( "You selected " + color ); pw.close(); } void setColor( HttpServletRequest req, String color ) throws ServletException { req.getSession().setAttribute( "color", color ); } } </CODE></PRE> you might want to test the individual methods one at a time. The following code obtains the servlet and casts it to get access to its package-level methods (the tests should be in the same package as the servlet to do this). It then invokes the setColor method to ensure that it is creating and updating the session correctly. <PRE><CODE> StatefulServlet ss = (StatefulServlet) ic.getServlet(); assertNull( "A session already exists", ic.getRequest().getSession( false ) ); ss.setColor( ic.getRequest(), "blue" ); assertNotNull( "Session was not created", ic.getRequest().getSession( false ) ); assertEquals( "Color in session", "blue", ic.getRequest().getSession().getAttribute( "color" ) ); </CODE></PRE> You can test the response from the servlet as well, if you invoke the code which creates it: <PRE><CODE> StatefulServlet ss = (StatefulServlet) ic.getServlet(); ss.writeSelectMessage( "blue", ic.getResponse().getWriter() ); WebResponse response = ic.getServletResponse(); assertEquals( "requested resource", "You selected blue", response.getText() ); assertEquals( "Returned cookie count", 1, response.getNewCookieNames().length ); </CODE></PRE> Note that the response returned from <CODE>getServletResponse</CODE> is the actual one returned by the servlet, without any processing by the client. For example, if the request contains a bad status or a forward request, the client might do some additional processing, which is not done at this time. Of course, since the response extends <CODE>WebResponse</CODE>, all of the normal HTML parsing methods are available to examine it. Finally, if you are writing a test which depends on the maintenance of state across servlet invocations, you will want to reinvolve the <CODE>ServletUnitClient</CODE>, giving it a chance to process the response, including updating its own list of cookies: <PRE><CODE> WebResponse response sc.getResponse( ic ); // pass the already processed InvocationContext response = sc.getResponse( "http://test.meterware.com/ReadColorFromSession" ); assertNotNull( "No response received", response ); assertEquals( "content type", "text/plain", response.getContentType() ); assertEquals( "requested resource", "You posted blue", response.getText() ); assertEquals( "Returned cookie count", 0, response.getNewCookieNames().length ); </CODE></PRE> This allows any subsequent request through the same client object to take advantage of the session state established by the just completed request, just as is possible with HttpUnit. </BODY> </HTML> --- NEW FILE --- <!doctype html public "-//w3c//dtd html 4.0 transitional//en"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="GENERATOR" content="Mozilla/4.72 [en] (X11; U; Linux 2.2.14-5.0 i686) [Netscape]"> </head> <body bgcolor="#FFFFFF"> <center> <h1> <font size=+3>Using SSL with httpunit FAQ</font></h1></center> <h2> Where can I get information on SSL?</h2> <a href="http://java.sun.com/security/ssl/API_users_guide.html">from Sun on SSL</a> <br><a href="http://www.thawte.com/developers/contents.html">from Thawte, a certificate vendor</a> <br> <a href="http://java.sun.com/products/jsse/">from the JSSE part of Sun's site</a> <h2> What are some tools for creating and modifying certificates?</h2> <a href="http://www.openssl.org/docs/apps/openssl.html">openssl</a> which is <a href="http://www.pseudonym.org/ssl/wwwj-index.html">also described at pseudonym.org</a><br> <a href="http://java.sun.com/products/jdk/1.2/docs/tooldocs/solaris/keytool.html">keytool</a> for java <h2> How do I create a certificate?</h2> Create a self-signed cert via openssl, given an existing key and openssl config file: <p> openssl req -new -out output.pem -key my_key.pem -days 9999 -x509 -config openssl.cnf <p>There's also a way to do this with the java "keytool" application. <br> <h2> How can I <a NAME="make my certificate trusted"></a>make my certificate trusted by the JVM?</h2> <p><br>If you purchased your SSL certificate from Verisign or Thawte, then it should be automatically trusted by the "trust file" within the JVM (Sun seems to ship JVMs with certs from these two suppliers). If you created your own certificate, you'll need to <a href="#import my existing certificate into the trust file for">import that cert into cacerts</a>. <h2> How can I <a NAME="import my existing certificate into the trust file for"></a>import my existing certificate into the "trust file" for a JVM?</h2> <p><br>1. Find the trusted file "cacerts" in your JRE, e.g. <br> find /java_install -name "cacerts" <p>2. Copy that file to a backup <br> cp cacerts cacerts.bak <p>3. Install your certificate into the trust file (note: the file cacerts ships from Sun with password "changeit") <br> keytool -import -alias <mycompany> -file mycert.pem -keystore $JAVA_HOME/jre/lib/security/cacerts <p>4. Verify that your cert was imported: <br> keytool -list -keystore $JAVA_HOME/jre/lib/security/cacerts <h2> How can I use SSL in httpunit?</h2> 1. You need an SSL certificate intalled into the web server to be tested. That <a href="#make my certificate trusted">certificate must be trusted</a> by the JVM of the test rig (httpunit). That certificate must have, as its Common Name, the exact domain name of the web server you want to secure (e.g. "www.foo.com" or "secure.foo.com". I have not had luck with certs like *.foo.com.) <p>2. You must enable SSL support (i.e., support for URLs that start with "https") in your test rig's JVM. Some environments like Weblogic offer native SSL support, which is fast compared to pure java. For Weblogic, set the property weblogic.security.ssl.enable=true in the config file and just start using URLs like "https://myhost". Also, there is at least one <a href="#free SSL implementation">free SSL implementation in java</a>. <br> <h2> How can I use a <a NAME="free SSL implementation"></a>free SSL implementation?</h2> There is a free <a href="http://java.sun.com/products/jsse/">SSL implementation available in pure java from Sun</a> , although it is relatively slow, especially in its creation of the random key to start an SSL connection (about 3 seconds on a 600Mz PIII). To use this implementation, download the JSSE package from the Sun URL above, then: <p>1. Add the three key jars to your JVM's "ext" (extentions) directory; e.g. <br> cp jcert.jar jnet.jar jsse.jar $JAVA_HOME/jre/lib/ext/ <p>2. After the jars are in place, you must modify the file "java.security" to allow usage of the providers found within the jars. Find the file <br> find $JAVA_HOME -name "java.security" <p>3. Add the following line to the file java.security: <br> security.provider.2=com.sun.net.ssl.internal.ssl.Provider <p>Then start using URLs like "https://myhost" within the test rig. The HTTPS protocol will automatically cause new provider classes within the extention jars to be employed for a java.net.URL class and its related connections. Note that you should NOT add these jars to the CLASSPATH. Javax jars are accessed by the JVM by their inclusion in the magic "ext" folder. <br> <h2> How do I solve a javax.net.ssl.SSLException: untrusted server cert chain?</h2> <p><br>See how to <a href="#make my certificate trusted">make your certificate trusted</a>. <br> <p> <hr WIDTH="100%"> <p>Compiled 12 Mar 2001 by larry hamel. Please post corrections/comments to the <a href="mailto:htt...@li...">httpunit discussion list</a>. </body> </html> Index: faq.html =================================================================== RCS file: /cvsroot/httpunit/httpunit/doc/faq.html,v retrieving revision 1.7 retrieving revision 1.8 diff -u -r1.7 -r1.8 --- faq.html 2001/05/04 21:07:07 1.7 +++ faq.html 2001/06/18 20:21:30 1.8 @@ -9,7 +9,7 @@ <LI><A HREF="#org.xml.sax">What is the org.xml.sax package?</A></LI> <LI><A HREF="#meterware.com">Where is meterware.com?</A></LI> <LI><A HREF="#javascript">How do I use HttpUnit to test my pages that use JavaScript?</A></LI> -<LI><A HREF="#https">Does HttpUnit support https?</A></LI> +<LI><A HREF="sslfaq.html">Does HttpUnit support https?</A></LI> <LI><A HREF="#proxy">Can I use HttpUnit through a proxy server?</A></LI> <LI><A HREF="#charset">Why isn't HttpUnit handling my non-English pages?</A></LI> <LI><A HREF="#utf8">HttpUnit fails with an IllegalArgumentException: sun.io.CharToByteUTF-8, what do I do?</A></LI> @@ -38,11 +38,6 @@ Unfortunately, you can't. HttpUnit does not support any dialect of JavaScript. I have been shown a JavaScript library and it is possible that I will one day add JavaScript support, but since I use it very little in my own development, and since it looks like a lot of work, it is not a major priority for me. If you feel ambitious enough to add JavaScript support yourself, I would be happy to accept submissions. - -<A NAME="https"><H2>Does HttpUnit support https?</H2></A> -Yes, as long as you have the <A HREF="http://java.sun.com/products/jsse/">JSSE extension</A> installed. -Download this extension and install -its three jars in your classpath. <A NAME="proxy"><H2>Can I use HttpUnit through a proxy server?</H2></A> Yes. HttpUnit uses java.net.HttpURLConnection, so the Index: release_notes.txt =================================================================== RCS file: /cvsroot/httpunit/httpunit/doc/release_notes.txt,v retrieving revision 1.37 retrieving revision 1.38 diff -u -r1.37 -r1.38 --- release_notes.txt 2001/06/13 16:38:19 1.37 +++ release_notes.txt 2001/06/18 20:21:30 1.38 @@ -9,59 +9,43 @@ Limitations: HttpUnit does not support JavaScript - Revision History: + +18-Jun-2001 1.2.5 Acknowledgements: Thanks to Rolf Schmidiger for corrected behavior when failing to find a site Thanks to Tom Watkins, Deepa Dihr, Marcos Tarruella for their implementation of PutMethodWebRequest + Thanks to Larry Hamel for writing the SSL FAQ -11-Jun-01 Additions: - 1. Added getInputStream method in WebResponse to support non-text responses. - 2. Matching of text in web pages is now controlled by the HttpUnitOption property + 1. selectFile() now can infer file content type for the most common file extensions: + text, txt, gif, jpg, jpeg, png, html, htm and zip. + 2. A new version of selectFile allows explicit specification of file content type + which will override any inferred type. + 3. <button> tags are now recognized as submit buttons if their type is "submit" + or not specified. + 4. Reading the character set from a <meta> tag is now supported. + 5. Added PutMethodWebRequest + 6. PostMethodWebRequest now has a constructor which allows its contents to be + taken from an InputSource, like PutMethodWebRequest + 7. Added ServletUnitClient and InvocationContext to servletunit to + permit more granular testing of servlets (still not well documented) + 8. Added getInputStream method in WebResponse to support non-text responses. + 9. Matching of text in web pages is now controlled by the HttpUnitOption property 'matchesIgnoreCase'. The default behavior is as before - matches are not case sensitive - - 6-Jun-01 -Additions: - 1. Added ServletUnitClient and InvocationContext to servletunit to - permit more granular testing of servlets - 4-Jun-01 -Additions: - 1. Added PutMethodWebRequest - 2. PostMethodWebRequest now has a constructor which allows its contents to be - taken from an InputSource, like PutMethodWebRequest - -31-May-01 Problems corrected: 1. Now throws HttpNotFoundException rather than NullPointerException when unable to connect to a web site 2. I/O exceptions when accessing a site are now thrown, rather than being turned into RuntimeException. - -22-May-01 -Additions: - 1. Reading the character set from a <meta> tag is now supported. - -21-May-01 -Additions: - 1. selectFile now infers file content for zip extension - 2. <button> tags are now recognized as submit buttons if their type is "submit" - or not specified. - -16-May-01 -Additions: - 1. selectFile now can infer file content type for the most common file extensions: - text, txt, gif, jpg, jpeg, png, html, and htm. - 2. A new version of selectFile allows explicit specification of file content type - which will override any inferred type. - Configuration changes: 1. The build.xml file has been changed to use a specified directory of dependant jars rather than the system classpath. This requires at least ant 1.3. It is no longer necessary to specify the classpath parameter when running the unit tests. + 5-May-01 1.2.4 Acknowledgements: Index: todo.txt =================================================================== RCS file: /cvsroot/httpunit/httpunit/doc/todo.txt,v retrieving revision 1.12 retrieving revision 1.13 diff -u -r1.12 -r1.13 --- todo.txt 2001/06/13 16:38:20 1.12 +++ todo.txt 2001/06/18 20:21:30 1.13 @@ -1,4 +1,5 @@ o Support <META HTTP_EQUIV=REFRESH tags> +o Support optional tags which hide their contents (as in IFRAME, OBJECT, etc.) o Support IFRAME tag o Support reset button detection o Support _new frame tag |
From: Russell G. <rus...@us...> - 2001-06-13 16:38:23
|
Update of /cvsroot/httpunit/httpunit/test/com/meterware/httpunit In directory usw-pr-cvs1:/tmp/cvs-serv19578/test/com/meterware/httpunit Modified Files: WebFrameTest.java Log Message: Added control for case-sensitivity of HTML matching Index: WebFrameTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/httpunit/WebFrameTest.java,v retrieving revision 1.5 retrieving revision 1.6 diff -u -r1.5 -r1.6 --- WebFrameTest.java 2001/04/03 16:49:08 1.5 +++ WebFrameTest.java 2001/06/13 16:38:20 1.6 @@ -163,15 +163,22 @@ } - private WebResponse getFrameWithURL( WebConversation wc, String urlString ) { + private String getNameOfFrameWithURL( WebConversation wc, String urlString ) { String[] names = wc.getFrameNames(); for (int i = 0; i < names.length; i++) { WebResponse candidate = wc.getFrameContents( names[i] ); if (candidate.getURL().toExternalForm().indexOf( urlString ) >= 0) { - return candidate; + return names[i]; } } return null; + } + + + private WebResponse getFrameWithURL( WebConversation wc, String urlString ) { + String name = getNameOfFrameWithURL( wc, urlString ); + if (name == null) return null; + return wc.getFrameContents( name ); } |
From: Russell G. <rus...@us...> - 2001-06-13 16:38:22
|
Update of /cvsroot/httpunit/httpunit/src/com/meterware/servletunit In directory usw-pr-cvs1:/tmp/cvs-serv19578/src/com/meterware/servletunit Modified Files: ServletUnitWebResponse.java Log Message: Added control for case-sensitivity of HTML matching Index: ServletUnitWebResponse.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/servletunit/ServletUnitWebResponse.java,v retrieving revision 1.3 retrieving revision 1.4 diff -u -r1.3 -r1.4 --- ServletUnitWebResponse.java 2001/06/11 21:21:09 1.3 +++ ServletUnitWebResponse.java 2001/06/13 16:38:20 1.4 @@ -20,8 +20,10 @@ * *******************************************************************************************************************/ +import java.io.ByteArrayInputStream; import java.io.BufferedReader; import java.io.FileNotFoundException; +import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; @@ -81,6 +83,14 @@ } + /** + * Returns an input stream for reading the contents of this reply. + **/ + public InputStream getInputStream() throws IOException { + return new ByteArrayInputStream( getText().getBytes() ); + } + + public String toString() { return "[ _response = " + _response + "]"; } |
From: Russell G. <rus...@us...> - 2001-06-13 16:38:22
|
Update of /cvsroot/httpunit/httpunit/src/com/meterware/httpunit In directory usw-pr-cvs1:/tmp/cvs-serv19578/src/com/meterware/httpunit Modified Files: HttpUnitOptions.java ParsedHTML.java WebResponse.java Log Message: Added control for case-sensitivity of HTML matching Index: HttpUnitOptions.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/HttpUnitOptions.java,v retrieving revision 1.5 retrieving revision 1.6 diff -u -r1.5 -r1.6 --- HttpUnitOptions.java 2000/12/26 14:40:17 1.5 +++ HttpUnitOptions.java 2001/06/13 16:38:20 1.6 @@ -2,7 +2,7 @@ /******************************************************************************************************************** * $Id$ * -* Copyright (c) 2000, Russell Gold +* Copyright (c) 2000-2001, Russell Gold * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation @@ -106,6 +106,24 @@ /** + * If true, text matches in methods such as {@link HTMLFragment#getLinkWith} are + * case insensitive. The default is true (matches ignore case). + **/ + public static boolean getMatchesIgnoreCase() { + return _matchesIgnoreCase; + } + + + /** + * If true, text matches in methods such as {@link HTMLFragment#getLinkWith} are + * case insensitive. The default is true (matches ignore case). + **/ + public static void setMatchesIgnoreCase( boolean ignoreCase ) { + _matchesIgnoreCase = ignoreCase; + } + + + /** * Returns true if HTTP headers are to be dumped to system output. **/ public static boolean isLoggingHttpHeaders() { @@ -152,6 +170,8 @@ private static boolean _imagesTreatedAsAltText; private static boolean _loggingHttpHeaders; + + private static boolean _matchesIgnoreCase = true; private static int _redirectDelay; Index: ParsedHTML.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/ParsedHTML.java,v retrieving revision 1.15 retrieving revision 1.16 diff -u -r1.15 -r1.16 --- ParsedHTML.java 2001/04/18 03:18:35 1.15 +++ ParsedHTML.java 2001/06/13 16:38:20 1.16 @@ -103,15 +103,14 @@ public WebLink getLinkWith( String text ) { WebLink[] links = getLinks(); for (int i = 0; i < links.length; i++) { - String linkText = NodeUtils.asText( links[i].getDOMSubtree().getChildNodes() ).toUpperCase(); - if (linkText.indexOf( text.toUpperCase() ) >= 0) { - return links[i]; - } + String linkText = NodeUtils.asText( links[i].getDOMSubtree().getChildNodes() ); + if (contains( linkText, text )) return links[i]; } return null; } + /** * Returns the first link which contains an image with the specified text as its 'alt' attribute. **/ @@ -121,8 +120,11 @@ NodeList nl = ((Element) links[i].getDOMSubtree()).getElementsByTagName( "img" ); for (int j = 0; j < nl.getLength(); j++) { NamedNodeMap nnm = nl.item(j).getAttributes(); - if (text.equalsIgnoreCase( getValue( nnm.getNamedItem( "alt" ) ) )) { + if (text.equals( getValue( nnm.getNamedItem( "alt" ) ) )) { return links[i]; + } else if (HttpUnitOptions.getMatchesIgnoreCase() && + text.equalsIgnoreCase( getValue( nnm.getNamedItem( "alt" ) ) )) { + return links[i]; } } } @@ -149,7 +151,7 @@ public boolean isTrue( WebTable table ) { table.purgeEmptyCells(); return table.getRowCount() > 0 && - table.getCellAsText(0,0).equalsIgnoreCase( text ); + matches( table.getCellAsText(0,0), text ); } } ); } @@ -160,13 +162,12 @@ * in its first non-blank row and non-blank column. Will recurse into any nested tables, as needed. * @return the selected table, or null if none is found **/ - public WebTable getTableStartingWithPrefix( String text ) { - final String prefix = text.toUpperCase(); + public WebTable getTableStartingWithPrefix( final String text ) { return getTableSatisfyingPredicate( getTables(), new TablePredicate() { public boolean isTrue( WebTable table ) { table.purgeEmptyCells(); return table.getRowCount() > 0 && - table.getCellAsText(0,0).toUpperCase().startsWith( prefix ); + hasPrefix( table.getCellAsText(0,0).toUpperCase(), text ); } } ); } @@ -180,7 +181,7 @@ public WebTable getTableWithSummary( final String summary ) { return getTableSatisfyingPredicate( getTables(), new TablePredicate() { public boolean isTrue( WebTable table ) { - return table.getSummary().equalsIgnoreCase( summary ); + return matches( table.getSummary(), summary ); } } ); } @@ -194,7 +195,7 @@ public WebTable getTableWithID( final String ID ) { return getTableSatisfyingPredicate( getTables(), new TablePredicate() { public boolean isTrue( WebTable table ) { - return table.getID().equalsIgnoreCase( ID ); + return matches( table.getID(), ID ); } } ); } @@ -263,6 +264,33 @@ private String _baseTarget; private String _characterSet; + + + private boolean contains( String string, String substring ) { + if (HttpUnitOptions.getMatchesIgnoreCase()) { + return string.toUpperCase().indexOf( substring.toUpperCase() ) >= 0; + } else { + return string.indexOf( substring ) >= 0; + } + } + + + private boolean hasPrefix( String string, String prefix ) { + if (HttpUnitOptions.getMatchesIgnoreCase()) { + return string.toUpperCase().startsWith( prefix.toUpperCase() ); + } else { + return string.startsWith( prefix ); + } + } + + + private boolean matches( String string1, String string2 ) { + if (HttpUnitOptions.getMatchesIgnoreCase()) { + return string1.equalsIgnoreCase( string2 ); + } else { + return string1.equals( string2 ); + } + } private String getValue( Node node ) { Index: WebResponse.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/WebResponse.java,v retrieving revision 1.35 retrieving revision 1.36 diff -u -r1.35 -r1.36 --- WebResponse.java 2001/06/11 21:21:09 1.35 +++ WebResponse.java 2001/06/13 16:38:20 1.36 @@ -426,17 +426,22 @@ private WebFrame[] getFrames() throws SAXException { if (_frames == null) { - NodeList nl = NodeUtils.getElementsByTagName( getReceivedPage().getDOM(), "frame" ); Vector list = new Vector(); - for (int i = 0; i < nl.getLength(); i++) { - Node child = nl.item(i); - list.addElement( new WebFrame( getReceivedPage().getBaseURL(), child ) ); - } + addFrameTags( list, "frame" ); _frames = new WebFrame[ list.size() ]; list.copyInto( _frames ); } return _frames; + } + + + private void addFrameTags( Vector list, String frameTagName ) throws SAXException { + NodeList nl = NodeUtils.getElementsByTagName( getReceivedPage().getDOM(), frameTagName ); + for (int i = 0; i < nl.getLength(); i++) { + Node child = nl.item(i); + list.addElement( new WebFrame( getReceivedPage().getBaseURL(), child ) ); + } } |
From: Russell G. <rus...@us...> - 2001-06-13 16:38:22
|
Update of /cvsroot/httpunit/httpunit/doc In directory usw-pr-cvs1:/tmp/cvs-serv19578/doc Modified Files: release_notes.txt todo.txt Log Message: Added control for case-sensitivity of HTML matching Index: release_notes.txt =================================================================== RCS file: /cvsroot/httpunit/httpunit/doc/release_notes.txt,v retrieving revision 1.36 retrieving revision 1.37 diff -u -r1.36 -r1.37 --- release_notes.txt 2001/06/11 21:21:09 1.36 +++ release_notes.txt 2001/06/13 16:38:19 1.37 @@ -19,6 +19,8 @@ 11-Jun-01 Additions: 1. Added getInputStream method in WebResponse to support non-text responses. + 2. Matching of text in web pages is now controlled by the HttpUnitOption property + 'matchesIgnoreCase'. The default behavior is as before - matches are not case sensitive 6-Jun-01 Additions: Index: todo.txt =================================================================== RCS file: /cvsroot/httpunit/httpunit/doc/todo.txt,v retrieving revision 1.11 retrieving revision 1.12 diff -u -r1.11 -r1.12 --- todo.txt 2001/06/06 13:25:33 1.11 +++ todo.txt 2001/06/13 16:38:20 1.12 @@ -1,5 +1,5 @@ -o Support non-text web responses o Support <META HTTP_EQUIV=REFRESH tags> +o Support IFRAME tag o Support reset button detection o Support _new frame tag o Send parameters in proper (HTML-file) order |
From: Russell G. <rus...@us...> - 2001-06-11 21:21:12
|
Update of /cvsroot/httpunit/httpunit/test/com/meterware/httpunit In directory usw-pr-cvs1:/tmp/cvs-serv18011/test/com/meterware/httpunit Modified Files: FileUploadTest.java HttpUnitTest.java MessageBodyRequestTest.java PseudoServer.java PseudoServerTest.java PseudoServlet.java WebFormTest.java WebLinkTest.java WebPageTest.java WebResource.java Added Files: HttpRequestStream.java UnknownMethodException.java Log Message: Added support for binary downloads ***** Error reading new file[Errno 2] No such file or directory: 'HttpRequestStream.java' ***** Error reading new file[Errno 2] No such file or directory: 'UnknownMethodException.java' Index: FileUploadTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/httpunit/FileUploadTest.java,v retrieving revision 1.5 retrieving revision 1.6 diff -u -r1.5 -r1.6 --- FileUploadTest.java 2001/05/16 21:05:30 1.5 +++ FileUploadTest.java 2001/06/11 21:21:09 1.6 @@ -209,10 +209,10 @@ } -class StringDataSource implements DataSource { - StringDataSource( String contentType, String contents ) { +class ByteArrayDataSource implements DataSource { + ByteArrayDataSource( String contentType, byte[] body ) { _contentType = contentType; - _inputStream = new ByteArrayInputStream( contents.getBytes() ); + _inputStream = new ByteArrayInputStream( body ); } @@ -243,12 +243,11 @@ class MimeEcho extends PseudoServlet { - public WebResource getPostResponse( Dictionary parameters, Dictionary headers ) { + public WebResource getPostResponse() { StringBuffer sb = new StringBuffer(); try { - String contentType = (String) headers.get( "CONTENT-TYPE" ); - String contents = (String) headers.get( PseudoServlet.CONTENTS ); - DataSource ds = new StringDataSource( contentType, contents ); + String contentType = getHeader( "Content-Type" ); + DataSource ds = new ByteArrayDataSource( contentType, getBody() ); MimeMultipart mm = new MimeMultipart( ds ); int numParts = mm.getCount(); for (int i = 0; i < numParts; i++) { Index: HttpUnitTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/httpunit/HttpUnitTest.java,v retrieving revision 1.11 retrieving revision 1.12 diff -u -r1.11 -r1.12 --- HttpUnitTest.java 2001/04/03 16:49:08 1.11 +++ HttpUnitTest.java 2001/06/11 21:21:09 1.12 @@ -136,6 +136,41 @@ } + + + protected void assertEquals( String comment, byte[] expected, byte[] actual ) + { + if (!equals( expected, actual )) + { + fail( comment + " expected:\n" + toString( expected ) + ", but was:\n" + toString( actual ) ); + } + } + + + private boolean equals( byte[] first, byte[] second ) + { + if (first.length != second.length) return false; + for (int i = 0; i < first.length; i++) + { + if (first[i] != second[i]) return false; + } + return true; + } + + + private String toString( byte[] message ) + { + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < message.length; i++) + { + if (i != 0 && (i % 4) == 0) sb.append( ' ' ); + if (message[i] >= 0 && message[i] < 16) sb.append( '0' ); + sb.append( Integer.toHexString( 0xff & (int) message[i] ) ); + } + return sb.toString(); + } + + //---------------------------------------- private members ----------------------------------------- private String _hostPath; Index: MessageBodyRequestTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/httpunit/MessageBodyRequestTest.java,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- MessageBodyRequestTest.java 2001/06/06 13:25:33 1.1 +++ MessageBodyRequestTest.java 2001/06/11 21:21:09 1.2 @@ -89,12 +89,51 @@ } + public void testDownloadRequest() throws Exception { + defineResource( "ReportData", new BodyEcho() ); + byte[] binaryData = new byte[] { 0x01, 0x05, 0x0d, 0x0a, 0x02 }; + + InputStream source = new ByteArrayInputStream( binaryData ); + + WebConversation wc = new WebConversation(); + WebRequest wr = new PutMethodWebRequest( getHostPath() + "/ReportData", source, "application/random" ); + WebResponse response = wc.getResponse( wr ); + + byte[] download = getDownload( response ); + assertEquals( "Body response", binaryData, download ); + } + + + private byte[] getDownload( WebResponse response ) throws IOException { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + InputStream inputStream = response.getInputStream(); + + byte[] buffer = new byte[8 * 1024]; + int count = 0; + do { + outputStream.write( buffer, 0, count ); + count = inputStream.read( buffer, 0, buffer.length ); + } while (count != -1); + + inputStream.close(); + return outputStream.toByteArray(); + } + + } class BodyEcho extends PseudoServlet { - public WebResource getResponse( String method, Dictionary parameters, Dictionary headers ) { - return new WebResource( "\n" + method + "\n" + (String) headers.get( PseudoServlet.CONTENTS ), (String) headers.get( "CONTENT-TYPE" ) ); + /** + * Returns a resource object as a result of a get request. + **/ + public WebResource getResponse( String method ) { + String contentType = getHeader( "Content-type" ); + if (contentType.startsWith( "text" )) { + return new WebResource( "\n" + method + "\n" + new String( getBody() ), contentType ); + } else { + return new WebResource( getBody(), contentType ); + } } } Index: PseudoServer.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/httpunit/PseudoServer.java,v retrieving revision 1.13 retrieving revision 1.14 diff -u -r1.13 -r1.14 --- PseudoServer.java 2001/06/04 20:45:33 1.13 +++ PseudoServer.java 2001/06/11 21:21:09 1.14 @@ -97,6 +97,14 @@ /** + * Defines the contents of an expected resource. + **/ + public void setResource( String name, byte[] value, String contentType ) { + _resources.put( asResourceName( name ), new WebResource( value, contentType ) ); + } + + + /** * Defines a resource which will result in an error message. **/ public void setErrorResource( String name, int errorCode, String errorMessage ) { @@ -146,11 +154,6 @@ private boolean _active = true; - /** The encoding used for HTTP headers. **/ - final private static String HEADER_ENCODING = "us-ascii"; - - final private static String CRLF = "\r\n"; - private String asResourceName( String rawName ) { if (rawName.startsWith( "/" )) { @@ -163,207 +166,162 @@ private void handleConnection() throws IOException { Socket socket = getServerSocket().accept(); - - BufferedReader br = new BufferedReader( new InputStreamReader( socket.getInputStream(), HEADER_ENCODING ) ); - PrintWriter pw = new PrintWriter( new OutputStreamWriter( socket.getOutputStream(), HEADER_ENCODING ) ); - socket.setSoTimeout( 1000 ); socket.setTcpNoDelay( true ); - String commandLine = br.readLine(); // get the first line only - StringTokenizer st = new StringTokenizer( commandLine ); - String command = st.nextToken(); - String uri = st.nextToken(); - String protocol = st.nextToken(); + HttpRequestStream request = new HttpRequestStream( socket.getInputStream() ); + HttpResponseStream response = new HttpResponseStream( socket.getOutputStream() ); - if (!command.equals( "GET" ) && !command.equals( "POST" ) && !command.equals( "PUT" )) { - sendResponse( pw, HttpURLConnection.HTTP_BAD_METHOD, "unsupported method: " + command ); - } else { - try { - WebResource resource = getResource( command, uri, br ); - if (resource == null) { - sendResponse( pw, HttpURLConnection.HTTP_NOT_FOUND, "unable to find " + uri ); - } else if (resource.getResponseCode() != HttpURLConnection.HTTP_OK) { - sendResponse( pw, resource.getResponseCode(), resource.getContents() ); - sendLine( pw, "" ); - pw.flush(); - } else { - sendResponse( pw, HttpURLConnection.HTTP_OK, "OK" ); - sendLine( pw, "Content-type: " + resource.getContentType() + resource.getCharacterSetParameter() ); - String[] headers = resource.getHeaders(); - for (int i = 0; i < headers.length; i++) { - sendLine( pw, headers[i] ); - } - sendLine( pw, "" ); - pw.flush(); - pw = new PrintWriter( new OutputStreamWriter( socket.getOutputStream(), resource.getCharacterSet() ) ); - sendText( pw, resource.getContents() ); + try { + WebResource resource = getResource( request ); + if (resource == null) { + response.setResponse( HttpURLConnection.HTTP_NOT_FOUND, "unable to find " + request.getURI() ); + } else if (resource.getResponseCode() != HttpURLConnection.HTTP_OK) { + response.setResponse( resource.getResponseCode(), resource.getResponseText() ); + } else { + response.addHeader( "Content-type: " + resource.getContentType() + resource.getCharacterSetParameter() ); + String[] headers = resource.getHeaders(); + for (int i = 0; i < headers.length; i++) { + response.addHeader( headers[i] ); } - } catch (IOException e) { - e.fillInStackTrace(); - pw.close(); - socket.close(); - throw e; - } catch (Throwable t) { - System.out.println( "Internal error: " + t ); - t.printStackTrace(); - sendResponse( pw, HttpURLConnection.HTTP_INTERNAL_ERROR, t.toString() ); + response.write( resource.getContents() ); } + } catch (UnknownMethodException e) { + response.setResponse( HttpURLConnection.HTTP_BAD_METHOD, "unsupported method: " + e.getMethod() ); + } catch (IOException e) { + e.fillInStackTrace(); + throw e; + } catch (Throwable t) { + t.printStackTrace(); + response.setResponse( HttpURLConnection.HTTP_INTERNAL_ERROR, t.toString() ); + } finally { + response.close(); + socket.close(); } - - pw.close(); - socket.close(); } + + private WebResource getResource( HttpRequestStream request ) throws IOException { + Object resource = _resources.get( request.getURI() ); - private WebResource getResource( String command, String uri, BufferedReader br ) throws IOException { - Object resource = _resources.get( uri ); - if (command.equals( "GET" ) && resource instanceof WebResource) { + if (request.getCommand().equals( "GET" ) && resource instanceof WebResource) { return (WebResource) resource; } else if (resource instanceof PseudoServlet) { - Dictionary requestData = readRequest( br ); - return ((PseudoServlet) resource).getResponse( command, getParameters( (String) requestData.get( PseudoServlet.CONTENTS ) ), requestData ); + return getResource( (PseudoServlet) resource, request ); } else { return null; } } - private Dictionary readRequest( BufferedReader br ) throws IOException { - Hashtable headers = new Hashtable(); - String lastHeader = null; - - String header = br.readLine(); - while (header.length() > 0) { - if (header.charAt(0) <= ' ') { - if (lastHeader == null) continue; - headers.put( lastHeader, headers.get( lastHeader ) + header.trim() ); - } else { - lastHeader = header.substring( 0, header.indexOf(':') ).toUpperCase(); - headers.put( lastHeader, header.substring( header.indexOf(':')+1 ).trim() ); - } - header = br.readLine(); - } - readContent( headers, br ); - return headers; + private WebResource getResource( PseudoServlet servlet, HttpRequestStream request ) { + servlet.init( request ); + return servlet.getResponse( request.getCommand() ); } - private void readContent( Hashtable headers, BufferedReader br ) throws IOException { - if (headers.get( "CONTENT-LENGTH" ) == null) return; - try { - int contentLength = Integer.parseInt( (String) headers.get( "CONTENT-LENGTH" ) ); - char[] content = new char[ contentLength ]; - br.read( content ); - headers.put( PseudoServlet.CONTENTS, new String( content ) ); - } catch (NumberFormatException e) { + private ServerSocket getServerSocket() throws IOException { + synchronized (this) { + if (_serverSocket == null) _serverSocket = new ServerSocket(0); + _serverSocket.setSoTimeout( 1000 ); } + return _serverSocket; } - private void printContent( char[] content ) { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < content.length; i++) { - if (i == 0) { - } else if ((i % 40) == 0) { - sb.append( '\n' ); - } else if (i % 4 == 0) { - sb.append( ' ' ); - } - sb.append( Integer.toHexString( content[i] ) ); - } - System.out.println( sb.toString() ); - } - - - private Dictionary getParameters( String content ) throws IOException { - Hashtable parameters = new Hashtable(); - if (content == null || content.trim().length() == 0) return parameters; - - StringTokenizer st = new StringTokenizer( content, "&=" ); - while (st.hasMoreTokens()) { - String name = st.nextToken(); - if (st.hasMoreTokens()) { - addParameter( parameters, decode( name ), decode( st.nextToken() ) ); - } - } - return parameters; + private ServerSocket _serverSocket; + +} + + + + +class HttpResponseStream { + + final private static String CRLF = "\r\n"; + + + void close() throws IOException { + flushHeaders(); + _pw.close(); } - private void addParameter( Hashtable parameters, String name, String value ) { - String[] oldValues = (String[]) parameters.get( name ); - if (oldValues == null) { - parameters.put( name, new String[] { value } ); - } else { - String[] values = new String[ oldValues.length+1 ]; - System.arraycopy( oldValues, 0, values, 0, oldValues.length ); - values[ oldValues.length ] = value; - parameters.put( name, values ); + HttpResponseStream( OutputStream stream ) { + _stream = stream; + try { + setCharacterSet( "us-ascii" ); + } catch (UnsupportedEncodingException e) { + _pw = new PrintWriter( new OutputStreamWriter( _stream ) ); } } - private String decode( String byteString ) { - StringBuffer sb = new StringBuffer(); - char[] chars = byteString.toCharArray(); - char[] hexNum = { '0', '0', '0' }; - - int i = 0; - while (i < chars.length) { - if (chars[i] == '+') { - i++; - sb.append( ' ' ); - } else if (chars[i] == '%') { - i++; - hexNum[1] = chars[i++]; - hexNum[2] = chars[i++]; - sb.append( (char) Integer.parseInt( new String( hexNum ), 16 ) ); - } else { - sb.append( chars[i++] ); - } - } - return sb.toString(); + void setResponse( int responseCode, String responseText ) { + _responseCode = responseCode; + _responseText = responseText; } - private void sendResponse( PrintWriter pw, int responseCode, String responseText ) throws IOException { - sendLine( pw, "HTTP/1.0 " + responseCode + ' ' + responseText ); + void addHeader( String header ) { + _headers.addElement( header ); } - private void sendLine( PrintWriter pw, String text ) throws IOException { - sendText( pw, text ); - sendText( pw, CRLF ); + void write( String contents, String charset ) throws IOException { + flushHeaders(); + setCharacterSet( charset ); + sendText( contents ); } - private void sendText( PrintWriter pw, String text ) throws IOException { - pw.write( text ); + void write( byte[] contents ) throws IOException { + flushHeaders(); + _stream.write( contents, 0, contents.length ); } + private void setCharacterSet( String characterSet ) throws UnsupportedEncodingException { + if (_pw != null) _pw.flush(); + _pw = new PrintWriter( new OutputStreamWriter( _stream, characterSet ) ); + } + - private String toUnicode( String string ) { - StringBuffer sb = new StringBuffer( ); - char[] chars = string.toCharArray(); - for (int i = 0; i < chars.length; i++) { - sb.append( "\\u" ); - sb.append( Integer.toHexString( chars[i] ) ); + private void flushHeaders() throws IOException { + if (!_headersWritten) { + sendResponse( _responseCode, _responseText ); + for (Enumeration e = _headers.elements(); e.hasMoreElements();) { + sendLine( (String) e.nextElement() ); + } + sendText( CRLF ); + _headersWritten = true; + _pw.flush(); } - return sb.toString(); } - - private ServerSocket getServerSocket() throws IOException { - synchronized (this) { - if (_serverSocket == null) _serverSocket = new ServerSocket(0); - _serverSocket.setSoTimeout( 1000 ); - } - return _serverSocket; + + private void sendResponse( int responseCode, String responseText ) throws IOException { + sendLine( "HTTP/1.0 " + responseCode + ' ' + responseText ); } - private ServerSocket _serverSocket; + private void sendLine( String text ) throws IOException { + sendText( text ); + sendText( CRLF ); + } + + + private void sendText( String text ) throws IOException { + _pw.write( text ); + } + + + private OutputStream _stream; + private PrintWriter _pw; + + private Vector _headers = new Vector(); + private int _responseCode = HttpURLConnection.HTTP_OK; + private String _responseText = "OK"; + private boolean _headersWritten; } Index: PseudoServerTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/httpunit/PseudoServerTest.java,v retrieving revision 1.12 retrieving revision 1.13 diff -u -r1.12 -r1.13 --- PseudoServerTest.java 2001/06/04 20:45:33 1.12 +++ PseudoServerTest.java 2001/06/11 21:21:09 1.13 @@ -212,8 +212,8 @@ try { ps.setResource( resourceName, new PseudoServlet() { - public WebResource getPostResponse( Dictionary parameters, Dictionary headers ) { - return new WebResource( prefix + ((String[]) parameters.get( "name" ))[0], "text/plain" ); + public WebResource getPostResponse() { + return new WebResource( prefix + getParameter( "name" )[0], "text/plain" ); } } ); @@ -246,8 +246,8 @@ try { ps.setResource( resourceName, new PseudoServlet() { - public WebResource getGetResponse( Dictionary parameters, Dictionary headers ) { - String referer = (String) headers.get( "REFERER" ); + public WebResource getGetResponse() { + String referer = getHeader( "Referer" ); return new WebResource( referer == null ? "null" : referer, "text/plain" ); } } ); Index: PseudoServlet.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/httpunit/PseudoServlet.java,v retrieving revision 1.4 retrieving revision 1.5 diff -u -r1.4 -r1.5 --- PseudoServlet.java 2001/06/04 20:45:33 1.4 +++ PseudoServlet.java 2001/06/11 21:21:09 1.5 @@ -21,6 +21,8 @@ *******************************************************************************************************************/ import java.util.Dictionary; +import java.io.Reader; + /** * A basic simulated servlet for testing the HttpUnit library. **/ @@ -33,17 +35,14 @@ /** * Returns a resource object as a result of a get request. - * @param parameters a mapping of parameter names to arrays of value string. - * @param headers a mapping of header names to header contents. Also contains a special 'header' named CONTENTS - * which is the raw bytes of the request contents stored in a string. **/ - public WebResource getResponse( String methodType, Dictionary parameters, Dictionary headers ) { + public WebResource getResponse( String methodType ) { if (methodType.equalsIgnoreCase( "GET" )) { - return getGetResponse( parameters, headers ); + return getGetResponse(); } else if (methodType.equalsIgnoreCase( "PUT" )) { - return getPutResponse( parameters, headers ); + return getPutResponse(); } else if (methodType.equalsIgnoreCase( "POST" )) { - return getPostResponse( parameters, headers ); + return getPostResponse(); } else { throw new RuntimeException( methodType + " not implemented" ); } @@ -52,35 +51,64 @@ /** * Returns a resource object as a result of a get request. - * @param parameters a mapping of parameter names to arrays of value string. - * @param headers a mapping of header names to header contents. Also contains a special 'header' named CONTENTS - * which is the raw bytes of the request contents stored in a string. **/ - public WebResource getGetResponse( Dictionary parameters, Dictionary headers ) { + public WebResource getGetResponse() { throw new RuntimeException( "get not implemented" ); } /* * Returns a resource object as a result of a post request. - * @param parameters a mapping of parameter names to arrays of value string. - * @param headers a mapping of header names to header contents. Also contains a special 'header' named CONTENTS - * which is the raw bytes of the request contents stored in a string. **/ - public WebResource getPostResponse( Dictionary parameters, Dictionary headers ) { + public WebResource getPostResponse() { throw new RuntimeException( "post not implemented" ); } /* * Returns a resource object as a result of a put request. - * @param parameters a mapping of parameter names to arrays of value string. - * @param headers a mapping of header names to header contents. Also contains a special 'header' named CONTENTS - * which is the raw bytes of the request contents stored in a string. **/ - public WebResource getPutResponse( Dictionary parameters, Dictionary headers ) { + public WebResource getPutResponse() { throw new RuntimeException( "put not implemented" ); } + + + void init( HttpRequestStream requestStream ) { + _requestStream = requestStream; + } + + + /** + * Returns the header with the specified name. If no such header exists, will return null. + **/ + protected String getHeader( String name ) { + return _requestStream.getHeader( name ); + } + + + /** + * Returns the values for the parameter with the specified name. If no values exist + * will return null. + **/ + protected String[] getParameter( String name ) { + return _requestStream.getParameter( name ); + } + + + /** + * Returns a reader for the body of the request. + **/ + protected Reader getReader() { + return _requestStream.getReader(); + } + + + protected byte[] getBody() { + return _requestStream.getBody(); + } + + + private HttpRequestStream _requestStream; } Index: WebFormTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/httpunit/WebFormTest.java,v retrieving revision 1.10 retrieving revision 1.11 diff -u -r1.10 -r1.11 --- WebFormTest.java 2001/04/18 03:18:35 1.10 +++ WebFormTest.java 2001/06/11 21:21:09 1.11 @@ -147,7 +147,8 @@ } - public void testNullTextValues() throws Exception { + // XXX turn this back on when Tidy handles it properly + public void notestNullTextValues() throws Exception { defineWebPage( "Default", "<form method=POST action = \"/servlet/Login\">" + "<Input name=\"secret\" type=\"hidden\" value=>" + "<br><Input name=typeless value=>" + Index: WebLinkTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/httpunit/WebLinkTest.java,v retrieving revision 1.7 retrieving revision 1.8 diff -u -r1.7 -r1.8 --- WebLinkTest.java 2000/10/06 14:52:53 1.7 +++ WebLinkTest.java 2001/06/11 21:21:09 1.8 @@ -156,7 +156,7 @@ WebRequest request = link.getRequest(); assertEquals( "Destination for link", getHostPath() + "/alternate/Target.html", request.getURL().toExternalForm() ); WebResponse nextPage = wc.getResponse( request ); - assert( "Did not find the target", nextPage.toString().indexOf( "Found" ) >= 0 ); + assert( "Did not find the target", nextPage.getText().indexOf( "Found" ) >= 0 ); } Index: WebPageTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/httpunit/WebPageTest.java,v retrieving revision 1.10 retrieving revision 1.11 diff -u -r1.10 -r1.11 --- WebPageTest.java 2001/05/22 22:18:55 1.10 +++ WebPageTest.java 2001/06/11 21:21:09 1.11 @@ -181,9 +181,9 @@ "<input type=text name=name><input type=submit></form></body></html>" ); setResourceCharSet( "HebrewForm.html", "iso-8859-8", true ); defineResource( "SayHello", new PseudoServlet() { - public WebResource getPostResponse( Dictionary parameters, Dictionary headers ) { + public WebResource getPostResponse() { try { - String name = ((String[]) parameters.get( "name" ))[0]; + String name = getParameter( "name" )[0]; WebResource result = new WebResource( "<html><body><table><tr><td>Hello, " + new String( name.getBytes( "iso-8859-1" ), "iso-8859-8" ) + "</td></tr></table></body></html>" ); Index: WebResource.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/httpunit/WebResource.java,v retrieving revision 1.3 retrieving revision 1.4 diff -u -r1.3 -r1.4 --- WebResource.java 2001/03/20 23:35:43 1.3 +++ WebResource.java 2001/06/11 21:21:09 1.4 @@ -34,7 +34,7 @@ final static String DEFAULT_CONTENT_TYPE = "text/html"; - final static String DEFAULT_CHARACTER_SET = "us-ascii"; + final static String DEFAULT_CHARACTER_SET = "iso-8859-1"; WebResource( String contents ) { this( contents, DEFAULT_CONTENT_TYPE ); @@ -47,11 +47,24 @@ WebResource( int responseCode, String responseText ) { - this( responseText, DEFAULT_CONTENT_TYPE, responseCode ); + this( "", DEFAULT_CONTENT_TYPE, responseCode ); + _responseText = responseText; } WebResource( String contents, String contentType, int responseCode ) { + _string = contents; + _contentType = contentType; + _responseCode = responseCode; + } + + + WebResource( byte[] contents, String contentType ) { + this( contents, contentType, HttpURLConnection.HTTP_OK ); + } + + + WebResource( byte[] contents, String contentType, int responseCode ) { _contents = contents; _contentType = contentType; _responseCode = responseCode; @@ -80,8 +93,12 @@ } - String getContents() { - return _contents; + byte[] getContents() throws UnsupportedEncodingException { + if (_string != null) { + return _string.getBytes( getCharacterSet() ); + } else { + return _contents; + } } @@ -108,16 +125,31 @@ return _responseCode; } + String getResponseText() { + return _responseText; + } + public String toString() { return "WebResource [code=" + _responseCode + "; type = " + _contentType - + "; charset = " + _characterSet + "]\n" + _contents; + + "; charset = " + _characterSet + "]\n" + getContentsAsString(); } + private String getContentsAsString() { + if (_string != null) { + return _string; + } else { + return "<< hex bytes >>"; + } + } + + + private byte[] _contents; + private String _string; private int _responseCode; private boolean _sendCharacterSet; - private String _contents; + private String _responseText = ""; private String _contentType; private String _characterSet = DEFAULT_CHARACTER_SET; private Vector _headers = new Vector(); |
From: Russell G. <rus...@us...> - 2001-06-11 21:21:12
|
Update of /cvsroot/httpunit/httpunit/src/com/meterware/servletunit In directory usw-pr-cvs1:/tmp/cvs-serv18011/src/com/meterware/servletunit Modified Files: ServletUnitWebResponse.java Log Message: Added support for binary downloads Index: ServletUnitWebResponse.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/servletunit/ServletUnitWebResponse.java,v retrieving revision 1.2 retrieving revision 1.3 diff -u -r1.2 -r1.3 --- ServletUnitWebResponse.java 2001/06/06 13:25:04 1.2 +++ ServletUnitWebResponse.java 2001/06/11 21:21:09 1.3 @@ -79,6 +79,11 @@ public String getText() { return _response.getContents(); } + + + public String toString() { + return "[ _response = " + _response + "]"; + } //-------------------------------------------- private members ------------------------------------------------ |
From: Russell G. <rus...@us...> - 2001-06-11 21:21:12
|
Update of /cvsroot/httpunit/httpunit/src/com/meterware/httpunit In directory usw-pr-cvs1:/tmp/cvs-serv18011/src/com/meterware/httpunit Modified Files: HttpWebResponse.java WebResponse.java Log Message: Added support for binary downloads Index: HttpWebResponse.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/HttpWebResponse.java,v retrieving revision 1.9 retrieving revision 1.10 diff -u -r1.9 -r1.10 --- HttpWebResponse.java 2001/05/31 16:44:15 1.9 +++ HttpWebResponse.java 2001/06/11 21:21:09 1.10 @@ -44,8 +44,11 @@ **/ HttpWebResponse( String target, URL url, URLConnection connection ) throws IOException { super( target, url ); + _connection = connection; readHeaders( connection ); - if (_responseCode == HttpURLConnection.HTTP_OK) loadResponseText( url, connection ); + if (_responseCode == HttpURLConnection.HTTP_OK && getContentType().startsWith( "text" )) { + loadResponseText( connection ); + } } @@ -69,10 +72,27 @@ * Returns the text of the response (excluding headers) as a string. Use this method in preference to 'toString' * which may be used to represent internal state of this object. **/ - public String getText() { + public String getText() throws IOException { + if (_responseText == null) loadResponseText( _connection ); return _responseText; } + + /** + * Returns an input stream for reading the contents of this reply. + **/ + public InputStream getInputStream() throws IOException { + if (_responseText != null) { + return new ByteArrayInputStream( _responseText.getBytes() ); + } else { + return new BufferedInputStream( _connection.getInputStream() ); + } + } + + + public String toString() { + return "[headers=" + _headers + "; ??]"; + } //-------------------------------------------- private members ------------------------------------------------ @@ -83,11 +103,13 @@ private int _responseCode = HttpURLConnection.HTTP_OK; + private URLConnection _connection; + private String _responseText; private Hashtable _headers = new Hashtable(); - private void loadResponseText( URL url, URLConnection connection ) throws IOException { + private void loadResponseText( URLConnection connection ) throws IOException { StringBuffer sb = new StringBuffer(); try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Index: WebResponse.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/WebResponse.java,v retrieving revision 1.34 retrieving revision 1.35 diff -u -r1.34 -r1.35 --- WebResponse.java 2001/06/06 13:25:04 1.34 +++ WebResponse.java 2001/06/11 21:21:09 1.35 @@ -20,6 +20,8 @@ * *******************************************************************************************************************/ +import java.io.ByteArrayInputStream; +import java.io.InputStream; import java.io.IOException; import java.io.StringReader; @@ -148,8 +150,15 @@ * which may be used to represent internal state of this object. **/ abstract - public String getText(); + public String getText() throws IOException; + + /** + * Returns an input stream for reading the contents of this reply. + **/ + abstract + public InputStream getInputStream() throws IOException; + /** * Returns the names of the frames found in the page in the order in which they appear. @@ -296,10 +305,8 @@ //---------------------------------------- Object methods -------------------------------------------- - - public String toString() { - return getText(); - } + abstract + public String toString(); //----------------------------------------- protected members ----------------------------------------------- @@ -435,8 +442,12 @@ private ReceivedPage getReceivedPage() throws SAXException { if (_page == null) { - if (!isHTML()) throw new NotHTMLException( getContentType() ); - _page = new ReceivedPage( _url, _target, getText(), getCharacterSet() ); + try { + if (!isHTML()) throw new NotHTMLException( getContentType() ); + _page = new ReceivedPage( _url, _target, getText(), getCharacterSet() ); + } catch (IOException e) { + throw new SAXException( e ); + } } return _page; } @@ -457,6 +468,8 @@ Method getDocumentMethod = parserClass.getMethod( "getDocument", null ); doc = (Document)getDocumentMethod.invoke( parser, null ); + } catch (IOException e) { + throw new SAXException( e ); } catch (InvocationTargetException ex) { Throwable tex = ex.getTargetException(); if (tex instanceof SAXException) { @@ -519,6 +532,19 @@ **/ public String getText() { return _responseText; + } + + + /** + * Returns an input stream for reading the contents of this reply. + **/ + public InputStream getInputStream() { + return new ByteArrayInputStream( _responseText.getBytes() ); + } + + + public String toString() { + return "DefaultWebResponse [" + _responseText + "]"; } |
From: Russell G. <rus...@us...> - 2001-06-11 21:21:12
|
Update of /cvsroot/httpunit/httpunit/doc In directory usw-pr-cvs1:/tmp/cvs-serv18011/doc Modified Files: release_notes.txt Log Message: Added support for binary downloads Index: release_notes.txt =================================================================== RCS file: /cvsroot/httpunit/httpunit/doc/release_notes.txt,v retrieving revision 1.35 retrieving revision 1.36 diff -u -r1.35 -r1.36 --- release_notes.txt 2001/06/06 13:25:33 1.35 +++ release_notes.txt 2001/06/11 21:21:09 1.36 @@ -16,6 +16,10 @@ Thanks to Tom Watkins, Deepa Dihr, Marcos Tarruella for their implementation of PutMethodWebRequest +11-Jun-01 +Additions: + 1. Added getInputStream method in WebResponse to support non-text responses. + 6-Jun-01 Additions: 1. Added ServletUnitClient and InvocationContext to servletunit to |
Update of /cvsroot/httpunit/httpunit/src/com/meterware/httpunit In directory usw-pr-cvs1:/tmp/cvs-serv2105/src/com/meterware/httpunit Modified Files: MessageBody.java MessageBodyWebRequest.java MimeEncodedMessageBody.java PostMethodWebRequest.java PutMethodWebRequest.java Log Message: input stream requests now contain content type Index: MessageBody.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/MessageBody.java,v retrieving revision 1.2 retrieving revision 1.3 diff -u -r1.2 -r1.3 --- MessageBody.java 2001/06/04 20:45:33 1.2 +++ MessageBody.java 2001/06/06 13:25:33 1.3 @@ -38,10 +38,20 @@ /** - * Updates the headers for this request as needed. + * Returns the content type of this message body. For text messages, this + * should include the character set. **/ abstract - void updateHeaders( URLConnection connection ) throws IOException; + String getContentType(); + + + /** + * Updates the headers for this request as needed. + * @deprecated use getContentType + **/ + final + void updateHeaders( URLConnection connection ) throws IOException { + } /** Index: MessageBodyWebRequest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/MessageBodyWebRequest.java,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- MessageBodyWebRequest.java 2001/06/04 20:45:33 1.1 +++ MessageBodyWebRequest.java 2001/06/06 13:25:33 1.2 @@ -57,7 +57,7 @@ connection.setDoOutput( true ); MessageBody mb = newMessageBody(); - mb.updateHeaders( connection ); + connection.setRequestProperty( "Content-type", mb.getContentType() ); OutputStream stream = connection.getOutputStream(); mb.writeTo( stream ); stream.flush(); @@ -102,19 +102,21 @@ static class InputStreamMessageBody extends MessageBody { - InputStreamMessageBody( MessageBodyWebRequest request, InputStream source ) { + InputStreamMessageBody( MessageBodyWebRequest request, InputStream source, String contentType ) { super( request ); _source = source; + _contentType = contentType; } /** - * Updates the headers for this request as needed. + * Returns the content type of this message body. **/ - void updateHeaders( URLConnection connection ) throws IOException { + String getContentType() { + return _contentType; } - - + + /** * Transmits the body of this request as a sequence of bytes. **/ @@ -131,5 +133,6 @@ private InputStream _source; + private String _contentType; } } Index: MimeEncodedMessageBody.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/MimeEncodedMessageBody.java,v retrieving revision 1.6 retrieving revision 1.7 diff -u -r1.6 -r1.7 --- MimeEncodedMessageBody.java 2001/06/04 20:45:33 1.6 +++ MimeEncodedMessageBody.java 2001/06/06 13:25:33 1.7 @@ -41,10 +41,10 @@ /** - * Updates the headers for this request as needed. + * Returns the content type of this message body. **/ - void updateHeaders( URLConnection connection ) throws IOException { - connection.setRequestProperty( "Content-type", "multipart/form-data; boundary=" + BOUNDARY ); + String getContentType() { + return "multipart/form-data; boundary=" + BOUNDARY; } Index: PostMethodWebRequest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/PostMethodWebRequest.java,v retrieving revision 1.13 retrieving revision 1.14 diff -u -r1.13 -r1.14 --- PostMethodWebRequest.java 2001/06/04 20:45:33 1.13 +++ PostMethodWebRequest.java 2001/06/06 13:25:33 1.14 @@ -50,10 +50,13 @@ /** * Constructs a web request using a specific absolute url string and input stream. + * @param urlString the URL to which the request should be issued + * @param source an input stream which will provide the body of this request + * @param contentType the MIME content type of the body, including any character set **/ - public PostMethodWebRequest( String urlString, InputStream source ) { + public PostMethodWebRequest( String urlString, InputStream source, String contentType ) { super( urlString ); - _source = source; + _body = new InputStreamMessageBody( this, source, contentType ); } @@ -97,8 +100,8 @@ protected MessageBody newMessageBody() { - if (_source != null) { - return new InputStreamMessageBody( this, _source ); + if (_body != null) { + return _body; } else if (isMimeEncoded()) { return new MimeEncodedMessageBody( this ); } else { @@ -131,6 +134,7 @@ private Hashtable _files = new Hashtable(); private InputStream _source; + private MessageBody _body; } @@ -151,9 +155,10 @@ /** - * Updates the headers for this request as needed. + * Returns the content type of this message body. **/ - void updateHeaders( URLConnection connection ) throws IOException { + String getContentType() { + return "application/x-www-form-urlencoded; charset=" + getRequest().getCharacterSet(); } Index: PutMethodWebRequest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/PutMethodWebRequest.java,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- PutMethodWebRequest.java 2001/06/04 20:45:33 1.1 +++ PutMethodWebRequest.java 2001/06/06 13:25:33 1.2 @@ -37,20 +37,18 @@ public class PutMethodWebRequest extends MessageBodyWebRequest { - public PutMethodWebRequest( String url, InputStream source ) { - super( url ); - _source = source; - } - /** - * Returns a message body based on the input stream. + * Constructs a web request using a specific absolute url string and input stream. + * @param urlString the URL to which the request should be issued + * @param source an input stream which will provide the body of this request + * @param contentType the MIME content type of the body, including any character set **/ - protected MessageBody newMessageBody() { - return new InputStreamMessageBody( this, _source ); + public PutMethodWebRequest( String url, InputStream source, String contentType ) { + super( url ); + _body = new InputStreamMessageBody( this, source, contentType ); } - /** * Returns 'PUT' to indicate the method. **/ @@ -58,6 +56,14 @@ return "PUT"; } + + /** + * Returns a message body based on the input stream. + **/ + protected MessageBody newMessageBody() { + return _body; + } + - private InputStream _source; + private MessageBody _body; } |
From: Russell G. <rus...@us...> - 2001-06-06 13:25:37
|
Update of /cvsroot/httpunit/httpunit/test/com/meterware/httpunit In directory usw-pr-cvs1:/tmp/cvs-serv2105/test/com/meterware/httpunit Added Files: MessageBodyRequestTest.java Log Message: input stream requests now contain content type ***** Error reading new file[Errno 2] No such file or directory: 'MessageBodyRequestTest.java' |
From: Russell G. <rus...@us...> - 2001-06-06 13:25:37
|
Update of /cvsroot/httpunit/httpunit/doc In directory usw-pr-cvs1:/tmp/cvs-serv2105/doc Modified Files: release_notes.txt todo.txt Log Message: input stream requests now contain content type Index: release_notes.txt =================================================================== RCS file: /cvsroot/httpunit/httpunit/doc/release_notes.txt,v retrieving revision 1.34 retrieving revision 1.35 diff -u -r1.34 -r1.35 --- release_notes.txt 2001/06/04 20:45:33 1.34 +++ release_notes.txt 2001/06/06 13:25:33 1.35 @@ -16,6 +16,11 @@ Thanks to Tom Watkins, Deepa Dihr, Marcos Tarruella for their implementation of PutMethodWebRequest + 6-Jun-01 +Additions: + 1. Added ServletUnitClient and InvocationContext to servletunit to + permit more granular testing of servlets + 4-Jun-01 Additions: 1. Added PutMethodWebRequest Index: todo.txt =================================================================== RCS file: /cvsroot/httpunit/httpunit/doc/todo.txt,v retrieving revision 1.10 retrieving revision 1.11 diff -u -r1.10 -r1.11 --- todo.txt 2001/06/04 20:45:33 1.10 +++ todo.txt 2001/06/06 13:25:33 1.11 @@ -1,3 +1,4 @@ +o Support non-text web responses o Support <META HTTP_EQUIV=REFRESH tags> o Support reset button detection o Support _new frame tag |
From: Russell G. <rus...@us...> - 2001-06-06 13:25:08
|
Update of /cvsroot/httpunit/httpunit/src/com/meterware/httpunit In directory usw-pr-cvs1:/tmp/cvs-serv1930/src/com/meterware/httpunit Modified Files: WebClient.java WebConversation.java WebResponse.java Log Message: Added servlet invocation context Index: WebClient.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/WebClient.java,v retrieving revision 1.5 retrieving revision 1.6 diff -u -r1.5 -r1.6 --- WebClient.java 2001/04/05 22:16:07 1.5 +++ WebClient.java 2001/06/06 13:25:04 1.6 @@ -63,18 +63,8 @@ if (request.getURLString().startsWith( "about:" )) return WebResponse.BLANK_RESPONSE; WebResponse response = newResponse( request ); - - validateHeaders( response ); - updateCookies( response ); - if (response.getHeaderField( "Location" ) != null) { - delay( HttpUnitOptions.getRedirectDelay() ); - return getResponse( new RedirectWebRequest( request, - response.getHeaderField( "Location" ), - request.getTarget() ) ); - } else { - updateFrames( response ); - return response; - } + updateClient( response ); + return getFrameContents( request.getTarget() ); } @@ -220,6 +210,23 @@ } + /** + * Updates this web client based on a received response. This includes updating + * cookies and frames. + **/ + final + protected void updateClient( WebResponse response ) throws MalformedURLException, IOException, SAXException { + validateHeaders( response ); + updateCookies( response ); + if (response.getHeaderField( "Location" ) == null) { + updateFrames( response ); + } else { + delay( HttpUnitOptions.getRedirectDelay() ); + getResponse( new RedirectWebRequest( response ) ); + } + } + + //------------------------------------------ private members ------------------------------------- @@ -279,9 +286,10 @@ } private void updateFrames( WebResponse response ) throws MalformedURLException, IOException, SAXException { + removeSubFrames( response.getTarget() ); + _frameContents.put( response.getTarget(), response ); + if (response.isHTML()) { - removeSubFrames( response.getTarget() ); - _frameContents.put( response.getTarget(), response ); createSubFrames( response.getTarget(), response.getFrameNames() ); WebRequest[] requests = response.getFrameRequests(); for (int i = 0; i < requests.length; i++) getResponse( requests[i] ); @@ -316,8 +324,8 @@ class RedirectWebRequest extends WebRequest { - RedirectWebRequest( WebRequest baseRequest, String relativeURL, String target ) throws MalformedURLException { - super( baseRequest, relativeURL, target ); + RedirectWebRequest( WebResponse response ) throws MalformedURLException { + super( response.getURL(), response.getHeaderField( "Location" ), response.getTarget() ); } Index: WebConversation.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/WebConversation.java,v retrieving revision 1.21 retrieving revision 1.22 diff -u -r1.21 -r1.22 --- WebConversation.java 2001/04/13 21:23:46 1.21 +++ WebConversation.java 2001/06/06 13:25:04 1.22 @@ -55,7 +55,7 @@ **/ protected WebResponse newResponse( WebRequest request ) throws MalformedURLException, IOException { URLConnection connection = openConnection( request.getURL() ); - sendHeaders( connection, request.getHeaders() ); + sendHeaders( connection, request.getHeaders() ); if (HttpUnitOptions.isLoggingHttpHeaders()) { for (Enumeration e = getHeaderFields().keys(); e.hasMoreElements(); ) { String key = (String) e.nextElement(); Index: WebResponse.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/WebResponse.java,v retrieving revision 1.33 retrieving revision 1.34 diff -u -r1.33 -r1.34 --- WebResponse.java 2001/05/21 21:04:29 1.33 +++ WebResponse.java 2001/06/06 13:25:04 1.34 @@ -76,9 +76,8 @@ /** * Returns the target of the page. - * @exception SAXException thrown if there is an error parsing this response **/ - public String getTarget() throws SAXException { + public String getTarget() { return _target; } @@ -389,8 +388,8 @@ if (i > -1) { String name = token.substring(0, i).trim(); String value = stripQuote( token.substring( i+1, token.length() ).trim() ); - _newCookies.put( name, value ); - } + _newCookies.put( name, value ); + } } @@ -400,7 +399,7 @@ return value.substring(1,value.length()-1); } return value; - } + } private void readContentTypeHeader() { |
From: Russell G. <rus...@us...> - 2001-06-06 13:25:08
|
Update of /cvsroot/httpunit/httpunit/src/com/meterware/servletunit In directory usw-pr-cvs1:/tmp/cvs-serv1930/src/com/meterware/servletunit Modified Files: ServletRunner.java ServletUnitWebResponse.java Added Files: InvocationContext.java ServletUnitClient.java Log Message: Added servlet invocation context ***** Error reading new file[Errno 2] No such file or directory: 'InvocationContext.java' ***** Error reading new file[Errno 2] No such file or directory: 'ServletUnitClient.java' Index: ServletRunner.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/servletunit/ServletRunner.java,v retrieving revision 1.3 retrieving revision 1.4 diff -u -r1.3 -r1.4 --- ServletRunner.java 2000/12/26 16:30:53 1.3 +++ ServletRunner.java 2001/06/06 13:25:04 1.4 @@ -2,7 +2,7 @@ /******************************************************************************************************************** * $Id$ * -* Copyright (c) 2000, Russell Gold +* Copyright (c) 2000-2001, Russell Gold * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation @@ -34,6 +34,8 @@ import javax.servlet.http.Cookie; import javax.servlet.http.HttpSession; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import com.meterware.httpunit.*; @@ -71,7 +73,10 @@ } - private Servlet getServlet( URL url ) { +//-------------------------------- package methods ------------------------------------- + + + Servlet getServlet( URL url ) { String className = (String) _servlets.get( getServletName( url.getFile() ) ); if (className == null) throw new HttpNotFoundException( url.toExternalForm() ); @@ -91,98 +96,37 @@ } - private String getServletName( String urlFile ) { - if (urlFile.indexOf( '?' ) < 0) { - return urlFile; - } else { - return urlFile.substring( 0, urlFile.indexOf( '?' ) ); - } + ServletUnitContext getContext() { + return _context; } - - ServletUnitHttpResponse getServletResponse( WebRequest request, Cookie[] cookies ) throws MalformedURLException, IOException { - ServletUnitHttpRequest servletRequest = new ServletUnitHttpRequest( request, _context ); - ServletUnitHttpResponse servletResponse = new ServletUnitHttpResponse(); - for (int i = 0; i < cookies.length; i++) servletRequest.addCookie( cookies[i] ); - try { - HttpSession session = servletRequest.getSession( /* create */ false ); - if (session != null) ((ServletUnitHttpSession) session).access(); +//---------------------------- private members ------------------------------------ - Servlet servlet = getServlet( request.getURL() ); - servlet.init( new ServletUnitServletConfig( servlet ) ); - servlet.service( servletRequest, servletResponse ); - session = servletRequest.getSession( /* create */ false ); - if (session != null && session.isNew()) { - servletResponse.addCookie( new Cookie( ServletUnitHttpSession.SESSION_COOKIE_NAME, session.getId() ) ); - } - } catch (ServletException e) { - throw new HttpInternalErrorException( request.getURL().toExternalForm() ); - } - return servletResponse; - } - -//-------------------------------------- private members -------------------------------------------- - - /** A mapping of resource names to servlet class names. **/ Hashtable _servlets = new Hashtable(); - - private String asResourceName( String rawName ) { - if (rawName.startsWith( "/" )) { - return rawName; - } else { - return "/" + rawName; - } - } - - ServletUnitClient _client = new ServletUnitClient( this ); ServletUnitContext _context = new ServletUnitContext(); - - -} - - -class ServletUnitClient extends WebClient { - - ServletUnitClient( ServletRunner runner ) { - _runner = runner; - } - - - /** - * Creates a web response object which represents the response to the specified web request. - **/ - protected WebResponse newResponse( WebRequest request ) throws MalformedURLException,IOException { - return new ServletUnitWebResponse( request.getTarget(), request.getURL(), _runner.getServletResponse( request, getCookies() ) ); + private String getServletName( String urlFile ) { + if (urlFile.indexOf( '?' ) < 0) { + return urlFile; + } else { + return urlFile.substring( 0, urlFile.indexOf( '?' ) ); + } } - private Cookie[] getCookies() { - String cookieHeader = (String) getHeaderFields().get( "Cookie" ); - if (cookieHeader == null) return NO_COOKIES; - Vector cookies = new Vector(); - - StringTokenizer st = new StringTokenizer( cookieHeader, "=;" ); - while (st.hasMoreTokens()) { - String name = st.nextToken(); - if (st.hasMoreTokens()) { - String value = st.nextToken(); - cookies.addElement( new Cookie( name, value ) ); - } + private String asResourceName( String rawName ) { + if (rawName.startsWith( "/" )) { + return rawName; + } else { + return "/" + rawName; } - Cookie[] results = new Cookie[ cookies.size() ]; - cookies.copyInto( results ); - return results; } - private ServletRunner _runner; - - final private static Cookie[] NO_COOKIES = new Cookie[0]; } Index: ServletUnitWebResponse.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/servletunit/ServletUnitWebResponse.java,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- ServletUnitWebResponse.java 2000/11/21 20:44:59 1.1 +++ ServletUnitWebResponse.java 2001/06/06 13:25:04 1.2 @@ -2,7 +2,7 @@ /******************************************************************************************************************** * $Id$ * -* Copyright (c) 2000, Russell Gold +* Copyright (c) 2000-2001, Russell Gold * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation @@ -46,12 +46,13 @@ /** * Constructs a response object from a servlet response. + * @param target the target frame on which the response will be displayed * @param url the url from which the response was received - * @param inputStream the input stream from which the response can be read + * @param response the response populated by the servlet **/ - ServletUnitWebResponse( String target, URL url, ServletUnitHttpResponse response ) { + ServletUnitWebResponse( String target, URL url, HttpServletResponse response ) { super( target, url ); - _response = response; + _response = (ServletUnitHttpResponse) response; } |
From: Russell G. <rus...@us...> - 2001-06-04 23:42:42
|
Update of /cvsroot/httpunit/httpunit/test/com/meterware/httpunit In directory usw-pr-cvs1:/tmp/cvs-serv26791/test/com/meterware/httpunit Modified Files: HttpUnitSuite.java PseudoServer.java PseudoServerTest.java PseudoServlet.java Log Message: Added PUT and generic (non-form) POST methods Index: HttpUnitSuite.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/httpunit/HttpUnitSuite.java,v retrieving revision 1.13 retrieving revision 1.14 diff -u -r1.13 -r1.14 --- HttpUnitSuite.java 2001/04/03 16:49:08 1.13 +++ HttpUnitSuite.java 2001/06/04 20:45:33 1.14 @@ -46,6 +46,7 @@ suite.addTest( FormSubmitTest.suite() ); suite.addTest( Base64Test.suite() ); suite.addTest( PseudoServerTest.suite() ); + suite.addTest( MessageBodyRequestTest.suite() ); addOptionalTestCase( suite, "com.meterware.httpunit.XMLPageTest" ); addOptionalTestCase( suite, "com.meterware.httpunit.FileUploadTest" ); return suite; Index: PseudoServer.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/httpunit/PseudoServer.java,v retrieving revision 1.12 retrieving revision 1.13 diff -u -r1.12 -r1.13 --- PseudoServer.java 2001/05/16 21:03:00 1.12 +++ PseudoServer.java 2001/06/04 20:45:33 1.13 @@ -48,7 +48,7 @@ _active = false; } } - try { + try { if (_serverSocket != null) _serverSocket.close(); _serverSocket = null; } catch (IOException e) { @@ -176,7 +176,7 @@ String uri = st.nextToken(); String protocol = st.nextToken(); - if (!command.equals( "GET" ) && !command.equals( "POST" )) { + if (!command.equals( "GET" ) && !command.equals( "POST" ) && !command.equals( "PUT" )) { sendResponse( pw, HttpURLConnection.HTTP_BAD_METHOD, "unsupported method: " + command ); } else { try { @@ -186,8 +186,8 @@ } else if (resource.getResponseCode() != HttpURLConnection.HTTP_OK) { sendResponse( pw, resource.getResponseCode(), resource.getContents() ); sendLine( pw, "" ); - pw.flush(); - } else { + pw.flush(); + } else { sendResponse( pw, HttpURLConnection.HTTP_OK, "OK" ); sendLine( pw, "Content-type: " + resource.getContentType() + resource.getCharacterSetParameter() ); String[] headers = resource.getHeaders(); @@ -205,8 +205,8 @@ socket.close(); throw e; } catch (Throwable t) { - System.out.println( "Internal error: " + t ); - t.printStackTrace(); + System.out.println( "Internal error: " + t ); + t.printStackTrace(); sendResponse( pw, HttpURLConnection.HTTP_INTERNAL_ERROR, t.toString() ); } } @@ -220,12 +220,9 @@ Object resource = _resources.get( uri ); if (command.equals( "GET" ) && resource instanceof WebResource) { return (WebResource) resource; - } else if (command.equals( "POST" ) && resource instanceof PseudoServlet) { + } else if (resource instanceof PseudoServlet) { Dictionary requestData = readRequest( br ); - return ((PseudoServlet) resource).getPostResponse( getParameters( (String) requestData.get( PseudoServlet.CONTENTS ) ), requestData ); - } else if (command.equals( "GET" ) && resource instanceof PseudoServlet) { - Dictionary requestData = readRequest( br ); - return ((PseudoServlet) resource).getGetResponse( getParameters( (String) requestData.get( PseudoServlet.CONTENTS ) ), requestData ); + return ((PseudoServlet) resource).getResponse( command, getParameters( (String) requestData.get( PseudoServlet.CONTENTS ) ), requestData ); } else { return null; } Index: PseudoServerTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/httpunit/PseudoServerTest.java,v retrieving revision 1.11 retrieving revision 1.12 diff -u -r1.11 -r1.12 --- PseudoServerTest.java 2001/05/31 16:44:15 1.11 +++ PseudoServerTest.java 2001/06/04 20:45:33 1.12 @@ -232,17 +232,17 @@ public void testRefererHeader() throws Exception { String resourceName = "tellMe"; String linkSource = "fromLink"; - String formSource = "fromForm"; + String formSource = "fromForm"; PseudoServer ps = new PseudoServer(); int port = ps.getConnectedPort(); String page0 = "http://localhost:" + port + '/' + resourceName; - String page1 = "http://localhost:" + port + '/' + linkSource; - String page2 = "http://localhost:" + port + '/' + formSource; + String page1 = "http://localhost:" + port + '/' + linkSource; + String page2 = "http://localhost:" + port + '/' + formSource; ps.setResource( linkSource, "<html><head></head><body><a href=\"tellMe\">Go</a></body></html>" ); - ps.setResource( formSource, "<html><body><form action=\"tellMe\"><input type=submit></form></body></html>" ); + ps.setResource( formSource, "<html><body><form action=\"tellMe\"><input type=submit></form></body></html>" ); try { ps.setResource( resourceName, new PseudoServlet() { @@ -257,13 +257,13 @@ assertEquals( "Content type", "text/plain", response.getContentType() ); assertEquals( "Default Referer header", "null", response.getText().trim() ); - response = wc.getResponse( page1 ); - response = wc.getResponse( response.getLinks()[0].getRequest() ); - assertEquals( "Link Referer header", page1, response.getText().trim() ); - - response = wc.getResponse( page2 ); - response = wc.getResponse( response.getForms()[0].getRequest() ); - assertEquals( "Form Referer header", page2, response.getText().trim() ); + response = wc.getResponse( page1 ); + response = wc.getResponse( response.getLinks()[0].getRequest() ); + assertEquals( "Link Referer header", page1, response.getText().trim() ); + + response = wc.getResponse( page2 ); + response = wc.getResponse( response.getForms()[0].getRequest() ); + assertEquals( "Form Referer header", page2, response.getText().trim() ); } finally { ps.shutDown(); } Index: PseudoServlet.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/httpunit/PseudoServlet.java,v retrieving revision 1.3 retrieving revision 1.4 diff -u -r1.3 -r1.4 --- PseudoServlet.java 2001/03/23 20:50:41 1.3 +++ PseudoServlet.java 2001/06/04 20:45:33 1.4 @@ -2,7 +2,7 @@ /******************************************************************************************************************** * $Id$ * -* Copyright (c) 2000, Russell Gold +* Copyright (c) 2000-2001, Russell Gold * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation @@ -37,6 +37,25 @@ * @param headers a mapping of header names to header contents. Also contains a special 'header' named CONTENTS * which is the raw bytes of the request contents stored in a string. **/ + public WebResource getResponse( String methodType, Dictionary parameters, Dictionary headers ) { + if (methodType.equalsIgnoreCase( "GET" )) { + return getGetResponse( parameters, headers ); + } else if (methodType.equalsIgnoreCase( "PUT" )) { + return getPutResponse( parameters, headers ); + } else if (methodType.equalsIgnoreCase( "POST" )) { + return getPostResponse( parameters, headers ); + } else { + throw new RuntimeException( methodType + " not implemented" ); + } + } + + + /** + * Returns a resource object as a result of a get request. + * @param parameters a mapping of parameter names to arrays of value string. + * @param headers a mapping of header names to header contents. Also contains a special 'header' named CONTENTS + * which is the raw bytes of the request contents stored in a string. + **/ public WebResource getGetResponse( Dictionary parameters, Dictionary headers ) { throw new RuntimeException( "get not implemented" ); } @@ -52,6 +71,16 @@ throw new RuntimeException( "post not implemented" ); } + + /* + * Returns a resource object as a result of a put request. + * @param parameters a mapping of parameter names to arrays of value string. + * @param headers a mapping of header names to header contents. Also contains a special 'header' named CONTENTS + * which is the raw bytes of the request contents stored in a string. + **/ + public WebResource getPutResponse( Dictionary parameters, Dictionary headers ) { + throw new RuntimeException( "put not implemented" ); + } } |
From: Russell G. <rus...@us...> - 2001-06-04 23:00:09
|
Update of /cvsroot/httpunit/httpunit/src/com/meterware/httpunit In directory usw-pr-cvs1:/tmp/cvs-serv26791/src/com/meterware/httpunit Modified Files: MessageBody.java MimeEncodedMessageBody.java PostMethodWebRequest.java WebRequest.java Added Files: MessageBodyWebRequest.java PutMethodWebRequest.java Log Message: Added PUT and generic (non-form) POST methods ***** Error reading new file[Errno 2] No such file or directory: 'MessageBodyWebRequest.java' --- NEW FILE --- package com.meterware.httpunit; /******************************************************************************************************************** * Copyright (c) 2001, Russell Gold * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and * to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions * of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *******************************************************************************************************************/ import java.io.InputStream; /** * A web request using the PUT protocol. * * The objectives of this class are to suport an HTTP PUT petition * so we can test this HTTP requests. * * <B>Documentation</B> See the HTTP 1.1 [<a href="http://www.w3.org/Protocols/HTTP/">spec</a>] * * @author Tom Watkins * @author Deepa Dihr * @author Marcos Tarruella * @author Russell Gold * **/ public class PutMethodWebRequest extends MessageBodyWebRequest { public PutMethodWebRequest( String url, InputStream source ) { super( url ); _source = source; } /** * Returns a message body based on the input stream. **/ protected MessageBody newMessageBody() { return new InputStreamMessageBody( this, _source ); } /** * Returns 'PUT' to indicate the method. **/ public String getMethod() { return "PUT"; } private InputStream _source; } Index: MessageBody.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/MessageBody.java,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- MessageBody.java 2001/01/05 14:00:36 1.1 +++ MessageBody.java 2001/06/04 20:45:33 1.2 @@ -26,13 +26,13 @@ /** - * An abstract class representing the body of a POST method request. + * An abstract class representing the body of a web request. **/ abstract class MessageBody { - MessageBody( PostMethodWebRequest request ) { + MessageBody( MessageBodyWebRequest request ) { _request = request; } @@ -51,11 +51,11 @@ void writeTo( OutputStream outputStream ) throws IOException; - protected PostMethodWebRequest getRequest() { + protected MessageBodyWebRequest getRequest() { return _request; } - private PostMethodWebRequest _request; + private MessageBodyWebRequest _request; } Index: MimeEncodedMessageBody.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/MimeEncodedMessageBody.java,v retrieving revision 1.5 retrieving revision 1.6 diff -u -r1.5 -r1.6 --- MimeEncodedMessageBody.java 2001/05/16 21:05:30 1.5 +++ MimeEncodedMessageBody.java 2001/06/04 20:45:33 1.6 @@ -49,6 +49,14 @@ /** + * Returns the request associated with this message body, cast to a POST request. + **/ + PostMethodWebRequest getPostRequest() { + return (PostMethodWebRequest) getRequest(); + } + + + /** * Transmits the body of this request as a sequence of bytes. **/ void writeTo( OutputStream outputStream ) throws IOException { @@ -64,7 +72,7 @@ } } - Dictionary files = getRequest().getSelectedFiles(); + Dictionary files = getPostRequest().getSelectedFiles(); for (Enumeration e = files.keys(); e.hasMoreElements();) { String name = (String) e.nextElement(); WebRequest.UploadFileSpec spec = (WebRequest.UploadFileSpec) files.get( name ); Index: PostMethodWebRequest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/PostMethodWebRequest.java,v retrieving revision 1.12 retrieving revision 1.13 diff -u -r1.12 -r1.13 --- PostMethodWebRequest.java 2001/05/16 21:05:30 1.12 +++ PostMethodWebRequest.java 2001/06/04 20:45:33 1.13 @@ -20,6 +20,7 @@ * *******************************************************************************************************************/ import java.io.File; +import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; @@ -36,7 +37,7 @@ /** * An HTTP request using the POST method. **/ -public class PostMethodWebRequest extends WebRequest { +public class PostMethodWebRequest extends MessageBodyWebRequest { /** @@ -48,6 +49,15 @@ /** + * Constructs a web request using a specific absolute url string and input stream. + **/ + public PostMethodWebRequest( String urlString, InputStream source ) { + super( urlString ); + _source = source; + } + + + /** * Constructs a web request with a specific target. **/ public PostMethodWebRequest( URL urlBase, String urlString, String target ) { @@ -83,18 +93,17 @@ } -//---------------------------------- WebRequest methods -------------------------------- +//----------------------------- MessageBodyWebRequest methods --------------------------- - protected void completeRequest( URLConnection connection ) throws IOException { - MessageBody mb = newMessageBody(); - mb.updateHeaders( connection ); - connection.setDoInput( true ); - connection.setDoOutput( true ); - OutputStream stream = connection.getOutputStream(); - mb.writeTo( stream ); - stream.flush(); - stream.close(); + protected MessageBody newMessageBody() { + if (_source != null) { + return new InputStreamMessageBody( this, _source ); + } else if (isMimeEncoded()) { + return new MimeEncodedMessageBody( this ); + } else { + return new URLEncodedMessageBody( this ); + } } @@ -121,17 +130,12 @@ //---------------------------------- private members ------------------------------------- private Hashtable _files = new Hashtable(); + private InputStream _source; - private MessageBody newMessageBody() { - if (isMimeEncoded()) { - return new MimeEncodedMessageBody( this ); - } else { - return new URLEncodedMessageBody( this ); - } - } - } + + //============================= class URLEncodedMessageBody ====================================== Index: WebRequest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/WebRequest.java,v retrieving revision 1.20 retrieving revision 1.21 diff -u -r1.20 -r1.21 --- WebRequest.java 2001/05/18 21:02:01 1.20 +++ WebRequest.java 2001/06/04 20:45:33 1.21 @@ -436,7 +436,7 @@ if (_sourceForm.isTextParameter( name )) return; if (_sourceForm.isFileParameter( name )) throw new IllegalFileParameterException( name ); if (!inArray( name, _sourceForm.getParameterNames() )) throw new NoSuchParameterException( name ); - if (!inArray( value, _sourceForm.getOptionValues( name ) )) throw new IllegalParameterValueException( name, value ); + if (!inArray( value, _sourceForm.getOptionValues( name ) )) throw new IllegalParameterValueException( name, value, _sourceForm.getOptionValues( name ) ); } @@ -561,17 +561,29 @@ class IllegalParameterValueException extends IllegalRequestParameterException { - IllegalParameterValueException( String parameterName, String badValue ) { + IllegalParameterValueException( String parameterName, String badValue, String[] allowed ) { _parameterName = parameterName; _badValue = badValue; + _allowedValues = allowed; } + public String getMessage() { - return "May not set parameter '" + _parameterName + "' to '" + _badValue + "'"; + StringBuffer sb = new StringBuffer(); + sb.append( "May not set parameter '" ).append( _parameterName ).append( "' to '" ); + sb.append( _badValue ).append( "'. Value must be one of: { " ); + for (int i = 0; i < _allowedValues.length; i++) { + if (i != 0) sb.append( ", " ); + sb.append( _allowedValues[i] ); + } + sb.append( " }" ); + return sb.toString(); } - private String _parameterName; - private String _badValue; + + private String _parameterName; + private String _badValue; + private String[] _allowedValues; } |
From: Russell G. <rus...@us...> - 2001-06-04 22:28:13
|
Update of /cvsroot/httpunit/httpunit/doc In directory usw-pr-cvs1:/tmp/cvs-serv26791/doc Modified Files: release_notes.txt todo.txt Log Message: Added PUT and generic (non-form) POST methods Index: release_notes.txt =================================================================== RCS file: /cvsroot/httpunit/httpunit/doc/release_notes.txt,v retrieving revision 1.33 retrieving revision 1.34 diff -u -r1.33 -r1.34 --- release_notes.txt 2001/05/31 16:44:15 1.33 +++ release_notes.txt 2001/06/04 20:45:33 1.34 @@ -5,6 +5,7 @@ 2. The "_self" target only works for links, not forms 3. The "accept-charset" attribute for forms is ignored; the page content character set is used to encode any response. This behavior matches that currently used by IE and Navigator. + 4. No order is guaranteed for parameters from forms, contrary to the HTML 4.01 spec Limitations: HttpUnit does not support JavaScript @@ -12,7 +13,15 @@ Revision History: Acknowledgements: Thanks to Rolf Schmidiger for corrected behavior when failing to find a site - + Thanks to Tom Watkins, Deepa Dihr, Marcos Tarruella for their implementation of + PutMethodWebRequest + + 4-Jun-01 +Additions: + 1. Added PutMethodWebRequest + 2. PostMethodWebRequest now has a constructor which allows its contents to be + taken from an InputSource, like PutMethodWebRequest + 31-May-01 Problems corrected: 1. Now throws HttpNotFoundException rather than NullPointerException when Index: todo.txt =================================================================== RCS file: /cvsroot/httpunit/httpunit/doc/todo.txt,v retrieving revision 1.9 retrieving revision 1.10 diff -u -r1.9 -r1.10 --- todo.txt 2001/05/31 16:44:15 1.9 +++ todo.txt 2001/06/04 20:45:33 1.10 @@ -1,9 +1,7 @@ -o Integrate PUT method (written by Marcos Tarruella, et. al.) o Support <META HTTP_EQUIV=REFRESH tags> o Support reset button detection +o Support _new frame tag o Send parameters in proper (HTML-file) order -o Add support for POST/PUT to contain user-specified data and content-type - taken either from file or a string o Documentation, Documentation Possibles: |
From: Russell G. <rus...@us...> - 2001-05-31 16:44:18
|
Update of /cvsroot/httpunit/httpunit/src/com/meterware/httpunit In directory usw-pr-cvs1:/tmp/cvs-serv26912/src/com/meterware/httpunit Modified Files: HttpWebResponse.java Log Message: Corrected exceptions when failing to connect Index: HttpWebResponse.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/src/com/meterware/httpunit/HttpWebResponse.java,v retrieving revision 1.8 retrieving revision 1.9 diff -u -r1.8 -r1.9 --- HttpWebResponse.java 2001/05/22 22:18:55 1.8 +++ HttpWebResponse.java 2001/05/31 16:44:15 1.9 @@ -87,7 +87,7 @@ private Hashtable _headers = new Hashtable(); - private void loadResponseText( URL url, URLConnection connection ) throws FileNotFoundException { + private void loadResponseText( URL url, URLConnection connection ) throws IOException { StringBuffer sb = new StringBuffer(); try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); @@ -111,13 +111,13 @@ e.fillInStackTrace(); throw e; } - } catch (IOException e) { - throw new RuntimeException( "Unable to retrieve data from URL: " + url.toExternalForm() + " (" + e + ")" ); } } - private int getResponseCode( String statusHeader ) { + private int getResponseCode( URLConnection connection, String statusHeader ) { + if (statusHeader == null) throw new HttpNotFoundException( connection.getURL().toExternalForm() ); + StringTokenizer st = new StringTokenizer( statusHeader ); st.nextToken(); if (!st.hasMoreTokens()) { @@ -159,7 +159,7 @@ private void readHeaders( URLConnection connection ) { loadHeaders( connection ); if (connection instanceof HttpURLConnection) { - _responseCode = getResponseCode( connection.getHeaderField(0) ); + _responseCode = getResponseCode( connection, connection.getHeaderField(0) ); } else { _responseCode = HttpURLConnection.HTTP_OK; if (getContentType().startsWith( "text" )) { |
From: Russell G. <rus...@us...> - 2001-05-31 16:44:17
|
Update of /cvsroot/httpunit/httpunit/test/com/meterware/httpunit In directory usw-pr-cvs1:/tmp/cvs-serv26912/test/com/meterware/httpunit Modified Files: PseudoServerTest.java Log Message: Corrected exceptions when failing to connect Index: PseudoServerTest.java =================================================================== RCS file: /cvsroot/httpunit/httpunit/test/com/meterware/httpunit/PseudoServerTest.java,v retrieving revision 1.10 retrieving revision 1.11 diff -u -r1.10 -r1.11 --- PseudoServerTest.java 2001/03/23 20:50:41 1.10 +++ PseudoServerTest.java 2001/05/31 16:44:15 1.11 @@ -49,6 +49,16 @@ } + public void testNoSuchServer() throws Exception { + WebConversation wc = new WebConversation(); + + try { + WebResponse response = wc.getResponse( "http://no.such.host" ); + } catch (HttpNotFoundException e) { + } + } + + public void testNotFound() throws Exception { PseudoServer ps = new PseudoServer(); int port = ps.getConnectedPort(); |
From: Russell G. <rus...@us...> - 2001-05-31 16:44:17
|
Update of /cvsroot/httpunit/httpunit/doc In directory usw-pr-cvs1:/tmp/cvs-serv26912/doc Modified Files: release_notes.txt todo.txt Log Message: Corrected exceptions when failing to connect Index: release_notes.txt =================================================================== RCS file: /cvsroot/httpunit/httpunit/doc/release_notes.txt,v retrieving revision 1.32 retrieving revision 1.33 diff -u -r1.32 -r1.33 --- release_notes.txt 2001/05/22 22:18:55 1.32 +++ release_notes.txt 2001/05/31 16:44:15 1.33 @@ -10,6 +10,16 @@ Revision History: +Acknowledgements: + Thanks to Rolf Schmidiger for corrected behavior when failing to find a site + +31-May-01 +Problems corrected: + 1. Now throws HttpNotFoundException rather than NullPointerException when + unable to connect to a web site + 2. I/O exceptions when accessing a site are now thrown, rather than being + turned into RuntimeException. + 22-May-01 Additions: Index: todo.txt =================================================================== RCS file: /cvsroot/httpunit/httpunit/doc/todo.txt,v retrieving revision 1.8 retrieving revision 1.9 diff -u -r1.8 -r1.9 --- todo.txt 2001/05/21 21:04:29 1.8 +++ todo.txt 2001/05/31 16:44:15 1.9 @@ -1,5 +1,7 @@ o Integrate PUT method (written by Marcos Tarruella, et. al.) o Support <META HTTP_EQUIV=REFRESH tags> +o Support reset button detection +o Send parameters in proper (HTML-file) order o Add support for POST/PUT to contain user-specified data and content-type taken either from file or a string o Documentation, Documentation |