Thread: [Httpunit-commit] SF.net SVN: httpunit:[994] trunk/httpunit
Brought to you by:
russgold
From: <wol...@us...> - 2008-11-05 22:27:15
|
Revision: 994 http://httpunit.svn.sourceforge.net/httpunit/?rev=994&view=rev Author: wolfgang_fahl Date: 2008-11-05 22:27:09 +0000 (Wed, 05 Nov 2008) Log Message: ----------- FR [ 2025598 ] support javascript window.scrollTo() Modified Paths: -------------- trunk/httpunit/src/com/meterware/httpunit/dom/DomWindow.java trunk/httpunit/src/com/meterware/httpunit/javascript/JavaScript.java trunk/httpunit/test/com/meterware/httpunit/dom/DomWindowTest.java Modified: trunk/httpunit/src/com/meterware/httpunit/dom/DomWindow.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/dom/DomWindow.java 2008-09-28 16:50:11 UTC (rev 993) +++ trunk/httpunit/src/com/meterware/httpunit/dom/DomWindow.java 2008-11-05 22:27:09 UTC (rev 994) @@ -155,8 +155,10 @@ public void moveTo( int x, int y ) { } + + public void scrollTo( int x, int y ) { + } - protected String getDocumentWriteBuffer() { return _document.getWriteBuffer().toString(); } Modified: trunk/httpunit/src/com/meterware/httpunit/javascript/JavaScript.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/javascript/JavaScript.java 2008-09-28 16:50:11 UTC (rev 993) +++ trunk/httpunit/src/com/meterware/httpunit/javascript/JavaScript.java 2008-11-05 22:27:09 UTC (rev 994) @@ -273,6 +273,10 @@ } + /** + * Window functions + * + */ static public class Window extends JavaScriptEngine { private Document _document; @@ -385,6 +389,9 @@ public void jsFunction_moveTo( int x, int y ) { } + + public void jsFunction_scrollTo( int x, int y ) { + } public void jsFunction_focus() { Modified: trunk/httpunit/test/com/meterware/httpunit/dom/DomWindowTest.java =================================================================== --- trunk/httpunit/test/com/meterware/httpunit/dom/DomWindowTest.java 2008-09-28 16:50:11 UTC (rev 993) +++ trunk/httpunit/test/com/meterware/httpunit/dom/DomWindowTest.java 2008-11-05 22:27:09 UTC (rev 994) @@ -156,6 +156,7 @@ window.setTimeout( 40 ); window.focus(); window.moveTo( 10, 20 ); + window.scrollTo(10,20); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <wol...@us...> - 2008-11-05 23:35:03
|
Revision: 995 http://httpunit.svn.sourceforge.net/httpunit/?rev=995&view=rev Author: wolfgang_fahl Date: 2008-11-05 23:34:58 +0000 (Wed, 05 Nov 2008) Log Message: ----------- FR [ 2163079 ] make form.name property mutable by Peter De Bruycker Modified Paths: -------------- trunk/httpunit/src/com/meterware/httpunit/WebForm.java trunk/httpunit/src/com/meterware/httpunit/javascript/JavaScript.java trunk/httpunit/test/com/meterware/httpunit/javascript/FormScriptingTest.java Modified: trunk/httpunit/src/com/meterware/httpunit/WebForm.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/WebForm.java 2008-11-05 22:27:09 UTC (rev 994) +++ trunk/httpunit/src/com/meterware/httpunit/WebForm.java 2008-11-05 23:34:58 UTC (rev 995) @@ -19,6 +19,7 @@ * DEALINGS IN THE SOFTWARE. * *******************************************************************************************************************/ +import com.meterware.httpunit.scripting.IdentifiedDelegate; import com.meterware.httpunit.scripting.NamedDelegate; import com.meterware.httpunit.scripting.ScriptableDelegate; import com.meterware.httpunit.scripting.FormScriptable; @@ -719,7 +720,12 @@ } - public class Scriptable extends HTMLElementScriptable implements NamedDelegate, FormScriptable { + /** + * + * Scriptable implementation for the WebForm + * + */ + public class Scriptable extends HTMLElementScriptable implements NamedDelegate, IdentifiedDelegate, FormScriptable { public String getAction() { return WebForm.this.getAction(); } public void setAction( String newAction ) { setDestination( newAction ); _presetParameters = null; } @@ -734,9 +740,21 @@ } + /** + * return the name of the WebForm + * @return the name + */ public String getName() { - return WebForm.this.getID().length() != 0 ? WebForm.this.getID() : WebForm.this.getName(); + return WebForm.this.getName().length() != 0 ? WebForm.this.getName() : WebForm.this.getID(); } + + /** + * return the id of the WebForm + * @return the id + */ + public String getID() { + return WebForm.this.getID(); + } /** @@ -771,6 +789,8 @@ setTargetAttribute( value.toString() ); } else if (propertyName.equals( "action" )) { setAction( value.toString() ); + } else if (propertyName.equals( "name" )) { + getElement().setAttribute( "name", value.toString() ); } else if (value instanceof String) { setParameterValue( propertyName, (String) value ); } else if (value instanceof Number) { Modified: trunk/httpunit/src/com/meterware/httpunit/javascript/JavaScript.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/javascript/JavaScript.java 2008-11-05 22:27:09 UTC (rev 994) +++ trunk/httpunit/src/com/meterware/httpunit/javascript/JavaScript.java 2008-11-05 23:34:58 UTC (rev 995) @@ -897,6 +897,10 @@ } + /** + * Form functions + * + */ static public class Form extends HTMLElement { private ElementArray _controls; @@ -908,6 +912,15 @@ public String jsGet_name() { return getDelegate().getName(); } + + /** + * @since FR [ 2163079 ] make form.name property mutable + * by Peter De Bruycker + * @param name + */ + public void jsSet_name( String name ) { + getDelegate().set( "name", name ); + } public String jsGet_action() { return getDelegate().getAction(); Modified: trunk/httpunit/test/com/meterware/httpunit/javascript/FormScriptingTest.java =================================================================== --- trunk/httpunit/test/com/meterware/httpunit/javascript/FormScriptingTest.java 2008-11-05 22:27:09 UTC (rev 994) +++ trunk/httpunit/test/com/meterware/httpunit/javascript/FormScriptingTest.java 2008-11-05 23:34:58 UTC (rev 995) @@ -67,14 +67,39 @@ "<form id='the_form_with_id'/>" + "<script type='JavaScript'>" + " alert( document.forms[1].name );" + + "</script>" + + "<form id='the_form_with_id2' name='the_form_with_name2'/>" + + "<script type='JavaScript'>" + + " alert( document.forms[2].name );" + "</script>" ); WebConversation wc = new WebConversation(); wc.getResponse( getHostPath() + "/OnCommand.html" ); assertEquals( "Message 1", "the_form_with_name", wc.popNextAlert() ); assertEquals( "Message 2", "the_form_with_id", wc.popNextAlert() ); + assertEquals( "Message 3", "the_form_with_name2", wc.popNextAlert() ); } /** + * FR [ 2163079 ] make form.name property mutable by Peter De Bruycker + * + * @throws Exception + */ + public void testModifyingFormNameProperty() throws Exception { + WebConversation wc = new WebConversation(); + defineWebPage( + "Default", + "<form id = 'the_form' name = 'form_name'/>" + + "<a href='#' name='doTell' onClick='document.forms[0].name=\"new_form_name\";'>tell</a>" + + "<a href='#' name='doShow' onClick='alert( document.forms[0].name );'>show</a>"); + WebResponse page = wc.getResponse(getHostPath() + "/Default.html"); + page.getLinkWithName("doShow").click(); + assertEquals("Initial name", "form_name", wc.popNextAlert()); + page.getLinkWithName("doTell").click(); + page.getLinkWithName("doShow").click(); + assertEquals("Current name", "new_form_name", wc.popNextAlert()); + } + + /** * test to access attributes from java script * @throws Exception */ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <wol...@us...> - 2008-11-14 20:29:00
|
Revision: 1006 http://httpunit.svn.sourceforge.net/httpunit/?rev=1006&view=rev Author: wolfgang_fahl Date: 2008-11-14 20:28:49 +0000 (Fri, 14 Nov 2008) Log Message: ----------- fix BR [ 2076028 ] Cookies are handeled incorrectly by Markus Gaisbauer Modified Paths: -------------- trunk/httpunit/src/com/meterware/httpunit/cookies/CookieJar.java trunk/httpunit/test/com/meterware/httpunit/cookies/CookieTest.java Modified: trunk/httpunit/src/com/meterware/httpunit/cookies/CookieJar.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/cookies/CookieJar.java 2008-11-14 19:49:45 UTC (rev 1005) +++ trunk/httpunit/src/com/meterware/httpunit/cookies/CookieJar.java 2008-11-14 20:28:49 UTC (rev 1006) @@ -375,6 +375,7 @@ */ class CookiePress { + // the current value private StringBuffer _value = new StringBuffer(); private HashMap _attributes = new HashMap(); private URL _sourceURL; @@ -389,12 +390,20 @@ } + /** + * clear the attributes and the cookie value + */ void clear() { _value.setLength(0); _attributes.clear(); } + /** + * add the token content + * @param token + * @param lastChar + */ void addToken( String token, char lastChar ) { _value.insert( 0, token ); if (lastChar != '=') _value.insert( 0, ',' ); @@ -408,13 +417,14 @@ * @param equalsIndex - the position of the equal sign */ void addTokenWithEqualsSign( CookieRecipe recipe, String token, int equalsIndex ) { - String name = token.substring( 0, equalsIndex ).trim(); - String value= token.substring( equalsIndex + 1 ).trim(); + final String name = token.substring( 0, equalsIndex ).trim(); + final String value= token.substring( equalsIndex + 1 ).trim(); _value.insert( 0, value ); + final String fvalue=_value.toString(); if (recipe.isCookieAttribute( name.toLowerCase() )) { - _attributes.put( name.toLowerCase(), _value.toString() ); + _attributes.put( name.toLowerCase(), value ); } else { - addCookieIfValid( new Cookie( name, _value.toString(), _attributes ) ); + addCookieIfValid( new Cookie( name, fvalue, _attributes ) ); _attributes.clear(); } _value.setLength(0); Modified: trunk/httpunit/test/com/meterware/httpunit/cookies/CookieTest.java =================================================================== --- trunk/httpunit/test/com/meterware/httpunit/cookies/CookieTest.java 2008-11-14 19:49:45 UTC (rev 1005) +++ trunk/httpunit/test/com/meterware/httpunit/cookies/CookieTest.java 2008-11-14 20:28:49 UTC (rev 1006) @@ -254,6 +254,18 @@ } /** + * test for bug report [ 2076028 ] Cookies are handeled incorrectly + */ + public void testHttpOnlyCookiePath() throws Exception { + CookieJar jar = new CookieJar( + new TestSource( new URL( "http://www.meterware.com" ), + new String[] { "myStuff=1234; path=/; HttpOnly"} ) ); + Cookie cookie=jar.getCookie("myStuff"); + String expected="/"; + assertEquals("The cookie should have the path '"+expected+"' but has "+cookie.getPath(),cookie.getPath(),expected); + } + + /** * test for bug report [ 1533762 ] Valid cookies are rejected * by Alexey Bulat * TODO enable when working patch is available This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <wol...@us...> - 2008-12-02 02:23:22
|
Revision: 1014 http://httpunit.svn.sourceforge.net/httpunit/?rev=1014&view=rev Author: wolfgang_fahl Date: 2008-12-02 02:23:17 +0000 (Tue, 02 Dec 2008) Log Message: ----------- Fix for BR[2264431] Revisited by Brendan Boesen Modified Paths: -------------- trunk/httpunit/src/com/meterware/httpunit/WebForm.java trunk/httpunit/test/com/meterware/httpunit/FormSubmitTest.java Modified: trunk/httpunit/src/com/meterware/httpunit/WebForm.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/WebForm.java 2008-11-15 01:22:53 UTC (rev 1013) +++ trunk/httpunit/src/com/meterware/httpunit/WebForm.java 2008-12-02 02:23:17 UTC (rev 1014) @@ -103,11 +103,9 @@ **/ public WebResponse submit( SubmitButton button, int x, int y ) throws IOException, SAXException { WebResponse result=null; - if (button==null || !button.doOnClickSequence(x, y)) { - result= doFormSubmit( button, x, y ); - } else { - result=getCurrentFrameContents(); - } + if (button == null) throw new IllegalSubmitButtonException( "?", "?" ); + button.doOnClickSequence(x, y); + result=getCurrentFrameContents(); return result; } Modified: trunk/httpunit/test/com/meterware/httpunit/FormSubmitTest.java =================================================================== --- trunk/httpunit/test/com/meterware/httpunit/FormSubmitTest.java 2008-11-15 01:22:53 UTC (rev 1013) +++ trunk/httpunit/test/com/meterware/httpunit/FormSubmitTest.java 2008-12-02 02:23:17 UTC (rev 1014) @@ -257,12 +257,44 @@ } catch (IllegalStateException e) {} } + /** + * test for bug report [2264431] double submit problem + * version 1.7 would have problem with double submits + */ + public void testDoubleSubmitProblem() throws Exception { + boolean states[]={false,true}; + String expected[]={"","1"}; + for (int i=0;i<states.length;i++) { + // countMySelf Tipp from http://www.tipstrs.com/tip/1084/Static-variables-in-Javascript + defineWebPage( "Default", "<form method=GET action = \"Default.html\" onsubmit=\"javascript:countMyself();\">" + + "<script type='JavaScript'>\n" + + "function countMyself() {\n"+ + " // Check to see if the counter has been initialized\n"+ + " if ( typeof countMyself.counter == 'undefined' ) {\n"+ + " // It has not... perform the initilization\n"+ + " countMyself.counter = 0;\n"+ + " }\n"+ + "\n"+ + " // Do something stupid to indicate the value\n"+ + " alert(++countMyself.counter);\n"+ + "}\n"+ + "</script>" + + "<Input type=submit name='update' onclick='return "+states[i]+";'></form>" + + "</form>" ); + WebResponse page = _wc.getResponse( getHostPath() + "/Default.html" ); + WebForm form = page.getForms()[0]; + form.submit(); + String alert=_wc.popNextAlert(); + assertEquals( "There should be "+expected[i]+" submits for onclick state '"+states[i]+"' but there are "+alert,alert,expected[i]); + } + } + /** * test self disabling submit Buttons * test for bug report [ 1289151 ] Order of events in button.click() is wrong */ public void testSelfDisablingSubmitButton() throws Exception { - defineWebPage( "Default", "<form method=GET action = \"Default.html\">" + + defineWebPage( "Default", "<form method=GET action = \"Default.html\">" + "<Input type=submit name='update' onclick='javascript:this.disabled=true;'></form>" + "</form>" ); WebResponse page = _wc.getResponse( getHostPath() + "/Default.html" ); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <wol...@us...> - 2009-02-26 19:26:41
|
Revision: 1019 http://httpunit.svn.sourceforge.net/httpunit/?rev=1019&view=rev Author: wolfgang_fahl Date: 2009-02-26 19:26:36 +0000 (Thu, 26 Feb 2009) Log Message: ----------- Negotiate Header should not spoil Authentication -- null pointer problem removed Modified Paths: -------------- trunk/httpunit/src/com/meterware/httpunit/AuthenticationChallenge.java trunk/httpunit/src/com/meterware/httpunit/HttpHeader.java trunk/httpunit/src/com/meterware/httpunit/WebClient.java trunk/httpunit/test/com/meterware/httpunit/WebClientTest.java Modified: trunk/httpunit/src/com/meterware/httpunit/AuthenticationChallenge.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/AuthenticationChallenge.java 2009-02-26 16:45:33 UTC (rev 1018) +++ trunk/httpunit/src/com/meterware/httpunit/AuthenticationChallenge.java 2009-02-26 19:26:36 UTC (rev 1019) @@ -23,6 +23,8 @@ import java.net.MalformedURLException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.util.Dictionary; +import java.util.Enumeration; import java.io.UnsupportedEncodingException; @@ -49,18 +51,24 @@ _request = request; } - + /** + * check whether authentication is needed + * @return + */ boolean needToAuthenticate() { if (getAuthenticationType() == null) return false; if (getCredentialsForRealm() != null) return true; - if (!_client.getExceptionsThrownOnErrorStatus()) return false; - + if (!_client.getExceptionsThrownOnErrorStatus()) return false;; + throw createAuthorizationRequiredException(); } private String getAuthenticationType() { - return getLabel(); + String result=getLabel(); + if (_headerString!=null && _headerString.equals("Negotiate")) + result=null; + return result; } @@ -82,8 +90,16 @@ } + /** + * get the credentials for the realm property + * @return + */ private PasswordAuthentication getCredentialsForRealm() { - return _client.getCredentialsForRealm( getProperty( "realm" ) ); + String realm=getProperty( "realm" ); + PasswordAuthentication result=null; + if (realm!=null) + result=_client.getCredentialsForRealm( realm ); + return result; } private String getMethod() { Modified: trunk/httpunit/src/com/meterware/httpunit/HttpHeader.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/HttpHeader.java 2009-02-26 16:45:33 UTC (rev 1018) +++ trunk/httpunit/src/com/meterware/httpunit/HttpHeader.java 2009-02-26 19:26:36 UTC (rev 1019) @@ -28,15 +28,26 @@ private String _label; private Map _properties; + protected String _headerString; + /** + * construct a HttpHeader from the given headerString + * @param headerString + */ public HttpHeader( String headerString ) { this( headerString, null ); } + /** + * construct a HttpHeader from the given headerString and label + * @param headerString + * @param defaultLabel + */ public HttpHeader( String headerString, String defaultLabel ) { if (headerString != null) { + _headerString=headerString; final int index = headerString.indexOf( ' ' ); if (index < 0) { // non-conforming header _label = defaultLabel; Modified: trunk/httpunit/src/com/meterware/httpunit/WebClient.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/WebClient.java 2009-02-26 16:45:33 UTC (rev 1018) +++ trunk/httpunit/src/com/meterware/httpunit/WebClient.java 2009-02-26 19:26:36 UTC (rev 1019) @@ -261,8 +261,20 @@ } + /** + * get the credentials for the given realm + * @param realm + * @return + */ PasswordAuthentication getCredentialsForRealm( String realm ) { - return ((PasswordAuthentication) _credentials.get( realm )); + if (_credentials==null) { + throw new Error("null _credentials while calling getCredentialsForRealm"); + } + if (realm==null) { + throw new Error("null realm while calling getCredentialsForRealm"); + } + PasswordAuthentication result=((PasswordAuthentication) _credentials.get( realm )); + return result; } /** Modified: trunk/httpunit/test/com/meterware/httpunit/WebClientTest.java =================================================================== --- trunk/httpunit/test/com/meterware/httpunit/WebClientTest.java 2009-02-26 16:45:33 UTC (rev 1018) +++ trunk/httpunit/test/com/meterware/httpunit/WebClientTest.java 2009-02-26 19:26:36 UTC (rev 1019) @@ -384,8 +384,32 @@ assertEquals( "bogusrealm", e.getAuthenticationParameter( "realm" ) ); } } + + /** + * test the Negotiate Header does not spoil authentication + * @throws Exception + */ + public void testAuthenticationNegotiateRequest() throws Exception { + defineResource( "getAuthorization", new PseudoServlet() { + public WebResource getGetResponse() { + String header = getHeader( "Authorization" ); + if (header == null) { + WebResource webResource = new WebResource( "unauthorized" ); + webResource.addHeader( "WWW-Authenticate: Negotiate"); + return webResource; + } else { + return new WebResource( header, "text/plain" ); + } + } + } ); + WebConversation wc = new WebConversation(); + wc.setAuthentication( "testrealm", "user", "password" ); + WebResponse wr = wc.getResponse( getHostPath() + "/getAuthorization" ); + assertEquals( "authorization", "unauthorized", wr.getText() ); + } + public void suspendtestProxyServerAccessWithAuthentication() throws Exception { defineResource( "http://someserver.com/sample", new PseudoServlet() { public WebResource getGetResponse() { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <wol...@us...> - 2009-03-13 14:28:59
|
Revision: 1020 http://httpunit.svn.sourceforge.net/httpunit/?rev=1020&view=rev Author: wolfgang_fahl Date: 2009-03-13 14:28:46 +0000 (Fri, 13 Mar 2009) Log Message: ----------- patch by Serge Maslyukov to solve issue with drupal's cookie Modified Paths: -------------- trunk/httpunit/src/com/meterware/httpunit/cookies/CookieJar.java trunk/httpunit/test/com/meterware/httpunit/cookies/CookieTest.java Modified: trunk/httpunit/src/com/meterware/httpunit/cookies/CookieJar.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/cookies/CookieJar.java 2009-02-26 19:26:36 UTC (rev 1019) +++ trunk/httpunit/src/com/meterware/httpunit/cookies/CookieJar.java 2009-03-13 14:28:46 UTC (rev 1020) @@ -251,15 +251,43 @@ * Add the cookie to this jar, replacing any previous matching cookie. */ void addUniqueCookie( Cookie cookie ) { - _cookies.remove( cookie ); + _cookies.remove( cookie ); + for (Iterator i = _cookies.iterator(); i.hasNext();) { + Cookie c = (Cookie) i.next(); + if (c.getName().equals(cookie.getName())) { + if (compareDomain(c.getDomain(), cookie.getDomain())) { + if (c.getPath() != null && cookie.getPath() != null + && c.getPath().equals(cookie.getPath())) { + i.remove(); + } + } + } + } _cookies.add( cookie ); } + /** + * compare the two domains given for "cookie-equality" + * + * @param domain + * @param newDomain + * @return + */ + private boolean compareDomain(String domain, String newDomain) { + if (domain.charAt(0) == '.' && newDomain.endsWith(domain)) { + return true; + } + if (newDomain.charAt(0) == '.' && domain.endsWith(newDomain)) { + return true; + } + + return domain.equals(newDomain); + } /** - * base class for the cookie recipies - there are two different implementations - * of this - */ + * base class for the cookie recipies - there are two different + * implementations of this + */ abstract class CookieRecipe { /** Modified: trunk/httpunit/test/com/meterware/httpunit/cookies/CookieTest.java =================================================================== --- trunk/httpunit/test/com/meterware/httpunit/cookies/CookieTest.java 2009-02-26 19:26:36 UTC (rev 1019) +++ trunk/httpunit/test/com/meterware/httpunit/cookies/CookieTest.java 2009-03-13 14:28:46 UTC (rev 1020) @@ -190,8 +190,7 @@ 0}; for (int i = 0; i < ages.length; i++) { - String index = "" + i; - String cookieName = "cookie" + index.trim(); + String cookieName = "cookie" + i; String header = cookieName + "=cookievalue;" + ages[i]; TestSource source = new TestSource( new URL( "http://www.somedomain.com/somepath/" ), header ); CookieJar jar = new CookieJar( source ); @@ -229,6 +228,44 @@ } /** + * + * @throws Exception + */ + public void testDrupalCookieInteraction() throws Exception { + CookieJar jar = new CookieJar(); + jar.putSingleUseCookie("SESS1234","1234",".drupalsite.org","/"); + Cookie cookie=jar.getCookie("SESS1234"); + assertTrue(cookie!=null); + assertEquals(cookie.getDomain(),".drupalsite.org"); + assertEquals(cookie.getValue(),"1234"); + assertEquals(cookie.getPath(),"/"); + assertEquals(1, jar.getCookies().size()); + + CookieJar jar1 = new CookieJar(); + jar1.putSingleUseCookie("SESS1234", "deleted", "www.drupalsite.org","/"); + jar.updateCookies( jar1 ); + + cookie=jar.getCookie("SESS1234"); + assertTrue(cookie!=null); + assertEquals(cookie.getDomain(),"www.drupalsite.org"); + assertEquals(cookie.getValue(),"deleted"); + assertEquals(cookie.getPath(),"/"); + assertEquals(1, jar.getCookies().size()); + + CookieJar jar2 = new CookieJar(); + jar2.putSingleUseCookie("SESS1234", "4321", ".drupalsite.org","/"); + jar.updateCookies( jar2 ); + + cookie=jar.getCookie("SESS1234"); + assertTrue(cookie!=null); + assertEquals(cookie.getDomain(),".drupalsite.org"); + assertEquals(cookie.getValue(),"4321"); + assertEquals(cookie.getPath(),"/"); + assertEquals(1, jar.getCookies().size()); + + } + + /** * test for [ 1488617 ] alternate patch for cookie bug #1371204 * @throws Exception */ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <wol...@us...> - 2009-03-16 15:31:59
|
Revision: 1021 http://httpunit.svn.sourceforge.net/httpunit/?rev=1021&view=rev Author: wolfgang_fahl Date: 2009-03-16 15:31:41 +0000 (Mon, 16 Mar 2009) Log Message: ----------- toLowerCase built in function added Modified Paths: -------------- trunk/httpunit/src/com/meterware/httpunit/javascript/JavaScript.java trunk/httpunit/test/com/meterware/httpunit/javascript/ScriptingTest.java Modified: trunk/httpunit/src/com/meterware/httpunit/javascript/JavaScript.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/javascript/JavaScript.java 2009-03-13 14:28:46 UTC (rev 1020) +++ trunk/httpunit/src/com/meterware/httpunit/javascript/JavaScript.java 2009-03-16 15:31:41 UTC (rev 1021) @@ -375,6 +375,14 @@ public void jsFunction_alert( String message ) { getDelegate().alertUser( message ); } + + /** + * javascript built in function "toLowerCase" + * @param s + */ + public String jsFunction_toLowerCase(String s) { + return s.toLowerCase(); + } public boolean jsFunction_confirm( String message ) { Modified: trunk/httpunit/test/com/meterware/httpunit/javascript/ScriptingTest.java =================================================================== --- trunk/httpunit/test/com/meterware/httpunit/javascript/ScriptingTest.java 2009-03-13 14:28:46 UTC (rev 1020) +++ trunk/httpunit/test/com/meterware/httpunit/javascript/ScriptingTest.java 2009-03-16 15:31:41 UTC (rev 1021) @@ -159,6 +159,21 @@ response.getLinkWith( "go" ).click(); assertEquals( "Alert message", "Cheese!", wc.popNextAlert() ); } + + /** + * test javascript call to built-in functions + * e.g. toLowerCase + */ + public void testJavaScriptWitBuiltInFunctions() throws Exception { + defineResource( "OnCommand.html", "<html>" + + "<body>" + + "<a href=\"javascript:alert(toLowerCase('Cheese!'))\">go</a>" + + "</body></html>" ); + WebConversation wc = new WebConversation(); + WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" ); + response.getLinkWith( "go" ).click(); + assertEquals( "Alert message", "cheese!", wc.popNextAlert() ); + } /** * test javascript call to an included function This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <wol...@us...> - 2009-06-29 15:46:22
|
Revision: 1023 http://httpunit.svn.sourceforge.net/httpunit/?rev=1023&view=rev Author: wolfgang_fahl Date: 2009-06-29 15:46:18 +0000 (Mon, 29 Jun 2009) Log Message: ----------- Eclipse setting modified for lesser warnings Modified Paths: -------------- trunk/httpunit/.classpath trunk/httpunit/.settings/org.eclipse.jdt.core.prefs Modified: trunk/httpunit/.classpath =================================================================== --- trunk/httpunit/.classpath 2009-03-29 13:20:36 UTC (rev 1022) +++ trunk/httpunit/.classpath 2009-06-29 15:46:18 UTC (rev 1023) @@ -17,11 +17,6 @@ <classpathentry kind="var" path="MAVEN_REPOSITORY/javax/activation/activation/1.1/activation-1.1.jar"/> <classpathentry kind="var" path="MAVEN_REPOSITORY/javax/mail/mail/1.4/mail-1.4.jar"/> <classpathentry kind="lib" path="jars/maven-ant-tasks-2.0.9.jar"/> - <!-- Libaries needed to test [ 2264431 ] form.submit() sends multiple HTTP POSTS - <classpathentry kind="var" path="MAVEN_REPOSITORY/org/mortbay/jetty/jetty/6.1.4/jetty-6.1.4.jar"/> - <classpathentry kind="var" path="MAVEN_REPOSITORY/org/mortbay/jetty/jetty-naming/6.1.4/jetty-naming-6.1.4.jar"/> - <classpathentry kind="var" path="MAVEN_REPOSITORY/org/mortbay/jetty/jetty-plus/6.1.4/jetty-plus-6.1.4.jar"/> - <classpathentry kind="var" path="MAVEN_REPOSITORY/org/mortbay/jetty/jetty-util/6.1.4/jetty-util-6.1.4.jar"/> + <classpathentry kind="var" path="MAVEN_REPOSITORY"/> <classpathentry kind="output" path="bin"/> - --> </classpath> Modified: trunk/httpunit/.settings/org.eclipse.jdt.core.prefs =================================================================== --- trunk/httpunit/.settings/org.eclipse.jdt.core.prefs 2009-03-29 13:20:36 UTC (rev 1022) +++ trunk/httpunit/.settings/org.eclipse.jdt.core.prefs 2009-06-29 15:46:18 UTC (rev 1023) @@ -1,12 +1,70 @@ -#Thu Jun 05 20:38:34 CEST 2008 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.4 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning -org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning -org.eclipse.jdt.core.compiler.source=1.3 +#Mon Jun 29 17:45:01 CEST 2009 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.4 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning +org.eclipse.jdt.core.compiler.problem.autoboxing=ignore +org.eclipse.jdt.core.compiler.problem.deprecation=ignore +org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled +org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled +org.eclipse.jdt.core.compiler.problem.discouragedReference=warning +org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore +org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning +org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore +org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled +org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore +org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning +org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning +org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning +org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore +org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore +org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore +org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning +org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore +org.eclipse.jdt.core.compiler.problem.missingSerialVersion=ignore +org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning +org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning +org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore +org.eclipse.jdt.core.compiler.problem.nullReference=warning +org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning +org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore +org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore +org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore +org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning +org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore +org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore +org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled +org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning +org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled +org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore +org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning +org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning +org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore +org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning +org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore +org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore +org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled +org.eclipse.jdt.core.compiler.problem.unusedImport=ignore +org.eclipse.jdt.core.compiler.problem.unusedLabel=warning +org.eclipse.jdt.core.compiler.problem.unusedLocal=ignore +org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore +org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled +org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=ignore +org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning +org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning +org.eclipse.jdt.core.compiler.source=1.3 This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <wol...@us...> - 2009-08-18 16:08:26
|
Revision: 1036 http://httpunit.svn.sourceforge.net/httpunit/?rev=1036&view=rev Author: wolfgang_fahl Date: 2009-08-18 16:08:16 +0000 (Tue, 18 Aug 2009) Log Message: ----------- implemented CR [ 914314 ] to add getResponse to HttpException improved handling of undefined resources in PseudoServer getIncludedScript now handles 404 errors according to the HttpUnit Options settings for script error and exception handling (thanks to Dan Lipofsky for pointing this out) Modified Paths: -------------- trunk/httpunit/src/com/meterware/httpunit/HttpException.java trunk/httpunit/src/com/meterware/httpunit/HttpUnitOptions.java trunk/httpunit/src/com/meterware/httpunit/HttpWebResponse.java trunk/httpunit/src/com/meterware/httpunit/ParsedHTML.java trunk/httpunit/src/com/meterware/httpunit/WebClient.java trunk/httpunit/src/com/meterware/httpunit/WebResponse.java trunk/httpunit/src/com/meterware/httpunit/dom/DomBasedScriptingEngineFactory.java trunk/httpunit/src/com/meterware/httpunit/javascript/JavaScriptEngineFactory.java trunk/httpunit/src/com/meterware/httpunit/javascript/ScriptingEngineImpl.java trunk/httpunit/src/com/meterware/httpunit/scripting/ScriptingEngineFactory.java trunk/httpunit/src/com/meterware/pseudoserver/PseudoServer.java trunk/httpunit/test/com/meterware/httpunit/WebClientTest.java trunk/httpunit/test/com/meterware/httpunit/javascript/ScriptingTest.java Modified: trunk/httpunit/src/com/meterware/httpunit/HttpException.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/HttpException.java 2009-08-18 11:31:16 UTC (rev 1035) +++ trunk/httpunit/src/com/meterware/httpunit/HttpException.java 2009-08-18 16:08:16 UTC (rev 1036) @@ -128,5 +128,24 @@ private Throwable _cause; + + // see feature request [ 914314 ] Add HttpException.getResponse for better reporting + private WebResponse response; + + /** + * return the WebResponse associated with this Exception (if any) + * @return + */ + public WebResponse getResponse() { + return response; + } + + /** + * add the given response to this exception + * @param response + */ + public void setResponse(WebResponse response) { + this.response=response; + } } \ No newline at end of file Modified: trunk/httpunit/src/com/meterware/httpunit/HttpUnitOptions.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/HttpUnitOptions.java 2009-08-18 11:31:16 UTC (rev 1035) +++ trunk/httpunit/src/com/meterware/httpunit/HttpUnitOptions.java 2009-08-18 16:08:16 UTC (rev 1036) @@ -505,6 +505,9 @@ public void clearErrorMessages() {} public ScriptingHandler createHandler( HTMLElement element ) { return ScriptableDelegate.NULL_SCRIPT_ENGINE; } public ScriptingHandler createHandler( WebResponse response ) { return ScriptableDelegate.NULL_SCRIPT_ENGINE; } + public void handleScriptException(Exception e, String badScript) { + // happily ignore and exception + } }; Modified: trunk/httpunit/src/com/meterware/httpunit/HttpWebResponse.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/HttpWebResponse.java 2009-08-18 11:31:16 UTC (rev 1035) +++ trunk/httpunit/src/com/meterware/httpunit/HttpWebResponse.java 2009-08-18 16:08:16 UTC (rev 1036) @@ -2,7 +2,7 @@ /******************************************************************************************************************** * $Id$ * -* Copyright (c) 2000-2004, Russell Gold +* Copyright (c) 2000-2009, 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,8 +58,12 @@ /** make sure that any IO exception for HTML received page happens here, not later. **/ if (_responseCode < HttpURLConnection.HTTP_BAD_REQUEST || !throwExceptionOnError) { - defineRawInputStream( new BufferedInputStream( getInputStream( connection ) ) ); - if (getContentType().startsWith( "text" )) loadResponseText(); + InputStream inputStream = getInputStream( connection ); + defineRawInputStream( new BufferedInputStream( inputStream ) ); + String contentType = getContentType(); + if (contentType.startsWith( "text" )) { + loadResponseText(); + } } } @@ -81,7 +85,7 @@ InputStream result=null; // check whether there is an error stream if (isResponseOnErrorStream( connection )) { - result=((HttpURLConnection) connection).getErrorStream(); + result=((HttpURLConnection) connection).getErrorStream(); } else { // if there is no error stream it depends on the response code try { @@ -190,30 +194,40 @@ private int _responseCode = HttpURLConnection.HTTP_OK; - private String _responseMessage = "OK"; + private String _responseMessage = "OK"; + + /** + * set the responseCode to the given code and message + * @param code + * @param message + */ + private void setResponseCode(int code, String message) { + _responseCode = code; + _responseMessage=message; + } private Hashtable _headers = new Hashtable(); - - + /** + * read the response Header for the given connection and set the response code and + * message accordingly + * @param connection + * @throws IOException + */ private void readResponseHeader( HttpURLConnection connection ) throws IOException { if (!needStatusWorkaround()) { - _responseCode = connection.getResponseCode(); - _responseMessage = connection.getResponseMessage(); + setResponseCode(connection.getResponseCode(),connection.getResponseMessage()); } else { if (connection.getHeaderField(0) == null) throw new UnknownHostException( connection.getURL().toExternalForm() ); StringTokenizer st = new StringTokenizer( connection.getHeaderField(0) ); st.nextToken(); if (!st.hasMoreTokens()) { - _responseCode = HttpURLConnection.HTTP_OK; - _responseMessage = "OK"; + setResponseCode(HttpURLConnection.HTTP_OK,"OK"); } else try { - _responseCode = Integer.parseInt( st.nextToken() ); - _responseMessage = getRemainingTokens( st ); + setResponseCode(Integer.parseInt( st.nextToken()) ,getRemainingTokens( st )); } catch (NumberFormatException e) { - _responseCode = HttpURLConnection.HTTP_INTERNAL_ERROR; - _responseMessage = "Cannot parse response header"; + setResponseCode (HttpURLConnection.HTTP_INTERNAL_ERROR,"Cannot parse response header"); } } } @@ -238,8 +252,7 @@ if (connection instanceof HttpURLConnection) { readResponseHeader( (HttpURLConnection) connection ); } else { - _responseCode = HttpURLConnection.HTTP_OK; - _responseMessage = "OK"; + setResponseCode (HttpURLConnection.HTTP_OK, "OK"); if (connection.getContentType().startsWith( "text" )) { setContentTypeHeader( connection.getContentType() + "; charset=" + FILE_ENCODING ); } Modified: trunk/httpunit/src/com/meterware/httpunit/ParsedHTML.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/ParsedHTML.java 2009-08-18 11:31:16 UTC (rev 1035) +++ trunk/httpunit/src/com/meterware/httpunit/ParsedHTML.java 2009-08-18 16:08:16 UTC (rev 1036) @@ -25,6 +25,7 @@ import org.w3c.dom.Document; import org.w3c.dom.html.*; +import java.net.HttpURLConnection; import java.net.URL; import java.util.*; import java.io.IOException; @@ -380,7 +381,7 @@ } else { try { return getIncludedScript( scriptLocation ); - } catch (IOException e) { + } catch (Exception e) { throw new RuntimeException( "Error loading included script: " + e ); } } @@ -391,13 +392,30 @@ * Returns the contents of an included script, given its src attribute. * @param srcAttribute the location of the script. * @return the contents of the script. - * @throws java.io.IOException if there is a problem retrieving the script + * @throws IOException if there is a problem retrieving the script */ String getIncludedScript( String srcAttribute ) throws IOException { WebRequest req = new GetMethodWebRequest( getBaseURL(), srcAttribute ); WebWindow window = getResponse().getWindow(); - if (window == null) throw new IllegalStateException( "Unable to retrieve script included by this response, since it was loaded by getResource(). Use getResponse() instead."); - return window.getResource( req ).getText(); + if (window == null) + throw new IllegalStateException( "Unable to retrieve script included by this response, since it was loaded by getResource(). Use getResponse() instead."); + WebResponse response = window.getResource( req ); + // check whether the Source is available + int code = response.getResponseCode(); + // if everything is o.k. + if (code<=HttpURLConnection.HTTP_BAD_REQUEST) { + // return the text + String result =response.getText(); + return result; + } else { + // in this case the text would be an error message + // we do not return it but set the + ScriptException se=new ScriptException(response.getText()); + String badScript="?"; + // let scripting engine decide what to do with this exception (throw it or remember it ...) + HttpUnitOptions.getScriptingEngine().handleScriptException(se, badScript); + return ""; + } } Modified: trunk/httpunit/src/com/meterware/httpunit/WebClient.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/WebClient.java 2009-08-18 11:31:16 UTC (rev 1035) +++ trunk/httpunit/src/com/meterware/httpunit/WebClient.java 2009-08-18 16:08:16 UTC (rev 1036) @@ -623,17 +623,25 @@ * @parm response - the response to validate **/ private void validateHeaders( WebResponse response ) throws HttpException { - if (!getExceptionsThrownOnErrorStatus()) - return; - // see feature request [ 914314 ] Add HttpException.getResponse for better reporting - // for possible improvements here + HttpException exception=null; if (response.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR) { - throw new HttpInternalErrorException( response.getURL() ); + exception=new HttpInternalErrorException( response.getURL() ); } else if (response.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) { - throw new HttpNotFoundException( response.getResponseMessage(), response.getURL() ); + exception= new HttpNotFoundException( response.getResponseMessage(), response.getURL() ); } else if (response.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST) { - throw new HttpException( response.getResponseCode(), response.getResponseMessage(), response.getURL() ); + exception= new HttpException( response.getResponseCode(), response.getResponseMessage(), response.getURL() ); } + // is there an exception? + if (exception!=null) { + // see feature request [ 914314 ] Add HttpException.getResponse for better reporting + exception.setResponse(response); + // shall we ignore errors? + if (!getExceptionsThrownOnErrorStatus()) { + return; + } else { + throw exception; + } + } } Modified: trunk/httpunit/src/com/meterware/httpunit/WebResponse.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/WebResponse.java 2009-08-18 11:31:16 UTC (rev 1035) +++ trunk/httpunit/src/com/meterware/httpunit/WebResponse.java 2009-08-18 16:08:16 UTC (rev 1036) @@ -282,16 +282,17 @@ * which may be used to represent internal state of this object. **/ public String getText() throws IOException { - if (_responseText == null) loadResponseText(); + if (_responseText == null) + loadResponseText(); return _responseText; } - /** * Returns a buffered input stream for reading the contents of this reply. **/ public InputStream getInputStream() throws IOException { - if (_inputStream == null) _inputStream = new ByteArrayInputStream( getText().getBytes() ); + if (_inputStream == null) + _inputStream = new ByteArrayInputStream( getText().getBytes() ); return _inputStream; } @@ -1056,7 +1057,7 @@ private String _responseText; - private InputStream _inputStream; + private InputStream _inputStream; private final URL _pageURL; Modified: trunk/httpunit/src/com/meterware/httpunit/dom/DomBasedScriptingEngineFactory.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/dom/DomBasedScriptingEngineFactory.java 2009-08-18 11:31:16 UTC (rev 1035) +++ trunk/httpunit/src/com/meterware/httpunit/dom/DomBasedScriptingEngineFactory.java 2009-08-18 16:08:16 UTC (rev 1036) @@ -26,6 +26,7 @@ import com.meterware.httpunit.scripting.ScriptingHandler; import com.meterware.httpunit.scripting.ScriptingEngine; import com.meterware.httpunit.HttpUnitUtils; +import com.meterware.httpunit.ScriptException; import com.meterware.httpunit.WebResponse; import com.meterware.httpunit.HTMLElement; @@ -38,6 +39,7 @@ import org.xml.sax.SAXException; import org.mozilla.javascript.Context; import org.mozilla.javascript.EcmaError; +import org.mozilla.javascript.EvaluatorException; import org.mozilla.javascript.Function; import org.mozilla.javascript.JavaScriptException; import org.mozilla.javascript.Scriptable; @@ -143,4 +145,14 @@ public ScriptingHandler createHandler( WebResponse response ) { return response.createDomScriptingHandler(); } + + + /** + * handle Exceptions + * @param e - the exception to handle + * @param badScript - the script that caused the problem + */ + public void handleScriptException( Exception e, String badScript ) { + ScriptingEngineImpl.handleScriptException(e, badScript); + } } Modified: trunk/httpunit/src/com/meterware/httpunit/javascript/JavaScriptEngineFactory.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/javascript/JavaScriptEngineFactory.java 2009-08-18 11:31:16 UTC (rev 1035) +++ trunk/httpunit/src/com/meterware/httpunit/javascript/JavaScriptEngineFactory.java 2009-08-18 16:08:16 UTC (rev 1036) @@ -82,6 +82,13 @@ public String[] getErrorMessages() { return ScriptingEngineImpl.getErrorMessages(); } + + /** + * delegate the handling for Script exceptions + */ + public void handleScriptException(Exception e, String badScript) { + ScriptingEngineImpl.handleScriptException(e, badScript); + } public void clearErrorMessages() { @@ -99,4 +106,6 @@ public ScriptingHandler createHandler( WebResponse response ) { return response.createJavascriptScriptingHandler(); } + + } Modified: trunk/httpunit/src/com/meterware/httpunit/javascript/ScriptingEngineImpl.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/javascript/ScriptingEngineImpl.java 2009-08-18 11:31:16 UTC (rev 1035) +++ trunk/httpunit/src/com/meterware/httpunit/javascript/ScriptingEngineImpl.java 2009-08-18 16:08:16 UTC (rev 1036) @@ -44,6 +44,10 @@ } + /** + * access to the list of error Messages that were collected + * @return the array with error Messages + */ static public String[] getErrorMessages() { return (String[]) _errorMessages.toArray( new String[ _errorMessages.size() ] ); } @@ -56,11 +60,15 @@ */ static public void handleScriptException( Exception e, String badScript ) { final String errorMessage = badScript + " failed: " + e; - if (!(e instanceof EcmaError) && !(e instanceof EvaluatorException)) { + + if (!(e instanceof EcmaError) && !(e instanceof EvaluatorException) && !(e instanceof ScriptException)) { HttpUnitUtils.handleException(e); throw new RuntimeException( errorMessage ); } else if (JavaScript.isThrowExceptionsOnError()) { HttpUnitUtils.handleException(e); + if (e instanceof ScriptException) + throw (ScriptException)e; + else throw new ScriptException( errorMessage ); } else { _errorMessages.add( errorMessage ); Modified: trunk/httpunit/src/com/meterware/httpunit/scripting/ScriptingEngineFactory.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/scripting/ScriptingEngineFactory.java 2009-08-18 11:31:16 UTC (rev 1035) +++ trunk/httpunit/src/com/meterware/httpunit/scripting/ScriptingEngineFactory.java 2009-08-18 16:08:16 UTC (rev 1036) @@ -64,6 +64,13 @@ * Clears the accumulated script error messages. */ public void clearErrorMessages(); + + /** + * handle Exceptions + * @param e - the exception to handle + * @param badScript - the script that caused the problem + */ + public void handleScriptException( Exception e, String badScript ); ScriptingHandler createHandler( HTMLElement elementBase ); Modified: trunk/httpunit/src/com/meterware/pseudoserver/PseudoServer.java =================================================================== --- trunk/httpunit/src/com/meterware/pseudoserver/PseudoServer.java 2009-08-18 11:31:16 UTC (rev 1035) +++ trunk/httpunit/src/com/meterware/pseudoserver/PseudoServer.java 2009-08-18 16:08:16 UTC (rev 1036) @@ -100,6 +100,10 @@ } + /** + * create a PseudoServer with the given socketTimeout + * @param socketTimeout - the time out to use + */ public PseudoServer( int socketTimeout ) { _socketTimeout = socketTimeout; _serverNum = ++_numServers; @@ -197,9 +201,16 @@ /** * Defines a resource which will result in an error message. - **/ - public void setErrorResource( String name, int errorCode, String errorMessage ) { - _resources.put( asResourceName( name ), new WebResource( errorMessage, errorCode ) ); + * return it for further use + * @param name + * @param errorCode + * @param errorMessage + * @return the resource + */ + public WebResource setErrorResource( String name, int errorCode, String errorMessage ) { + WebResource resource = new WebResource( errorMessage, errorCode ); + _resources.put( asResourceName( name ), resource ); + return resource; } @@ -314,7 +325,9 @@ boolean keepAlive = respondToRequest( request, outputStream ); if (!keepAlive) break; while (_active && 0 == inputStream.available()) { - try { Thread.sleep( INPUT_POLL_INTERVAL ); } catch (InterruptedException e) {} + try { + Thread.sleep( INPUT_POLL_INTERVAL ); + } catch (InterruptedException e) {} } } } catch (IOException e) { @@ -329,6 +342,12 @@ } + /** + * respond to the given request + * @param request - the request + * @param response - the response stream + * @return + */ private boolean respondToRequest( HttpRequest request, HttpResponseStream response ) { debug( "Server thread handling request: " + request ); boolean keepAlive = isKeepAlive( request ); @@ -338,25 +357,39 @@ response.setProtocol( getResponseProtocol( request ) ); resource = getResource( request ); if (resource == null) { - response.setResponse( HttpURLConnection.HTTP_NOT_FOUND, "unable to find " + request.getURI() ); + // what resource could not be find? + String uri=request.getURI(); + // 404 - Not Found error code + int errorCode=HttpURLConnection.HTTP_NOT_FOUND; + // typical 404 error Message + String errorMessage="unable to find " + uri; + // make sure there is a resource and + // next time we'll take it from the resource Cache + resource=setErrorResource(uri, errorCode, errorMessage); + // set the errorCode for this response + response.setResponse(errorCode , errorMessage ); } else { - if (resource.closesConnection()) keepAlive = false; if (resource.getResponseCode() != HttpURLConnection.HTTP_OK) { response.setResponse( resource.getResponseCode(), "" ); - } - String[] headers = resource.getHeaders(); - for (int i = 0; i < headers.length; i++) { - debug( "Server thread sending header: " + headers[i] ); - response.addHeader( headers[i] ); - } + } } + if (resource.closesConnection()) keepAlive = false; + String[] headers = resource.getHeaders(); + for (int i = 0; i < headers.length; i++) { + debug( "Server thread sending header: " + headers[i] ); + response.addHeader( headers[i] ); + } } catch (UnknownMethodException e) { response.setResponse( HttpURLConnection.HTTP_BAD_METHOD, "unsupported method: " + e.getMethod() ); } catch (Throwable t) { t.printStackTrace(); response.setResponse( HttpURLConnection.HTTP_INTERNAL_ERROR, t.toString() ); } - try { response.write( resource ); } catch (IOException e) { System.out.println( "*** Failed to send reply: " + e ); } + try { + response.write( resource ); + } catch (IOException e) { + System.out.println( "*** Failed to send reply: " + e ); + } return keepAlive; } @@ -470,6 +503,11 @@ } + /** + * set the response to the given response Code + * @param responseCode + * @param responseText + */ void setResponse( int responseCode, String responseText ) { _responseCode = responseCode; _responseText = responseText; Modified: trunk/httpunit/test/com/meterware/httpunit/WebClientTest.java =================================================================== --- trunk/httpunit/test/com/meterware/httpunit/WebClientTest.java 2009-08-18 11:31:16 UTC (rev 1035) +++ trunk/httpunit/test/com/meterware/httpunit/WebClientTest.java 2009-08-18 16:08:16 UTC (rev 1036) @@ -72,6 +72,10 @@ } + /** + * check access to resources that are not defined + * @throws Exception + */ public void testNotFound() throws Exception { WebConversation wc = new WebConversation(); WebRequest request = new GetMethodWebRequest( getHostPath() + "/nothing.htm" ); @@ -81,8 +85,50 @@ } catch (HttpNotFoundException e) { assertEquals( "Response code", HttpURLConnection.HTTP_NOT_FOUND, e.getResponseCode() ); assertEquals( "Response message", "unable to find /nothing.htm", e.getResponseMessage() ); + assertEquals( "Response text","",e.getResponse().getText()); } } + + /** + * check access to undefined resources + * @throws IOException + */ + public void testUndefinedResource() throws IOException { + boolean originalState = HttpUnitOptions + .getExceptionsThrownOnErrorStatus(); + // try two cases for throwException true on i==0, false on i==1 + for (int i = 0; i <2; i++) { + boolean throwException = i == 0; + HttpUnitOptions.setExceptionsThrownOnErrorStatus(throwException); + WebResponse response = null; + try { + WebConversation wc = new WebConversation(); + WebRequest request = new GetMethodWebRequest(getHostPath() + + "/undefined"); + response = wc.getResponse(request); + if (throwException) { + fail("there should have been an exception here"); + } + } catch (HttpNotFoundException hnfe) { + assertTrue(throwException); + response=hnfe.getResponse(); + } catch (Exception e) { + fail("there should be no exception here"); + } + assertTrue(response != null); + assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response + .getResponseCode()); + if (throwException) { + assertEquals("with throwException="+throwException,"", response.getText()); + assertEquals("with throwException="+throwException,"unable to find /undefined",response.getResponseMessage()); + } else { + // FIXME what do we expect here and how do we get it! + assertEquals("with throwException="+throwException,"unable to find /undefined", response.getText()); + assertNull(response.getResponseMessage()); + } + } + HttpUnitOptions.setExceptionsThrownOnErrorStatus(originalState); + } public void testNotModifiedResponse() throws Exception { @@ -770,39 +816,6 @@ } /** - * check access to undefined resources - */ - public void testUndefinedResource() { - boolean originalState = HttpUnitOptions - .getExceptionsThrownOnErrorStatus(); - for (int i = 0; i < 1; i++) { - boolean throwException = i == 0; - HttpUnitOptions.setExceptionsThrownOnErrorStatus(throwException); - WebResponse response = null; - try { - WebConversation wc = new WebConversation(); - WebRequest request = new GetMethodWebRequest(getHostPath() - + "/undefined"); - response = wc.getResponse(request); - if (throwException) { - fail("there should have been an exception here"); - } - assertTrue(response != null); - assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response - .getResponseCode()); - assertEquals(0, response.getContentLength()); - } catch (Exception e) { - if (throwException) { - assertTrue(e instanceof HttpNotFoundException); - } else { - fail("there should be no exception here"); - } - } - } - HttpUnitOptions.setExceptionsThrownOnErrorStatus(originalState); - } - - /** * test for bug report [ 1283878 ] FileNotFoundException using Sun JDK 1.5 on empty error pages * by Roger Lindsj\xF6 * @throws Exception Modified: trunk/httpunit/test/com/meterware/httpunit/javascript/ScriptingTest.java =================================================================== --- trunk/httpunit/test/com/meterware/httpunit/javascript/ScriptingTest.java 2009-08-18 11:31:16 UTC (rev 1035) +++ trunk/httpunit/test/com/meterware/httpunit/javascript/ScriptingTest.java 2009-08-18 16:08:16 UTC (rev 1036) @@ -193,8 +193,59 @@ WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" ); response.getLinkWith( "go" ).click(); assertEquals( "Alert message", "Cheese!", wc.popNextAlert() ); - } + } + /** + * test Detection of Javascript files that can not be found + * behaviour pointed out by Dan Lipofsky + * @throws Exception + */ + public void testBadJavascriptFile() throws Exception { + // define xyz.js to create a 404 error + // we don't do this - it should be a default behaviour of the Pseudo Server! + // defineResource( "xyz.js", "File does not exist: xyz.js", 404); + defineResource("OnCommand.html", + "<html><head>" + + "<script language='JavaScript' src='xyz.js'></script></head>" + + "<body>Hello</body></html>" ); + boolean originalState = + HttpUnitOptions.getExceptionsThrownOnErrorStatus(); + boolean originalScriptState= + HttpUnitOptions.getExceptionsThrownOnScriptError(); + boolean oldDebug= HttpUnitUtils.setEXCEPTION_DEBUG(false); + + // make sure exceptions are thrown + HttpUnitOptions.setExceptionsThrownOnErrorStatus(false); + for (int i=0;i<2;i++) { + boolean throwScriptException=i==0; + HttpUnitOptions.setExceptionsThrownOnScriptError(throwScriptException); + HttpUnitOptions.clearScriptErrorMessages(); + WebConversation wc = new WebConversation(); + try { + WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" ); + // WebResponse response = wc.getResponse( getHostPath() + "/xyz.js" ); + // assertEquals( 404, response.getResponseCode() ); + if (throwScriptException) { + fail("there should have been an exception"); + } else { + String[] errMsgs = HttpUnitOptions.getScriptErrorMessages(); + assertTrue("There should be an error Message",errMsgs.length==1); + String errMsg=errMsgs[0]; + assertEquals(errMsg,"? failed: com.meterware.httpunit.ScriptException: unable to find /xyz.js"); + } + } catch (ScriptException se) { + assertTrue(throwScriptException); + } catch (Exception e) { + fail("there should be no exception when throwScriptException is "+throwScriptException); + } + } + // Restore exceptions state + HttpUnitOptions.setExceptionsThrownOnErrorStatus(originalState ); + HttpUnitOptions.setExceptionsThrownOnScriptError(originalScriptState); + HttpUnitUtils.setEXCEPTION_DEBUG(oldDebug); + } + + public void testJavaScriptURLInNewWindow() throws Exception { defineWebPage( "OnCommand", "<input type='button' id='nowindow' onClick='alert(\"hi\")'></input>\n" + "<input type='button' id='withwindow' onClick=\"window.open('javascript:alert(\\'hi\\')','_self')\"></input>" ); @@ -279,17 +330,20 @@ "<body>" + "<a href=\"javascript:sayCheese()\">go</a>" + "</body></html>" ); - HttpUnitOptions.setExceptionsThrownOnScriptError( true); - HttpUnitOptions.clearScriptErrorMessages(); WebConversation wc = new WebConversation(); + boolean oldDebug= HttpUnitUtils.setEXCEPTION_DEBUG(false); + HttpUnitOptions.setExceptionsThrownOnScriptError( false); WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" ); - boolean oldDebug= HttpUnitUtils.setEXCEPTION_DEBUG(false); try { + HttpUnitOptions.setExceptionsThrownOnScriptError( true); + HttpUnitOptions.clearScriptErrorMessages(); response.getLinkWith( "go" ).click(); fail("there should have been an exception"); - } catch (Throwable th) { + } catch (ScriptException se) { + fail("Runtime exception is appropriate in this test case since we ignored the loading error"); + } catch (RuntimeException rte) { // java.lang.RuntimeException: Error clicking link: com.meterware.httpunit.ScriptException: URL 'javascript:sayCheese()' failed: org.mozilla.javascript.EcmaError: ReferenceError: "sayCheese" is not defined. - assertTrue("is not defined should be found in message",th.getMessage().indexOf("not defined")>0); + assertTrue("is not defined should be found in message",rte.getMessage().indexOf("not defined")>0); } finally { HttpUnitUtils.setEXCEPTION_DEBUG(oldDebug); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <wol...@us...> - 2009-08-19 07:07:05
|
Revision: 1039 http://httpunit.svn.sourceforge.net/httpunit/?rev=1039&view=rev Author: wolfgang_fahl Date: 2009-08-19 07:06:57 +0000 (Wed, 19 Aug 2009) Log Message: ----------- modify message on failure of getIncludes Scripts via src attributes to make sure the message is the same on all setting of Exception and ScriptError status flags Modified Paths: -------------- trunk/httpunit/src/com/meterware/httpunit/ParsedHTML.java trunk/httpunit/src/com/meterware/httpunit/javascript/ScriptingEngineImpl.java trunk/httpunit/test/com/meterware/httpunit/javascript/ScriptingTest.java Modified: trunk/httpunit/src/com/meterware/httpunit/ParsedHTML.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/ParsedHTML.java 2009-08-18 17:16:34 UTC (rev 1038) +++ trunk/httpunit/src/com/meterware/httpunit/ParsedHTML.java 2009-08-19 07:06:57 UTC (rev 1039) @@ -410,8 +410,8 @@ } else { // in this case the text would be an error message // we do not return it but set the - ScriptException se=new ScriptException(response.getText()); - String badScript="?"; + ScriptException se=new ScriptException("reponseCode "+code+" on getIncludedScript for src='"+srcAttribute+"'"); + String badScript=null; // let scripting engine decide what to do with this exception (throw it or remember it ...) HttpUnitOptions.getScriptingEngine().handleScriptException(se, badScript); return ""; Modified: trunk/httpunit/src/com/meterware/httpunit/javascript/ScriptingEngineImpl.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/javascript/ScriptingEngineImpl.java 2009-08-18 17:16:34 UTC (rev 1038) +++ trunk/httpunit/src/com/meterware/httpunit/javascript/ScriptingEngineImpl.java 2009-08-19 07:06:57 UTC (rev 1039) @@ -39,6 +39,9 @@ private static ArrayList _errorMessages = new ArrayList(); + /** + * clear the list of error Messages + */ static public void clearErrorMessages() { _errorMessages.clear(); } @@ -59,7 +62,7 @@ * @param badScript - the script that caused the problem */ static public void handleScriptException( Exception e, String badScript ) { - final String errorMessage = badScript + " failed: " + e; + String errorMessage=badScript==null? e.getMessage():badScript + " failed: " + e; if (!(e instanceof EcmaError) && !(e instanceof EvaluatorException) && !(e instanceof ScriptException)) { HttpUnitUtils.handleException(e); Modified: trunk/httpunit/test/com/meterware/httpunit/javascript/ScriptingTest.java =================================================================== --- trunk/httpunit/test/com/meterware/httpunit/javascript/ScriptingTest.java 2009-08-18 17:16:34 UTC (rev 1038) +++ trunk/httpunit/test/com/meterware/httpunit/javascript/ScriptingTest.java 2009-08-19 07:06:57 UTC (rev 1039) @@ -23,6 +23,8 @@ import com.meterware.httpunit.*; import junit.framework.Assert; +import junit.framework.AssertionFailedError; +import junit.framework.ComparisonFailure; import junit.framework.TestSuite; import junit.textui.TestRunner; @@ -200,7 +202,7 @@ * behaviour pointed out by Dan Lipofsky * @throws Exception */ - public void testBadJavascriptFile() throws Exception { + public void testBadJavascriptFile() { // define xyz.js to create a 404 error // we don't do this - it should be a default behaviour of the Pseudo Server! // defineResource( "xyz.js", "File does not exist: xyz.js", 404); @@ -212,12 +214,16 @@ HttpUnitOptions.getExceptionsThrownOnErrorStatus(); boolean originalScriptState= HttpUnitOptions.getExceptionsThrownOnScriptError(); + // make sure stackTraces are not printed on Exceptions + // uncomment this if you'd actually like to debug the following code boolean oldDebug= HttpUnitUtils.setEXCEPTION_DEBUG(false); - - // make sure exceptions are thrown - HttpUnitOptions.setExceptionsThrownOnErrorStatus(false); - for (int i=0;i<2;i++) { - boolean throwScriptException=i==0; + AssertionFailedError failure=null; + // check 4 combinations of Exception and ScriptError status flags + for (int i=0;i<4;i++) { + boolean throwScriptException=(i%2)==0; // true on case 0 and 2 + boolean throwException=((i/2)%2)==0; // true on case 0 and 1 + String testDescription=("case "+i+" throwScriptException="+throwScriptException+" throwException="+throwException); + HttpUnitOptions.setExceptionsThrownOnErrorStatus(throwException); HttpUnitOptions.setExceptionsThrownOnScriptError(throwScriptException); HttpUnitOptions.clearScriptErrorMessages(); WebConversation wc = new WebConversation(); @@ -231,14 +237,19 @@ String[] errMsgs = HttpUnitOptions.getScriptErrorMessages(); assertTrue("There should be an error Message",errMsgs.length==1); String errMsg=errMsgs[0]; - assertEquals(errMsg,"? failed: com.meterware.httpunit.ScriptException: unable to find /xyz.js"); + assertEquals(testDescription,"reponseCode 404 on getIncludedScript for src='xyz.js'",errMsg); } } catch (ScriptException se) { assertTrue(throwScriptException); } catch (Exception e) { fail("there should be no exception when throwScriptException is "+throwScriptException); - } + } catch (AssertionFailedError afe) { + // continue looping on failed tests + failure=afe; + } } + if (failure!=null) + throw(failure); // Restore exceptions state HttpUnitOptions.setExceptionsThrownOnErrorStatus(originalState ); HttpUnitOptions.setExceptionsThrownOnScriptError(originalScriptState); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <wol...@us...> - 2009-08-19 09:01:01
|
Revision: 1040 http://httpunit.svn.sourceforge.net/httpunit/?rev=1040&view=rev Author: wolfgang_fahl Date: 2009-08-19 09:00:49 +0000 (Wed, 19 Aug 2009) Log Message: ----------- add test for HeadMethodWebRequest by Dan Lipofsky and fix the PseudoServer accordingly. Make sure GetMethodWebRequest sets the method attribute in the superClass. Modified Paths: -------------- trunk/httpunit/src/com/meterware/httpunit/GetMethodWebRequest.java trunk/httpunit/src/com/meterware/httpunit/HeadMethodWebRequest.java trunk/httpunit/src/com/meterware/httpunit/HeaderOnlyWebRequest.java trunk/httpunit/src/com/meterware/httpunit/WebRequest.java trunk/httpunit/src/com/meterware/pseudoserver/PseudoServer.java trunk/httpunit/test/com/meterware/httpunit/WebPageTest.java Modified: trunk/httpunit/src/com/meterware/httpunit/GetMethodWebRequest.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/GetMethodWebRequest.java 2009-08-19 07:06:57 UTC (rev 1039) +++ trunk/httpunit/src/com/meterware/httpunit/GetMethodWebRequest.java 2009-08-19 09:00:49 UTC (rev 1040) @@ -24,16 +24,52 @@ import java.net.URL; /** - * An HTTP request using the GET method. + * An HTTP request using the GET method. + * RFC 2616 http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html defines: + * + * 9.3 GET + * + * The GET method means retrieve whatever information (in the form of an entity) + * is identified by the Request-URI. If the Request-URI refers to a + * data-producing process, it is the produced data which shall be returned as + * the entity in the response and not the source text of the process, unless + * that text happens to be the output of the process. + * + * The semantics of the GET method change to a "conditional GET" if the request + * message includes an If-Modified-Since, If-Unmodified-Since, If-Match, + * If-None-Match, or If-Range header field. A conditional GET method requests + * that the entity be transferred only under the circumstances described by the + * conditional header field(s). The conditional GET method is intended to reduce + * unnecessary network usage by allowing cached entities to be refreshed without + * requiring multiple requests or transferring data already held by the client. + * + * The semantics of the GET method change to a "partial GET" if the request + * message includes a Range header field. A partial GET requests that only part + * of the entity be transferred, as described in section 14.35. The partial GET + * method is intended to reduce unnecessary network usage by allowing + * partially-retrieved entities to be completed without transferring data + * already held by the client. + * + * The response to a GET request is cacheable if and only if it meets the + * requirements for HTTP caching described in section 13. + * + * See section 15.1.3 for security considerations when used for forms. **/ public class GetMethodWebRequest extends HeaderOnlyWebRequest { + /** + * initialize me - set method to GET + */ + private void init() { + super.setMethod("GET"); + } /** * Constructs a web request using a specific absolute url string. **/ public GetMethodWebRequest( String urlString ) { super( urlString ); + init(); } @@ -42,6 +78,7 @@ **/ public GetMethodWebRequest( URL urlBase, String urlString ) { super( urlBase, urlString ); + init(); } @@ -50,17 +87,10 @@ **/ public GetMethodWebRequest( URL urlBase, String urlString, String target ) { super( urlBase, urlString, target ); + init(); } - /** - * Returns the HTTP method defined for this request. - **/ - public String getMethod() { - return "GET"; - } - - //--------------------------------------- package members --------------------------------------------- @@ -69,6 +99,7 @@ **/ GetMethodWebRequest( WebForm sourceForm ) { super( sourceForm ); + init(); } @@ -77,6 +108,7 @@ **/ GetMethodWebRequest( FixedURLWebRequestSource source ) { super( source ); + init(); } @@ -85,6 +117,7 @@ **/ GetMethodWebRequest( WebResponse referer, Element sourceElement, URL urlBase, String urlString, String target ) { super( referer, sourceElement, urlBase, urlString, target ); + init(); } @@ -93,6 +126,7 @@ **/ GetMethodWebRequest( URL urlBase, String urlString, FrameSelector frame ) { super( urlBase, urlString, frame ); + init(); } @@ -101,6 +135,7 @@ **/ GetMethodWebRequest( URL urlBase, String urlString, FrameSelector frame, String target ) { super( urlBase, urlString, frame, target ); + init(); } @@ -109,11 +144,8 @@ **/ GetMethodWebRequest( WebForm sourceForm, ParameterHolder parameterHolder, SubmitButton button, int x, int y ) { super( sourceForm, parameterHolder, button, x, y ); + init(); } -} - - - - +} \ No newline at end of file Modified: trunk/httpunit/src/com/meterware/httpunit/HeadMethodWebRequest.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/HeadMethodWebRequest.java 2009-08-19 07:06:57 UTC (rev 1039) +++ trunk/httpunit/src/com/meterware/httpunit/HeadMethodWebRequest.java 2009-08-19 09:00:49 UTC (rev 1040) @@ -24,31 +24,61 @@ *******************************************************************************************************************/ /** - * A web request using the HEAD method. This request is used to obtain header information for a resource - * without necessarily waiting for the data to be computed or transmitted. - * + * A web request using the HEAD method. This request is used to obtain header + * information for a resource without necessarily waiting for the data to be + * computed or transmitted. + * + * RFC 2616 http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html defines: + * 9.4 HEAD + * + * The HEAD method is identical to GET except that the server MUST NOT return a + * message-body in the response. The metainformation contained in the HTTP + * headers in response to a HEAD request SHOULD be identical to the information + * sent in response to a GET request. This method can be used for obtaining + * metainformation about the entity implied by the request without transferring + * the entity-body itself. This method is often used for testing hypertext links + * for validity, accessibility, and recent modification. + * + * The response to a HEAD request MAY be cacheable in the sense that the + * information contained in the response MAY be used to update a previously + * cached entity from that resource. If the new field values indicate that the + * cached entity differs from the current entity (as would be indicated by a + * change in Content-Length, Content-MD5, ETag or Last-Modified), then the cache + * MUST treat the cache entry as stale. + * * @author <a href="mailto:rus...@ht...">Russell Gold</a> - **/ + **/ public class HeadMethodWebRequest extends HeaderOnlyWebRequest { - /** - * Creates a new head request from a complete URL string. - * @param urlString the URL desired, including the protocol. - */ - public HeadMethodWebRequest( String urlString ) { - super( urlString ); - this.setMethod("HEAD"); - } + /** + * initialize me - set method to HEAD + */ + private void init() { + super.setMethod("HEAD"); + } + + /** + * Creates a new head request from a complete URL string. + * + * @param urlString + * the URL desired, including the protocol. + */ + public HeadMethodWebRequest(String urlString) { + super(urlString); + init(); + } + /** + * Creates a new head request using a relative URL and base. + * + * @param urlBase + * the base URL. + * @param urlString + * the relative URL + */ + public HeadMethodWebRequest(URL urlBase, String urlString) { + super(urlBase, urlString); + init(); + } - /** - * Creates a new head request using a relative URL and base. - * @param urlBase the base URL. - * @param urlString the relative URL - */ - public HeadMethodWebRequest( URL urlBase, String urlString ) { - super( urlBase, urlString ); - this.setMethod("HEAD"); - } - } Modified: trunk/httpunit/src/com/meterware/httpunit/HeaderOnlyWebRequest.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/HeaderOnlyWebRequest.java 2009-08-19 07:06:57 UTC (rev 1039) +++ trunk/httpunit/src/com/meterware/httpunit/HeaderOnlyWebRequest.java 2009-08-19 09:00:49 UTC (rev 1040) @@ -50,11 +50,11 @@ } /** - * @param method the method to set - */ - public void setMethod(String method) { - this.method = method; - } + * @param method the method to set + */ + public void setMethod(String method) { + this.method = method; + } //-------------------------------- protected members --------------------------- Modified: trunk/httpunit/src/com/meterware/httpunit/WebRequest.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/WebRequest.java 2009-08-19 07:06:57 UTC (rev 1039) +++ trunk/httpunit/src/com/meterware/httpunit/WebRequest.java 2009-08-19 09:00:49 UTC (rev 1040) @@ -189,12 +189,12 @@ protected String method; - /** - * @return the method - */ - public String getMethod() { - return method; - } + /** + * @return the method + */ + public String getMethod() { + return method; + } /** Modified: trunk/httpunit/src/com/meterware/pseudoserver/PseudoServer.java =================================================================== --- trunk/httpunit/src/com/meterware/pseudoserver/PseudoServer.java 2009-08-19 07:06:57 UTC (rev 1039) +++ trunk/httpunit/src/com/meterware/pseudoserver/PseudoServer.java 2009-08-19 09:00:49 UTC (rev 1040) @@ -404,11 +404,21 @@ } + /** + * get the resource for the given request by first trying to look it up in the cache + * then depending on the type of request PseudoServlet and the method / command e.g. GET/HEAD + * finally the extension of the uri ".zip" ".class" and ".jar" are handled + * @param request + * @return the WebResource or null if non of the recipes above will lead to a valid resource + * @throws IOException + */ private WebResource getResource( HttpRequest request ) throws IOException { Object resource = _resources.get( request.getURI() ); if (resource == null) resource = _resources.get( withoutParameters( request.getURI() ) ); - if (request.getCommand().equals( "GET" ) && resource instanceof WebResource) { + // check the method of the request + String command=request.getCommand(); + if ((command.equals( "GET" ) || command.equals("HEAD")) && resource instanceof WebResource) { return (WebResource) resource; } else if (resource instanceof PseudoServlet) { return getResource( (PseudoServlet) resource, request ); Modified: trunk/httpunit/test/com/meterware/httpunit/WebPageTest.java =================================================================== --- trunk/httpunit/test/com/meterware/httpunit/WebPageTest.java 2009-08-19 07:06:57 UTC (rev 1039) +++ trunk/httpunit/test/com/meterware/httpunit/WebPageTest.java 2009-08-19 09:00:49 UTC (rev 1040) @@ -153,8 +153,29 @@ assertNotNull( "No DOM created for document", dom ); assertTrue( "returned dom does not implement HTMLDocument, but is " + dom.getClass().getName(), dom instanceof HTMLDocument ); } + + /** + * add test for HeadMethodWebRequest + * @author Dan Lipofsky 2009-08-19 + * @throws Exception + */ + public void testHeadMethodWebRequest() throws Exception { + defineResource( "SimplePage.html", + "<html><head><title>A Sample Page</title></head>\n" + + "<body>Hello</body></html>\n" ); + HttpUnitOptions.setExceptionsThrownOnErrorStatus(true); + WebConversation wc = new WebConversation(); + // create a HeadMethodWebRequest + // see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html for definition + WebRequest request = new HeadMethodWebRequest( getHostPath() + "/SimplePage.html" ); + WebResponse simplePage = wc.getResponse( request ); + String text=simplePage.getText(); + // no body should be returned + assertEquals("",text); + } + public void testTitle() throws Exception { defineResource( "SimplePage.html", "<html><head><title>A Sample Page</title></head>\n" + This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <wol...@us...> - 2009-08-20 07:07:36
|
Revision: 1042 http://httpunit.svn.sourceforge.net/httpunit/?rev=1042&view=rev Author: wolfgang_fahl Date: 2009-08-20 07:07:28 +0000 (Thu, 20 Aug 2009) Log Message: ----------- proposed fix for BR 2407470 Regression in httpUnit-1.7 by redsonic with Patch from Adam Heath Modified Paths: -------------- trunk/httpunit/src/com/meterware/httpunit/HttpUnitOptions.java trunk/httpunit/src/com/meterware/httpunit/ParsedHTML.java trunk/httpunit/test/com/meterware/httpunit/WebFormTest.java Modified: trunk/httpunit/src/com/meterware/httpunit/HttpUnitOptions.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/HttpUnitOptions.java 2009-08-19 10:08:00 UTC (rev 1041) +++ trunk/httpunit/src/com/meterware/httpunit/HttpUnitOptions.java 2009-08-20 07:07:28 UTC (rev 1042) @@ -450,10 +450,13 @@ /** * Determines whether script errors result in exceptions or warning messages. + * @return the current state */ - public static void setExceptionsThrownOnScriptError( boolean throwExceptions ) { + public static boolean setExceptionsThrownOnScriptError( boolean throwExceptions ) { + boolean current=_exceptionsThrownOnScriptError; _exceptionsThrownOnScriptError = throwExceptions; getScriptingEngine().setThrowExceptionsOnError( throwExceptions ); + return current; } Modified: trunk/httpunit/src/com/meterware/httpunit/ParsedHTML.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/ParsedHTML.java 2009-08-19 10:08:00 UTC (rev 1041) +++ trunk/httpunit/src/com/meterware/httpunit/ParsedHTML.java 2009-08-20 07:07:28 UTC (rev 1042) @@ -97,6 +97,7 @@ * @return an array of objects representing the forms in the page or portion of a page. **/ public WebForm[] getForms() { + loadElements(); HTMLCollection forms = ((HTMLContainerElement) _rootNode).getForms(); WebForm[] result = new WebForm[ forms.getLength() ]; for (int i = 0; i < result.length; i++) { @@ -116,6 +117,7 @@ * Returns the links found in the page in the order in which they appear. **/ public WebLink[] getLinks() { + loadElements(); HTMLCollection links = ((HTMLContainerElement) _rootNode).getLinks(); WebLink[] result = new WebLink[ links.getLength() ]; for (int i = 0; i < result.length; i++) { @@ -133,6 +135,7 @@ * Returns a proxy for each applet found embedded in this page. */ public WebApplet[] getApplets() { + loadElements(); HTMLCollection applets = ((HTMLContainerElement) _rootNode).getApplets(); WebApplet[] result = new WebApplet[ applets.getLength() ]; for (int i = 0; i < result.length; i++) { @@ -150,6 +153,7 @@ * Returns the images found in the page in the order in which they appear. */ public WebImage[] getImages() { + loadElements(); HTMLCollection images = ((HTMLContainerElement) _rootNode).getImages(); WebImage[] result = new WebImage[ images.getLength() ]; for (int i = 0; i < result.length; i++) { @@ -167,6 +171,7 @@ * Returns the top-level block elements found in the page in the order in which they appear. */ public TextBlock[] getTextBlocks() { + loadElements(); if (_blocks == null) { loadElements(); _blocks = (TextBlock[]) _blocksList.toArray( new TextBlock[ _blocksList.size() ] ); @@ -179,6 +184,7 @@ * Returns the first text block found in the page which matches the specified predicate and value. */ public TextBlock getFirstMatchingTextBlock( HTMLElementPredicate predicate, Object criteria ) { + loadElements(); TextBlock[] blocks = getTextBlocks(); for (int i = 0; i < blocks.length; i++) { if (predicate.matchesCriteria( blocks[i], criteria )) return blocks[i]; @@ -187,7 +193,13 @@ } + /** + * get the next text block based on the given block + * @param block + * @return - the next text block + */ public TextBlock getNextTextBlock( TextBlock block ) { + loadElements(); int index = _blocksList.indexOf( block ); if (index < 0 || index == _blocksList.size() - 1) return null; return (TextBlock) _blocksList.get( index+1 ); @@ -196,8 +208,10 @@ /** * Returns the top-level tables found in the page in the order in which they appear. + * @return an array of tables **/ public WebTable[] getTables() { + loadElements(); if (_tables == null) { loadElements(); _tables = (WebTable[]) _tableList.toArray( new WebTable[ _tableList.size() ] ); Modified: trunk/httpunit/test/com/meterware/httpunit/WebFormTest.java =================================================================== --- trunk/httpunit/test/com/meterware/httpunit/WebFormTest.java 2009-08-19 10:08:00 UTC (rev 1041) +++ trunk/httpunit/test/com/meterware/httpunit/WebFormTest.java 2009-08-20 07:07:28 UTC (rev 1042) @@ -65,6 +65,38 @@ "</form>" ); } + /** + * placeholder for test for BR 2407470 by redsonic with comment and patch by Adam Heath + * + */ + public void testGetFormWithID() throws Exception { + defineWebPage( "OnCommand", + "<html>\n"+ + " <head>\n"+ + " <script type='JavaScript'>\n" + + " function function1() {\n"+ + " alert( document.forms[0].name );\n" + + " }\n"+ + " </script>\n" + + " </head>\n" + + " <body>\n"+ + " <form id='form1' name='form1name'/>\n" + + " <form id='form2' name='form2name'/>\n" + + " <form id='form3' name='form3name'/>\n" + + " <body>\n"+ + "</html>\n"); + boolean oldstate = HttpUnitOptions.setExceptionsThrownOnScriptError(false); + try { + WebConversation wc = new WebConversation(); + WebResponse wr=wc.getResponse( getHostPath() + "/OnCommand.html" ); + WebForm form = wr.getFormWithID( "form3" ); + assertTrue(form!=null); + } catch (Exception ex) { + throw ex; + } finally { + HttpUnitOptions.setExceptionsThrownOnScriptError(oldstate); + } + } public void testSubmitFromForm() throws Exception { defineWebPage( "Form", "<form method=GET id=main action = 'tryMe'>" + This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <wol...@us...> - 2009-08-20 08:44:07
|
Revision: 1043 http://httpunit.svn.sourceforge.net/httpunit/?rev=1043&view=rev Author: wolfgang_fahl Date: 2009-08-20 08:43:55 +0000 (Thu, 20 Aug 2009) Log Message: ----------- getBytes added to WebResponse according to a CR by Oliver Wahlen getDownload helper function is superfluous now Modified Paths: -------------- trunk/httpunit/src/com/meterware/httpunit/WebResponse.java trunk/httpunit/src/com/meterware/pseudoserver/HttpUserAgentTest.java trunk/httpunit/test/com/meterware/httpunit/MessageBodyRequestTest.java Modified: trunk/httpunit/src/com/meterware/httpunit/WebResponse.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/WebResponse.java 2009-08-20 07:07:28 UTC (rev 1042) +++ trunk/httpunit/src/com/meterware/httpunit/WebResponse.java 2009-08-20 08:43:55 UTC (rev 1043) @@ -276,10 +276,21 @@ abstract public String getHeaderField( String fieldName ); - /** + * Returns the actual byte stream of the response e.g. for download results + * @return the byte array read for this response + * @throws IOException + */ + public byte[] getBytes() throws IOException { + if (_responseText == null) + loadResponseText(); + return _bytes; + } + + /** * 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. + * @return the response text **/ public String getText() throws IOException { if (_responseText == null) @@ -1055,7 +1066,15 @@ private int _refreshDelay = -1; // initialized to invalid value + /** + * the response as a String + */ private String _responseText; + + /** + * the response as a byte array + */ + private byte[] _bytes; private InputStream _inputStream; @@ -1082,15 +1101,15 @@ try { final int contentLength = this.encodedUsingGZIP() ? -1 : getContentLength(); int bytesRemaining = contentLength < 0 ? Integer.MAX_VALUE : contentLength; - byte[] bytes = readFromStream( inputStream, bytesRemaining ); + _bytes = readFromStream( inputStream, bytesRemaining ); - readTags( bytes ); - _responseText = new String( bytes, getCharacterSet() ); - _inputStream = new ByteArrayInputStream( bytes ); + readTags( _bytes ); + _responseText = new String( _bytes, getCharacterSet() ); + _inputStream = new ByteArrayInputStream( _bytes ); - if (HttpUnitOptions.isCheckContentLength() && contentLength >= 0 && bytes.length != contentLength) { + if (HttpUnitOptions.isCheckContentLength() && contentLength >= 0 && _bytes.length != contentLength) { throw new IOException("Truncated message. Expected length: " + contentLength + - ", Actual length: " + bytes.length); + ", Actual length: " + _bytes.length); } } finally { inputStream.close(); Modified: trunk/httpunit/src/com/meterware/pseudoserver/HttpUserAgentTest.java =================================================================== --- trunk/httpunit/src/com/meterware/pseudoserver/HttpUserAgentTest.java 2009-08-20 07:07:28 UTC (rev 1042) +++ trunk/httpunit/src/com/meterware/pseudoserver/HttpUserAgentTest.java 2009-08-20 08:43:55 UTC (rev 1043) @@ -255,9 +255,7 @@ protected void assertEquals( String comment, byte[] expected, byte[] actual ) { - if (!equals( expected, actual )) { - fail( comment + " expected:\n" + toString( expected ) + ", but was:\n" + toString( actual ) ); - } + assertEquals(comment,toString(expected),toString(actual)); } Modified: trunk/httpunit/test/com/meterware/httpunit/MessageBodyRequestTest.java =================================================================== --- trunk/httpunit/test/com/meterware/httpunit/MessageBodyRequestTest.java 2009-08-20 07:07:28 UTC (rev 1042) +++ trunk/httpunit/test/com/meterware/httpunit/MessageBodyRequestTest.java 2009-08-20 08:43:55 UTC (rev 1043) @@ -1,24 +1,25 @@ package com.meterware.httpunit; + /******************************************************************************************************************** -* $Id$ -* -* 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 -* 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. -* -*******************************************************************************************************************/ + * $Id$ + * + * 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 + * 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 com.meterware.pseudoserver.PseudoServlet; import com.meterware.pseudoserver.WebResource; @@ -30,109 +31,142 @@ import junit.framework.Test; import junit.framework.TestSuite; - /** * A unit test to verify miscellaneous requests with message bodies. **/ public class MessageBodyRequestTest extends HttpUnitTest { - public static void main(String args[]) { - junit.textui.TestRunner.run( suite() ); - } - - - public static Test suite() { - return new TestSuite( MessageBodyRequestTest.class ); - } + public static void main(String args[]) { + junit.textui.TestRunner.run(suite()); + } + public static Test suite() { + return new TestSuite(MessageBodyRequestTest.class); + } - public MessageBodyRequestTest( String name ) { - super( name ); - } + public MessageBodyRequestTest(String name) { + super(name); + } + public void setUp() throws Exception { + super.setUp(); + } - public void setUp() throws Exception { - super.setUp(); - } - - - public void testGenericPostRequest() throws Exception { - defineResource( "ReportData", new BodyEcho() ); - String sourceData = "This is an interesting test\nWith two lines"; - InputStream source = new ByteArrayInputStream( sourceData.getBytes( "iso-8859-1" ) ); + public void testGenericPostRequest() throws Exception { + defineResource("ReportData", new BodyEcho()); + String sourceData = "This is an interesting test\nWith two lines"; + InputStream source = new ByteArrayInputStream(sourceData + .getBytes("iso-8859-1")); - WebConversation wc = new WebConversation(); - WebRequest wr = new PostMethodWebRequest( getHostPath() + "/ReportData", source, "text/sample" ); - WebResponse response = wc.getResponse( wr ); - assertEquals( "Body response", "\nPOST\n" + sourceData, response.getText() ); - assertEquals( "Content-type", "text/sample", response.getContentType() ); - } + WebConversation wc = new WebConversation(); + WebRequest wr = new PostMethodWebRequest(getHostPath() + "/ReportData", + source, "text/sample"); + WebResponse response = wc.getResponse(wr); + assertEquals("Body response", "\nPOST\n" + sourceData, response + .getText()); + assertEquals("Content-type", "text/sample", response.getContentType()); + } + public void testPutRequest() throws Exception { + defineResource("ReportData", new BodyEcho()); + String sourceData = "This is an interesting test\nWith two lines"; + InputStream source = new ByteArrayInputStream(sourceData + .getBytes("iso-8859-1")); - public void testPutRequest() throws Exception { - defineResource( "ReportData", new BodyEcho() ); - String sourceData = "This is an interesting test\nWith two lines"; - InputStream source = new ByteArrayInputStream( sourceData.getBytes( "iso-8859-1" ) ); + WebConversation wc = new WebConversation(); + WebRequest wr = new PutMethodWebRequest(getHostPath() + "/ReportData", + source, "text/plain"); + WebResponse response = wc.getResponse(wr); + assertEquals("Body response", "\nPUT\n" + sourceData, response + .getText()); + } - WebConversation wc = new WebConversation(); - WebRequest wr = new PutMethodWebRequest( getHostPath() + "/ReportData", source, "text/plain" ); - WebResponse response = wc.getResponse( wr ); - assertEquals( "Body response", "\nPUT\n" + sourceData, response.getText() ); - } + /** + * test for download problem described by Oliver Wahlen + */ + public void testDownloadRequestUsingGetText() throws Exception { + defineResource( "ReportData", new BodyEcho() ); + byte[] binaryData = new byte[256]; + for(int i=0;i<=255;i++) { + binaryData[i] = (byte)i; + } + InputStream source = new ByteArrayInputStream( binaryData ); - public void testDownloadRequest() throws Exception { - defineResource( "ReportData", new BodyEcho() ); - byte[] binaryData = new byte[] { 0x01, 0x05, 0x0d, 0x0a, 0x02 }; + WebConversation wc = new WebConversation(); + WebRequest wr = new PutMethodWebRequest( getHostPath() + "/ReportData", source, "application/random" ); + WebResponse response = wc.getResponse( wr ); + // currently the following line does not work: + byte[] download = response.getText().getBytes(); + // currently the following line works: + // byte[] download = getDownload( response ); + // and this one is now available ... + download=response.getBytes(); + assertEquals("Body response", binaryData, download); + } + + public void testDownloadRequest() throws Exception { + defineResource("ReportData", new BodyEcho()); + byte[] binaryData = new byte[] { 0x01, 0x05, 0x0d, 0x0a, 0x02 }; - InputStream source = new ByteArrayInputStream( binaryData ); + InputStream source = new ByteArrayInputStream(binaryData); - WebConversation wc = new WebConversation(); - WebRequest wr = new PutMethodWebRequest( getHostPath() + "/ReportData", source, "application/random" ); - WebResponse response = wc.getResponse( wr ); + WebConversation wc = new WebConversation(); + WebRequest wr = new PutMethodWebRequest(getHostPath() + "/ReportData", + source, "application/random"); + WebResponse response = wc.getResponse(wr); + byte[] download = response.getBytes(); + assertEquals("Body response", binaryData, download); - byte[] download = getDownload( response ); - assertEquals( "Body response", binaryData, download ); - } - - /** - * test for BR [ 1964665 ] HeaderOnlyRequest cannot be constructed - */ - public void testHeaderOnlyWebRequest() throws Exception { - HeaderOnlyWebRequest r = new HeaderOnlyWebRequest("http://www.google.com"); - } + download = getDownload(response); + assertEquals("Body response", binaryData, download); + + download = response.getBytes(); + assertEquals("Body response", binaryData, download); + } + /** + * test for BR [ 1964665 ] HeaderOnlyRequest cannot be constructed + */ + public void testHeaderOnlyWebRequest() throws Exception { + HeaderOnlyWebRequest r = new HeaderOnlyWebRequest( + "http://www.google.com"); + } - private byte[] getDownload( WebResponse response ) throws IOException { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - InputStream inputStream = response.getInputStream(); + /** + * please do not copy this function any more - use getBytes instead ... + * @param response + * @return + * @throws IOException + */ + 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); + 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(); - } + inputStream.close(); + return outputStream.toByteArray(); + } - } - class BodyEcho extends PseudoServlet { - /** - * 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 ); - } - } + /** + * 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); + } + } } - This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <wol...@us...> - 2009-08-20 12:02:34
|
Revision: 1047 http://httpunit.svn.sourceforge.net/httpunit/?rev=1047&view=rev Author: wolfgang_fahl Date: 2009-08-20 12:02:21 +0000 (Thu, 20 Aug 2009) Log Message: ----------- Patch by Antoine Vernois: it implements getServerName() and getServerPort of ServletUnitHttpRequest. ServerName and ServerPort are extracted from request's URL instead of always returning localhost and 0. Modified Paths: -------------- trunk/httpunit/src/com/meterware/servletunit/ServletUnitHttpRequest.java trunk/httpunit/test/com/meterware/servletunit/HttpServletRequestTest.java Modified: trunk/httpunit/src/com/meterware/servletunit/ServletUnitHttpRequest.java =================================================================== --- trunk/httpunit/src/com/meterware/servletunit/ServletUnitHttpRequest.java 2009-08-20 11:31:40 UTC (rev 1046) +++ trunk/httpunit/src/com/meterware/servletunit/ServletUnitHttpRequest.java 2009-08-20 12:02:21 UTC (rev 1047) @@ -56,7 +56,8 @@ private boolean _gotReader; private boolean _gotInputStream; private BufferedReader _reader; - + private int _serverPort; + private String _serverName; /** @@ -75,6 +76,11 @@ _messageBody = messageBody; _protocol=request.getURL().getProtocol().toLowerCase(); _secure = _protocol.endsWith("s" ); + _serverName = request.getURL().getHost(); + _serverPort = request.getURL().getPort(); + if ( _serverPort == -1 ) { + _serverPort = request.getURL().getDefaultPort(); + } _requestContext = new RequestContext( request.getURL() ); String contentTypeHeader = (String) _headers.get( "Content-Type" ); @@ -472,7 +478,7 @@ * Returns the host name of the server that received the request. **/ public String getServerName() { - return "localhost"; + return _serverName; } @@ -480,7 +486,7 @@ * Returns the port number on which this request was received. **/ public int getServerPort() { - return 0; + return _serverPort; } Modified: trunk/httpunit/test/com/meterware/servletunit/HttpServletRequestTest.java =================================================================== --- trunk/httpunit/test/com/meterware/servletunit/HttpServletRequestTest.java 2009-08-20 11:31:40 UTC (rev 1046) +++ trunk/httpunit/test/com/meterware/servletunit/HttpServletRequestTest.java 2009-08-20 12:02:21 UTC (rev 1047) @@ -2,7 +2,7 @@ /******************************************************************************************************************** * $Id$ * -* Copyright (c) 2000-2008 by Russell Gold +* Copyright (c) 2000-2009 by 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 @@ -714,10 +714,9 @@ /** * test the reader with a Specific Character set (here UTF-8) * @throws Exception - * TODO make work an switch back on + * FIXME make work an switch back on */ public void xtestGetReaderSpecificCharset() throws Exception { - //String body = "東京"; String body = "\u05d0\u05d1\u05d2\u05d3"; InputStream stream = new ByteArrayInputStream( body.getBytes( "UTF-8" ) ); WebRequest wr = new PostMethodWebRequest( "http://localhost/simple", stream, "text/plain; charset=UTF-8" ); @@ -771,7 +770,40 @@ assertEquals( "param2 value", hebrewValue, request.getParameter( "param2") ); } + /** + * test for getServerPort and getServerName by Antoine Vernois + * @throws Exception + */ + public void testDefaultHttpServerPort() throws Exception { + WebRequest wr = new GetMethodWebRequest( "http://localhost/simple" ); + HttpServletRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), NO_MESSAGE_BODY ); + int serverPort = request.getServerPort(); + assertEquals( "default http server port", serverPort, 80 ); + } + /** + * test for getServerPort and getServerName by Antoine Vernois + * @throws Exception + */ + public void testSuppliedHttpServerPort() throws Exception { + WebRequest wr = new GetMethodWebRequest( "http://localhost:8080/simple" ); + HttpServletRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), NO_MESSAGE_BODY ); + int serverPort = request.getServerPort(); + assertEquals( "supplied http server port", serverPort, 8080 ); + } + + /** + * test for getServerPort and getServerName by Antoine Vernois + * @throws Exception + */ + public void testServerName() throws Exception { + WebRequest wr = new GetMethodWebRequest( "http://myhost:8080/simple" ); + HttpServletRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), NO_MESSAGE_BODY ); + String serverName = request.getServerName(); + assertEquals( "server name", serverName, "myhost" ); + } + + private final static byte[] NO_MESSAGE_BODY = new byte[0]; private final static ServletMetaData NULL_SERVLET_REQUEST = new ServletMetaData() { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <wol...@us...> - 2009-08-20 13:22:37
|
Revision: 1048 http://httpunit.svn.sourceforge.net/httpunit/?rev=1048&view=rev Author: wolfgang_fahl Date: 2009-08-20 12:14:08 +0000 (Thu, 20 Aug 2009) Log Message: ----------- Patch by Rick Huff: to implement the getElementsWithClassName() method. This method returns those nodes where there are more than one class name on the element. Modified Paths: -------------- trunk/httpunit/src/com/meterware/httpunit/ParsedHTML.java trunk/httpunit/src/com/meterware/httpunit/WebResponse.java trunk/httpunit/test/com/meterware/httpunit/WebPageTest.java Modified: trunk/httpunit/src/com/meterware/httpunit/ParsedHTML.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/ParsedHTML.java 2009-08-20 12:02:21 UTC (rev 1047) +++ trunk/httpunit/src/com/meterware/httpunit/ParsedHTML.java 2009-08-20 12:14:08 UTC (rev 1048) @@ -66,6 +66,9 @@ /** map of element names to lists of elements. **/ private HashMap _elementsByName = new HashMap(); + + /** map of element class to elements. **/ + private HashMap _elementsByClass = new HashMap(); /** map of DOM elements to HTML elements **/ private ElementRegistry _registry = new ElementRegistry(); @@ -237,7 +240,16 @@ return elements == null ? NO_ELEMENTS : (HTMLElement[]) elements.toArray( new HTMLElement[ elements.size() ] ); } + /** + * Returns the HTML elements with the specified class. + */ + public HTMLElement[] getElementsWithClassName( String className ) { + loadElements(); + ArrayList elements = (ArrayList) _elementsByClass.get( className ); + return elements == null ? NO_ELEMENTS : (HTMLElement[]) elements.toArray( new HTMLElement[ elements.size() ] ); + } + /** * Returns the HTML elements with an attribute with the specified name and value. * @param name - the name of the attribute to check @@ -889,6 +901,22 @@ _registry.registerElement( node, htmlElement ); if (htmlElement.getID() != null) _elementsByID.put( htmlElement.getID(), htmlElement ); if (htmlElement.getName() != null) addNamedElement( htmlElement.getName(), htmlElement ); + if (htmlElement.getClassName() != null) { + StringTokenizer tokenizer = new StringTokenizer(htmlElement.getClassName()); + String token; + + while(tokenizer.hasMoreElements()) { + token = tokenizer.nextToken(); + + if ( _elementsByClass.containsKey( token )) { + ((ArrayList) _elementsByClass.get( token )).add( htmlElement ); + } else { + ArrayList arrayList = new ArrayList(); + arrayList.add(htmlElement); + _elementsByClass.put( token, arrayList ); + } + } + } } Modified: trunk/httpunit/src/com/meterware/httpunit/WebResponse.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/WebResponse.java 2009-08-20 12:02:21 UTC (rev 1047) +++ trunk/httpunit/src/com/meterware/httpunit/WebResponse.java 2009-08-20 12:14:08 UTC (rev 1048) @@ -387,8 +387,14 @@ return getReceivedPage().getElementsWithName( name ); } - /** + * Returns the HTMLElements found in this segment with the specified class. + */ + public HTMLElement[] getElementsWithClassName( String className ) throws SAXException { + return getReceivedPage().getElementsWithClassName( className ); + } + + /** * Returns the HTMLElements found with the specified attribute value. * @since 1.6 */ Modified: trunk/httpunit/test/com/meterware/httpunit/WebPageTest.java =================================================================== --- trunk/httpunit/test/com/meterware/httpunit/WebPageTest.java 2009-08-20 12:02:21 UTC (rev 1047) +++ trunk/httpunit/test/com/meterware/httpunit/WebPageTest.java 2009-08-20 12:14:08 UTC (rev 1048) @@ -2,7 +2,7 @@ /******************************************************************************************************************** * $Id$ * -* Copyright (c) 2000-2007, Russell Gold +* Copyright (c) 2000-2009, 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 @@ -459,6 +459,26 @@ } /** + * test for getElementsWithClassName supplied by Rick Huff + * @throws Exception + */ + public void testGetElementsWithClassName() throws Exception { + defineResource( "SimplePage.html", + "<html><head><title>A Sample Page</title></head>\n" + + "<body><form class='first colorsample' name='aForm'><input name=color></form>" + + "have <a id='link1' href='/other.html'>an <b>active</b> link</A>\n" + + "<img id='23' src='/images/arrow.gif' ALT='Next -->' WIDTH=1 HEIGHT=4>\n" + + "</body></html>\n" ); + WebConversation wc = new WebConversation(); + WebRequest request = new GetMethodWebRequest( getHostPath() + "/SimplePage.html" ); + WebResponse simplePage = wc.getResponse( request ); + assertImplement( "elements with class attribute 'first colorsample'", simplePage.getElementsWithAttribute( "class", "first colorsample" ), WebForm.class ); + assertImplement( "elements with class 'first'", simplePage.getElementsWithClassName( "first" ), WebForm.class ); + assertImplement( "elements with class 'colorsample'", simplePage.getElementsWithClassName( "colorsample" ), WebForm.class ); + } + + + /** * Test the {@link WebResponse.ByteTagParser} to ensure that embedded JavaScript is skipped. */ public void testByteTagParser() throws Exception { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <wol...@us...> - 2009-08-21 09:03:55
|
Revision: 1049 http://httpunit.svn.sourceforge.net/httpunit/?rev=1049&view=rev Author: wolfgang_fahl Date: 2009-08-21 09:03:44 +0000 (Fri, 21 Aug 2009) Log Message: ----------- Patch by Matthew Boedicker: post with authentication using inputstream Modified Paths: -------------- trunk/httpunit/src/com/meterware/httpunit/MessageBodyWebRequest.java trunk/httpunit/test/com/meterware/httpunit/WebClientTest.java Modified: trunk/httpunit/src/com/meterware/httpunit/MessageBodyWebRequest.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/MessageBodyWebRequest.java 2009-08-20 12:14:08 UTC (rev 1048) +++ trunk/httpunit/src/com/meterware/httpunit/MessageBodyWebRequest.java 2009-08-21 09:03:44 UTC (rev 1049) @@ -2,7 +2,7 @@ /******************************************************************************************************************** * $Id$ * -* Copyright (c) 2001-2004,2007 Russell Gold +* Copyright (c) 2001-2009 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 @@ -157,8 +157,14 @@ /** * Transmits the body of this request as a sequence of bytes. - **/ + * @param outputStream + * @param parameters + * @throws IOException if the tranmission fails + */ public void writeTo( OutputStream outputStream, ParameterCollection parameters ) throws IOException { + if (_source.markSupported()) { + mark(); + } byte[] buffer = new byte[8 * 1024]; int count = 0; do { @@ -166,10 +172,27 @@ count = _source.read( buffer, 0, buffer.length ); } while (count != -1); - _source.close(); + written = true; } + /** + * + * @throws IOException + */ + public void mark() throws IOException { + if (written) { + _source.reset(); + } else { + // amount of bytes to be read after mark gets invalid + int readlimit=1024*1024; // ! MByte + // Marks the current position in this input stream. + // A subsequent call to the reset method repositions + // this stream at the last marked position so that subsequent reads re-read the same bytes. + _source.mark(readlimit); + } + } + private boolean written = false; private InputStream _source; private String _contentType; } Modified: trunk/httpunit/test/com/meterware/httpunit/WebClientTest.java =================================================================== --- trunk/httpunit/test/com/meterware/httpunit/WebClientTest.java 2009-08-20 12:14:08 UTC (rev 1048) +++ trunk/httpunit/test/com/meterware/httpunit/WebClientTest.java 2009-08-21 09:03:44 UTC (rev 1049) @@ -26,8 +26,10 @@ import junit.framework.TestSuite; +import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.InputStream; import java.io.OutputStreamWriter; import java.net.*; import java.util.*; @@ -403,7 +405,39 @@ assertEquals( "authorization", "Basic dXNlcjpwYXNzd29yZA==", wr.getText() ); } + /** + * test on demand Basic Authentication with InputStream + * + * @throws Exception + */ + public void testOnDemandBasicAuthenticationInputStream() throws Exception { + defineResource("postRequiringAuthentication", new PseudoServlet() { + public WebResource getPostResponse() { + String header = getHeader("Authorization"); + if (header == null) { + WebResource webResource = new WebResource("unauthorized"); + webResource + .addHeader("WWW-Authenticate: Basic realm=\"testrealm\""); + return webResource; + } else { + return new WebResource(getBody(), "text/plain"); + } + } + }); + String body = "something"; + InputStream bodyStream = new ByteArrayInputStream(body.getBytes("UTF-8")); + PostMethodWebRequest request = new PostMethodWebRequest(getHostPath() + + "/postRequiringAuthentication", bodyStream, "text/plain"); + + WebConversation wc = new WebConversation(); + wc.setAuthentication("testrealm", "user", "password"); + + WebResponse wr = wc.getResponse(request); + assertEquals(body, wr.getText()); + bodyStream.close(); + } + /** * Verifies that even though we have specified username and password for a realm, * a request for a different realm will still result in an exception. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <wol...@us...> - 2009-08-21 09:43:49
|
Revision: 1050 http://httpunit.svn.sourceforge.net/httpunit/?rev=1050&view=rev Author: wolfgang_fahl Date: 2009-08-21 09:43:42 +0000 (Fri, 21 Aug 2009) Log Message: ----------- Patch by Dan Lipofsky - reset Listeners and allow switching off parsing. Switch off parsing for Head method. Modified Paths: -------------- trunk/httpunit/src/com/meterware/httpunit/HttpWebResponse.java trunk/httpunit/src/com/meterware/httpunit/WebResponse.java trunk/httpunit/src/com/meterware/httpunit/parsing/HTMLParserFactory.java trunk/httpunit/test/com/meterware/httpunit/parsing/HTMLParserListenerTest.java Modified: trunk/httpunit/src/com/meterware/httpunit/HttpWebResponse.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/HttpWebResponse.java 2009-08-21 09:03:44 UTC (rev 1049) +++ trunk/httpunit/src/com/meterware/httpunit/HttpWebResponse.java 2009-08-21 09:43:42 UTC (rev 1050) @@ -70,6 +70,7 @@ HttpWebResponse( WebConversation client, FrameSelector frame, WebRequest request, URLConnection connection, boolean throwExceptionOnError ) throws IOException { this( client, frame, request.getURL(), connection, throwExceptionOnError ); + super.setWithParse(!request.getMethod().equals("HEAD")); _referer = request.getReferer(); } Modified: trunk/httpunit/src/com/meterware/httpunit/WebResponse.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/WebResponse.java 2009-08-21 09:03:44 UTC (rev 1049) +++ trunk/httpunit/src/com/meterware/httpunit/WebResponse.java 2009-08-21 09:43:42 UTC (rev 1050) @@ -74,12 +74,29 @@ private static final int UNKNOWN_LENGTH_RETRY_INTERVAL = 10; private FrameSelector _frame; - + // allow to switch off parsing e.g. for method="HEAD" + private boolean _withParse=true; private String _baseTarget; private String _refreshHeader; private URL _baseURL; private boolean _parsingPage; + /** + * is parsing on? + * @return + */ + public boolean isWithParse() { + return _withParse; + } + + /** + * set the parsing switch + * @param doparse + * @return + */ + public void setWithParse(boolean doParse) { + _withParse=doParse; + } /** * Returns a web response built from a URL connection. Provided to allow @@ -832,7 +849,7 @@ public void load() throws SAXException { - if (isHTML()) { + if (isHTML() && isWithParse()) { getReceivedPage().getForms(); // TODO be more explicit here - don't care about forms, after all doEventScript( getReceivedPage().getOnLoadEvent() ); } @@ -1308,8 +1325,10 @@ private WebFrame[] getFrames() throws SAXException { - return getReceivedPage().getFrames(); - + if (isWithParse()) + return getReceivedPage().getFrames(); + else + return new WebFrame[0]; } @@ -1324,10 +1343,11 @@ _parsingPage = true; if (!isHTML()) throw new NotHTMLException( getContentType() ); _page = new HTMLPage( this, _frame, _baseURL, _baseTarget, getCharacterSet() ); - _page.parse( getText(), _pageURL ); - if (_page == null) throw new IllegalStateException( "replaceText called in the middle of getReceivedPage()" ); - - ((HTMLDocumentImpl) _page.getRootNode()).getWindow().setProxy( this ); + if (_withParse) { + _page.parse( getText(), _pageURL ); + if (_page == null) throw new IllegalStateException( "replaceText called in the middle of getReceivedPage()" ); + ((HTMLDocumentImpl) _page.getRootNode()).getWindow().setProxy( this ); + } } catch (IOException e) { HttpUnitUtils.handleException(e); throw new RuntimeException( e.toString() ); Modified: trunk/httpunit/src/com/meterware/httpunit/parsing/HTMLParserFactory.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/parsing/HTMLParserFactory.java 2009-08-21 09:03:44 UTC (rev 1049) +++ trunk/httpunit/src/com/meterware/httpunit/parsing/HTMLParserFactory.java 2009-08-21 09:43:42 UTC (rev 1050) @@ -2,7 +2,7 @@ /******************************************************************************************************************** * $Id$ * - * Copyright (c) 2002-2008, Russell Gold + * Copyright (c) 2002-2009, 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 @@ -54,7 +54,8 @@ _parserWarningsEnabled = false; _htmlParser = null; _forceUpper = false; - _forceLower = false; + _forceLower = false; + _listeners.clear(); } Modified: trunk/httpunit/test/com/meterware/httpunit/parsing/HTMLParserListenerTest.java =================================================================== --- trunk/httpunit/test/com/meterware/httpunit/parsing/HTMLParserListenerTest.java 2009-08-21 09:03:44 UTC (rev 1049) +++ trunk/httpunit/test/com/meterware/httpunit/parsing/HTMLParserListenerTest.java 2009-08-21 09:43:42 UTC (rev 1050) @@ -1,24 +1,25 @@ package com.meterware.httpunit.parsing; + /******************************************************************************************************************** -* $Id$ -* -* Copyright (c) 2003, 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. -* -*******************************************************************************************************************/ + * $Id$ + * + * Copyright (c) 2003, 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 com.meterware.httpunit.*; import java.net.URL; @@ -26,109 +27,159 @@ import junit.framework.TestSuite; - /** - * + * * @author <a href="mailto:rus...@ht...">Russell Gold</a> **/ public class HTMLParserListenerTest extends HttpUnitTest { - public static void main(String[] args) { - junit.textui.TestRunner.run( suite() ); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } + public static TestSuite suite() { + return new TestSuite(HTMLParserListenerTest.class); + } - public static TestSuite suite() { - return new TestSuite( HTMLParserListenerTest.class ); - } + public HTMLParserListenerTest(String name) { + super(name); + } - public HTMLParserListenerTest( String name ) { - super( name ); - } + public void testBadHTMLPage() throws Exception { + defineResource("BadPage.html", "<html>" + + "<head><title>A Sample Page</head>\n" + + "<body><p><b>Wrong embedded tags</p></b>\n" + + "have <a blef=\"other.html?a=1&b=2\">an invalid link</A>\n" + + "<IMG SRC=\"/images/arrow.gif\" WIDTH=1 HEIGHT=4>\n" + + "<unknownTag>bla</unknownTag>" + "</body></html>\n"); + final ErrorHandler errorHandler = new ErrorHandler( + /* expectProblems */true); + try { + WebConversation wc = new WebConversation(); + HTMLParserFactory.addHTMLParserListener(errorHandler); + WebRequest request = new GetMethodWebRequest(getHostPath() + + "/BadPage.html"); + wc.getResponse(request); + assertTrue("Should have found problems", errorHandler + .foundProblems()); + assertEquals("Expected URL", request.getURL(), errorHandler + .getBadURL()); + } finally { + HTMLParserFactory.removeHTMLParserListener(errorHandler); + } + } - public void testBadHTMLPage() throws Exception { - defineResource( "BadPage.html", - "<html>" + - "<head><title>A Sample Page</head>\n" + - "<body><p><b>Wrong embedded tags</p></b>\n" + - "have <a blef=\"other.html?a=1&b=2\">an invalid link</A>\n" + - "<IMG SRC=\"/images/arrow.gif\" WIDTH=1 HEIGHT=4>\n" + - "<unknownTag>bla</unknownTag>" + - "</body></html>\n" ); + public void testGoodHTMLPage() throws Exception { + final ErrorHandler errorHandler = new ErrorHandler( + /* expectProblems */false); + try { + defineResource( + "SimplePage.html", + "<html>\n" + + "<head><title>A Sample Page</title></head>\n" + + "<body><p><b>OK embedded tags</b></p>\n" + + "have <a href=\"other.html?a=1&b=2\">an OK link</A>\n" + + "<IMG SRC=\"/images/arrow.gif\" alt=\"\" WIDTH=1 HEIGHT=4>\n" + + "</body></html>\n"); - final ErrorHandler errorHandler = new ErrorHandler( /* expectProblems */ true ); - try { - WebConversation wc = new WebConversation(); - HTMLParserFactory.addHTMLParserListener( errorHandler ); - WebRequest request = new GetMethodWebRequest( getHostPath() + "/BadPage.html" ); - wc.getResponse( request ); - assertTrue( "Should have found problems", errorHandler.foundProblems() ); - assertEquals( "Expected URL", request.getURL(), errorHandler.getBadURL() ); - } finally { - HTMLParserFactory.removeHTMLParserListener( errorHandler ); - } - } + WebConversation wc = new WebConversation(); + HTMLParserFactory.addHTMLParserListener(errorHandler); + WebRequest request = new GetMethodWebRequest(getHostPath() + + "/SimplePage.html"); + wc.getResponse(request); + } finally { + HTMLParserFactory.removeHTMLParserListener(errorHandler); + } + } + public void testJTidyPrintWriterParsing() throws Exception { + URL url = new URL("http://localhost/blank.html"); + PrintWriter p = new JTidyPrintWriter(url); + p.print("line 1234 column 1234"); + p.print("line 1,234 column 1,234"); + p.print("line 1,234,567 column 1,234,567"); + p.print("line 1,2,34 column 12,34"); + p.print("line 123,,4 column 12,,34"); + } - public void testGoodHTMLPage() throws Exception { - final ErrorHandler errorHandler = new ErrorHandler( /* expectProblems */ false ); - try { - defineResource( "SimplePage.html", - "<html>\n" + - "<head><title>A Sample Page</title></head>\n" + - "<body><p><b>OK embedded tags</b></p>\n" + - "have <a href=\"other.html?a=1&b=2\">an OK link</A>\n" + - "<IMG SRC=\"/images/arrow.gif\" alt=\"\" WIDTH=1 HEIGHT=4>\n" + - "</body></html>\n" ); + /** + * test by Dan Lipofsky + * + * @throws Exception + */ + public void testHeadMethodWebRequest2() throws Exception { + defineResource("SimplePage.html", + "<html><head><title>A Sample Page</title></head>\n" + + "<body>Hello</body></html>\n"); + HttpUnitOptions.setExceptionsThrownOnErrorStatus(true); + try { + HTMLParserFactory.setParserWarningsEnabled(true); + HTMLParserFactory.setHTMLParser(new NekoHTMLParser() { + // @Override + public void parse(URL pageURL, String pageText, + DocumentAdapter adapter) { + System.err.println("Parsing URL=" + pageURL + "\n" + + pageText); + fail("Should not be parsing a HEAD request"); + } + }); + HTMLParserFactory.addHTMLParserListener(new HTMLParserListener() { + public void error(URL url, String msg, int line, int column) { + System.err.println("ERROR @url=" + url + ": (" + line + + ", " + column + "):" + msg); + } - WebConversation wc = new WebConversation(); - HTMLParserFactory.addHTMLParserListener( errorHandler ); - WebRequest request = new GetMethodWebRequest( getHostPath() + "/SimplePage.html" ); - wc.getResponse( request ); - } finally { - HTMLParserFactory.removeHTMLParserListener( errorHandler ); - } - } + public void warning(URL url, String msg, int line, int column) { + System.err.println("WARN @url=" + url + ": (" + line + ", " + + column + "):" + msg); + } + }); + WebConversation wc = new WebConversation(); + // create a HeadMethodWebRequest + // see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html for + // definition + WebRequest request = new HeadMethodWebRequest(getHostPath() + + "/SimplePage.html"); + WebResponse simplePage = wc.getResponse(request); + String text = simplePage.getText(); + // no body should be returned + assertEquals("", text); + } finally { + HTMLParserFactory.reset(); + } + } - public void testJTidyPrintWriterParsing() throws Exception { - URL url = new URL("http://localhost/blank.html"); - PrintWriter p = new JTidyPrintWriter(url); - p.print("line 1234 column 1234"); - p.print("line 1,234 column 1,234"); - p.print("line 1,234,567 column 1,234,567"); - p.print("line 1,2,34 column 12,34"); - p.print("line 123,,4 column 12,,34"); - } + static private class ErrorHandler implements HTMLParserListener { + private boolean _expectProblems; + private boolean _foundProblems; + private URL _badURL; - static private class ErrorHandler implements HTMLParserListener { + public ErrorHandler(boolean expectProblems) { + _expectProblems = expectProblems; + } - private boolean _expectProblems; - private boolean _foundProblems; - private URL _badURL; + public void warning(URL url, String msg, int line, int column) { + _foundProblems = true; + _badURL = url; + } + public void error(URL url, String msg, int line, int column) { + assertTrue(msg + " at line " + line + ", column " + column, + _expectProblems); + _foundProblems = true; + _badURL = url; + } - public ErrorHandler( boolean expectProblems ) { - _expectProblems = expectProblems; - } + public URL getBadURL() { + return _badURL; + } + public boolean foundProblems() { + return _foundProblems; + } + } - public void warning( URL url, String msg, int line, int column ) { - _foundProblems = true; - _badURL = url; - } - - public void error( URL url, String msg, int line, int column ) { - assertTrue( msg + " at line " + line + ", column " + column, _expectProblems ); - _foundProblems = true; - _badURL = url; - } - - public URL getBadURL() { return _badURL; } - - public boolean foundProblems() { return _foundProblems; } - } - } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <wol...@us...> - 2009-08-21 11:08:20
|
Revision: 1051 http://httpunit.svn.sourceforge.net/httpunit/?rev=1051&view=rev Author: wolfgang_fahl Date: 2009-08-21 11:08:14 +0000 (Fri, 21 Aug 2009) Log Message: ----------- fix for BR 2534057 by Igor Kanshin Modified Paths: -------------- trunk/httpunit/src/com/meterware/httpunit/dom/HTMLContainerDelegate.java trunk/httpunit/src/com/meterware/httpunit/dom/NodeImpl.java trunk/httpunit/test/com/meterware/httpunit/WebLinkTest.java trunk/httpunit/test/com/meterware/httpunit/dom/NodeTest.java Modified: trunk/httpunit/src/com/meterware/httpunit/dom/HTMLContainerDelegate.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/dom/HTMLContainerDelegate.java 2009-08-21 09:43:42 UTC (rev 1050) +++ trunk/httpunit/src/com/meterware/httpunit/dom/HTMLContainerDelegate.java 2009-08-21 11:08:14 UTC (rev 1051) @@ -44,12 +44,12 @@ /** * get Links for a given Node - * @param rootNode + * @param rootNode - an array of forms * @return */ HTMLCollection getLinks( NodeImpl rootNode ) { ArrayList elements = new ArrayList(); - for (Iterator each = rootNode.preOrderIteratorAfterNode( _iteratorMask ); each.hasNext();) { + for (Iterator each = rootNode.preOrderIteratorWithinNode( _iteratorMask ); each.hasNext();) { Node node = (Node) each.next(); if (node.getNodeType() != Node.ELEMENT_NODE) continue; @@ -61,9 +61,14 @@ } + /** + * get forms for a given Node + * @param rootNode - the node to start from + * @return - an array of forms + */ HTMLCollection getForms( NodeImpl rootNode ) { ArrayList elements = new ArrayList(); - for (Iterator each = rootNode.preOrderIteratorAfterNode( _iteratorMask ); each.hasNext();) { + for (Iterator each = rootNode.preOrderIteratorWithinNode( _iteratorMask ); each.hasNext();) { Node node = (Node) each.next(); if (node.getNodeType() != Node.ELEMENT_NODE) continue; Modified: trunk/httpunit/src/com/meterware/httpunit/dom/NodeImpl.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/dom/NodeImpl.java 2009-08-21 09:43:42 UTC (rev 1050) +++ trunk/httpunit/src/com/meterware/httpunit/dom/NodeImpl.java 2009-08-21 11:08:14 UTC (rev 1051) @@ -352,7 +352,23 @@ return new PreOrderIterator( PreOrderIterator.nextNode( this ) ); } + /** + * + * @return + */ + public Iterator preOrderIteratorWithinNode() { + PreOrderIterator result = new PreOrderIterator( PreOrderIterator.nextNode( this ) ); + result.setDoNotLeaveNode(this); + return result; + } + + public Iterator preOrderIteratorWithinNode(IteratorMask mask) { + PreOrderIterator result = new PreOrderIterator( PreOrderIterator.nextNode( this ),mask ); + result.setDoNotLeaveNode(this); + return result; + } + public Iterator preOrderIteratorAfterNode( IteratorMask mask ) { return new PreOrderIterator( PreOrderIterator.nextNode( this ), mask ); } @@ -367,36 +383,105 @@ } + /** + * allow masking of the iteration + */ interface IteratorMask { + // skip a given subtree boolean skipSubtree( Node subtreeRoot ); } - + /** + * iterator for Nodetrees that can be influenced with an Iterator mask to skip + * specific parts + */ static class PreOrderIterator implements Iterator { private NodeImpl _nextNode; + private NodeImpl _startNode; private IteratorMask _mask; + private NodeImpl _doNotLeaveNode=null; + /** + * get the limit node + * @return + */ + public NodeImpl getDoNotLeaveNode() { + return _doNotLeaveNode; + } + /** + * limit the PreOrderIterator not to leave the given node + * @param doNotLeaveNode + */ + public void setDoNotLeaveNode(NodeImpl doNotLeaveNode) { + _doNotLeaveNode = doNotLeaveNode; + } + + /** + * check whether the node is a child of the doNotLeaveNode (if one is set) + * @param node + * @return + */ + private boolean isChild(Node node) { + if (node==null) { + return false; + } if (_doNotLeaveNode==null) { + return true; + } else { + Node parent = node.getParentNode(); + if (parent==null) { + return false; + } else { + if (parent.isSameNode(_doNotLeaveNode)) { + return true; + } else { + return isChild(parent); + } + } + } + } + + /** + * create a PreOrderIterator starting at a given currentNode + * @param currentNode + */ PreOrderIterator( NodeImpl currentNode ) { _nextNode = currentNode; + _startNode= currentNode; } + /** + * create a PreOrderIterator starting at a given currentNode and setting + * the iterator mask to the given mask + * @param currentNode + * @param mask + */ PreOrderIterator( NodeImpl currentNode, IteratorMask mask ) { this( currentNode ); _mask = mask; } + /** + * is there still a next node? + */ public boolean hasNext() { return null != _nextNode; } + /** + * move one step in the tree + */ public Object next() { NodeImpl currentNode = _nextNode; _nextNode = nextNode( _nextNode ); - while (_mask != null && _nextNode != null && _mask.skipSubtree( _nextNode )) _nextNode = nextSubtree( _nextNode ); + while (_mask != null && _nextNode != null && _mask.skipSubtree( _nextNode )) + _nextNode = nextSubtree( _nextNode ); + // check that we fit the doNotLeaveNode condition in case there is one + if (!isChild(_nextNode)) + _nextNode=null; return currentNode; } @@ -421,4 +506,5 @@ return null; } } + } Modified: trunk/httpunit/test/com/meterware/httpunit/WebLinkTest.java =================================================================== --- trunk/httpunit/test/com/meterware/httpunit/WebLinkTest.java 2009-08-21 09:43:42 UTC (rev 1050) +++ trunk/httpunit/test/com/meterware/httpunit/WebLinkTest.java 2009-08-21 11:08:14 UTC (rev 1051) @@ -19,6 +19,8 @@ * DEALINGS IN THE SOFTWARE. * *******************************************************************************************************************/ +import org.xml.sax.SAXException; + import junit.framework.TestSuite; @@ -52,6 +54,7 @@ "<body>This has no forms but it does\n" + "have <a href='/other.html#middle' id='activeID'>an <b>active</b> link</A>\n" + " and <a name=here>an anchor</a>\n" + + "<table><tr><td name='acell'><a href='basic.html' name='acelllink'>a link in a cell</a></td></tr></table>"+ "<a href='basic.html' name=\"nextLink\"><IMG SRC=\"/images/arrow.gif\" ALT=\"Next -->\" WIDTH=1 HEIGHT=4></a>\n" + "<a href='another.html' name='myLink'>some text</a>\n" + "</body></html>\n" ); @@ -107,11 +110,14 @@ assertTrue("the blank %20 in the link2 should not be converted but we got '"+link2.getURLString()+"'",link2.getURLString().equals(blankLink2)); } - + /** + * check the number of links in the sample page + * @throws Exception + */ public void testLinks() throws Exception { WebLink[] links = _simplePage.getLinks(); assertNotNull( "Found no links", links ); - assertEquals( "number of links in page", 3, links.length ); + assertEquals( "number of links in page", 4, links.length ); } @@ -141,6 +147,25 @@ assertEquals( "URLString", "/other.html", link.getURLString() ); } + + /** + * test for BR 2534057 + * getLinks() for a Cell return all page links + * @throws SAXException + */ + public void testGetLinksForCell() throws SAXException { + HTMLElement[] elements = _simplePage.getElementsWithName("acell"); + assertTrue(elements.length==1); + assertTrue(elements[0] instanceof TableCell); + TableCell aCell=(TableCell)elements[0]; + WebLink[] cellLinks = aCell.getLinks(); + for (int i=0;i<cellLinks.length;i++) { + WebLink link=cellLinks[i]; + System.out.println("link "+i+"="+link.getName()); + } + assertEquals(1,cellLinks.length); + assertEquals("acelllink",cellLinks[0].getName()); + } public void testGetLinkByText() throws Exception { WebLink link = _simplePage.getLinkWith( "no link" ); Modified: trunk/httpunit/test/com/meterware/httpunit/dom/NodeTest.java =================================================================== --- trunk/httpunit/test/com/meterware/httpunit/dom/NodeTest.java 2009-08-21 09:43:42 UTC (rev 1050) +++ trunk/httpunit/test/com/meterware/httpunit/dom/NodeTest.java 2009-08-21 11:08:14 UTC (rev 1051) @@ -372,6 +372,19 @@ assertFalse( "Iterator should have terminated after " + expectedNodes.length + " nodes", each.hasNext() ); } + /** + * Verifies that we can iterate through nodes in order, starting after a specific node. + */ + public void testPreOrderIteratorWithinNode() throws Exception { + Iterator each = ((NodeImpl)_foo1).preOrderIteratorWithinNode(); + Node[] expectedNodes = { _bar1, _text, _foo2}; + for (int i = 0; i < expectedNodes.length; i++) { + assertTrue( "Iterator prematurely terminated after " + i + " nodes", each.hasNext() ); + Object node = each.next(); + assertSame( "Node " + (1 + i) + ":", expectedNodes[i], node ); + } + assertFalse( "Iterator should have terminated after " + expectedNodes.length + " nodes", each.hasNext() ); + } /** * Verifies that we can iterate through nodes in order skipping a specified subtree. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <wol...@us...> - 2009-08-21 12:41:41
|
Revision: 1053 http://httpunit.svn.sourceforge.net/httpunit/?rev=1053&view=rev Author: wolfgang_fahl Date: 2009-08-21 12:41:31 +0000 (Fri, 21 Aug 2009) Log Message: ----------- add getSocketFactory convenience method as proposed by Florian Weimar Modified Paths: -------------- trunk/httpunit/src/com/meterware/httpunit/HttpsProtocolSupport.java trunk/httpunit/test/com/meterware/httpunit/ssl/HttpsProtocolSupportTest.java Modified: trunk/httpunit/src/com/meterware/httpunit/HttpsProtocolSupport.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/HttpsProtocolSupport.java 2009-08-21 12:33:21 UTC (rev 1052) +++ trunk/httpunit/src/com/meterware/httpunit/HttpsProtocolSupport.java 2009-08-21 12:41:31 UTC (rev 1053) @@ -22,8 +22,14 @@ *******************************************************************************************************************/ import java.security.Provider; import java.security.Security; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.X509TrustManager; + /** * Encapsulates support for the HTTPS protocol. * @@ -154,8 +160,36 @@ } return false; } + + /** + * convenience function: create a socket factory which + * uses an anything-goes trust manager. + * proposed by Florian Weimar + */ + public static SSLSocketFactory getSocketFactory() throws Exception { + final SSLContext context = SSLContext.getInstance("TLS"); + context.init(null, new X509TrustManager[] { + new X509TrustManager() { + //@Override + public void checkClientTrusted(X509Certificate[] arg0, + String arg1) throws CertificateException { + } + //@Override + public void checkServerTrusted(X509Certificate[] arg0, + String arg1) throws CertificateException { + } + //@Override + public X509Certificate[] getAcceptedIssuers() { + return null; + } + + }}, null); + return context.getSocketFactory(); + } + + /** * register the Secure Socket Layer Protocol Handler */ Modified: trunk/httpunit/test/com/meterware/httpunit/ssl/HttpsProtocolSupportTest.java =================================================================== --- trunk/httpunit/test/com/meterware/httpunit/ssl/HttpsProtocolSupportTest.java 2009-08-21 12:33:21 UTC (rev 1052) +++ trunk/httpunit/test/com/meterware/httpunit/ssl/HttpsProtocolSupportTest.java 2009-08-21 12:41:31 UTC (rev 1053) @@ -22,6 +22,8 @@ import java.security.Provider; import java.security.Security; +import javax.net.ssl.SSLSocketFactory; + import com.meterware.httpunit.HttpsProtocolSupport; import junit.framework.Test; @@ -77,4 +79,13 @@ expected= sslProviders[0].getClass().getName(); assertEquals( "provider",expected, provider.getName() ); } + + /** + * test the socket Factory convenience method as proposed by Florian Weimar + * @throws Exception + */ + public void testSocketFactory() throws Exception { + SSLSocketFactory factory = HttpsProtocolSupport.getSocketFactory(); + assertTrue(factory!=null); + } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <wol...@us...> - 2009-08-21 17:54:09
|
Revision: 1055 http://httpunit.svn.sourceforge.net/httpunit/?rev=1055&view=rev Author: wolfgang_fahl Date: 2009-08-21 17:54:02 +0000 (Fri, 21 Aug 2009) Log Message: ----------- [ 1163753 ] partial patch for bug 771335 (DOM2 Events support) by Rafal Krzewski Modified Paths: -------------- trunk/httpunit/src/com/meterware/httpunit/javascript/JavaScript.java trunk/httpunit/test/com/meterware/httpunit/javascript/JavaScriptTestSuite.java Added Paths: ----------- trunk/httpunit/src/com/meterware/httpunit/javascript/events/ trunk/httpunit/src/com/meterware/httpunit/javascript/events/Event.java trunk/httpunit/src/com/meterware/httpunit/javascript/events/EventException.java trunk/httpunit/src/com/meterware/httpunit/javascript/events/EventListener.java trunk/httpunit/src/com/meterware/httpunit/javascript/events/EventTarget.java Modified: trunk/httpunit/src/com/meterware/httpunit/javascript/JavaScript.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/javascript/JavaScript.java 2009-08-21 14:00:15 UTC (rev 1054) +++ trunk/httpunit/src/com/meterware/httpunit/javascript/JavaScript.java 2009-08-21 17:54:02 UTC (rev 1055) @@ -21,11 +21,17 @@ *******************************************************************************************************************/ import com.meterware.httpunit.*; +import com.meterware.httpunit.javascript.events.EventException; +import com.meterware.httpunit.javascript.events.EventTarget; import com.meterware.httpunit.scripting.*; import java.lang.reflect.InvocationTargetException; import java.io.IOException; import java.net.URL; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; import org.mozilla.javascript.*; import org.xml.sax.SAXException; @@ -104,10 +110,12 @@ /** * abstract Engine for JavaScript */ - abstract static class JavaScriptEngine extends ScriptingEngineImpl { + abstract static class JavaScriptEngine extends ScriptingEngineImpl implements EventTarget { protected ScriptableDelegate _scriptable; protected JavaScriptEngine _parent; + protected Map _eventListeners = new HashMap(); // Map<String,Set<EventListener>> + protected Map _eventCaptureListeners = new HashMap(); // Map<String,Set<EventListener>> /** * initialize JavaScript for the given ScriptEngine @@ -270,6 +278,57 @@ result.initialize( elements ); return result; } + + /** + * {@inheritDoc} + */ + public void jsFunction_addEventListener(String type, Scriptable listener, boolean useCapture) { + if(useCapture) { + Set set = (Set)_eventCaptureListeners.get(type); //Set<Scriptable> + if(set == null) { + set = new HashSet(); + _eventCaptureListeners.put(type, set); + } + set.add(listener); + } else { + Set set = (Set)_eventListeners.get(type); //Set<Scriptable> + if(set == null) { + set = new HashSet(); + _eventListeners.put(type, set); + } + set.add(listener); + } + //System.out.println(getClassName()+".addEventListener("+type+")"); + } + + + /** + * {@inheritDoc} + */ + public boolean jsFunction_dispatchEvent(Scriptable evt) throws EventException { + // TODO implement event dispatching & listener invocation + //System.out.println(getClassName()+".dispatchEvent("+evt.get("type",evt)+")"); + return true; + } + + + /** + * {@inheritDoc} + */ + public void jsFunction_removeEventListener(String type, Scriptable listener, boolean useCapture) { + if(useCapture) { + Set set = (Set)_eventCaptureListeners.get(type); //Set<EventListener> + if(set != null) { + set.remove(listener); + } + } else { + Set set = (Set)_eventListeners.get(type); //Set<EventListener> + if(set != null) { + set.remove(listener); + } + } + //System.out.println(getClassName()+".removeEventListener("+type+")"); + } } @@ -415,6 +474,7 @@ } + public Window jsFunction_open( Object url, String name, String features, boolean replace ) throws PropertyException, JavaScriptException, NotAFunctionException, IOException, SAXException { WebResponse.Scriptable delegate = getDelegate().open( toStringIfNotUndefined( url ), name, features, replace ); @@ -576,6 +636,27 @@ return (HTMLPage.Scriptable) _scriptable; } + + public void jsFunction_addEventListener(String type, + Scriptable listener, boolean useCapture) { + // TODO Auto-generated method stub + + } + + + public boolean jsFunction_dispatchEvent(Scriptable evt) + throws EventException { + // TODO Auto-generated method stub + return false; + } + + + public void jsFunction_removeEventListener(String type, + Scriptable listener, boolean useCapture) { + // TODO Auto-generated method stub + + } + } Added: trunk/httpunit/src/com/meterware/httpunit/javascript/events/Event.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/javascript/events/Event.java (rev 0) +++ trunk/httpunit/src/com/meterware/httpunit/javascript/events/Event.java 2009-08-21 17:54:02 UTC (rev 1055) @@ -0,0 +1,190 @@ +/******************************************************************************************************************** + * $Id: FormScriptingTest.java 1031 2009-08-17 12:15:24Z wolfgang_fahl $ + * $URL: https://httpunit.svn.sourceforge.net/svnroot/httpunit/trunk/httpunit/test/com/meterware/httpunit/javascript/FormScriptingTest.java $ + * + * Copyright (c) 2005, Caltha - Gajda, Krzewski, Mach, Potempski Sp.J., + * Copyright (c) 2009, Wolfgang Fahl + * + * 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. + * + *******************************************************************************************************************/ +package com.meterware.httpunit.javascript.events; + +import org.mozilla.javascript.ScriptableObject; + +/** + * @author <a href="mailto:ra...@ca...">Rafal Krzewski</a> + * @version $Id$ + */ +public abstract class Event + extends ScriptableObject +{ + // -- Scriptable interface ------------------------------------------------------------------ + + /** JavaScript class name. */ + private static final String JS_CLASS_NAME = "Event"; + + /** + * {@inheritDoc} + */ + public String getClassName() + { + return JS_CLASS_NAME; + } + + // -- DOM2 Events specification ------------------------------------------------------------- + + /** + * The current event phase is the capturing phase. + */ + public static final short CAPTURING_PHASE = 1; + + /** + * The event is currently being evaluated at the target EventTarget. + */ + public static final short AT_TARGET = 2; + + /** + * The current event phase is the bubbling phase. + */ + public static final short BUBBLING_PHASE = 3; + + /** + * The name of the event (case-insensitive). The name must be an XML name. + */ + private String type; + + /** + * Used to indicate whether or not an event is a bubbling event. If the event can bubble the + * value is true, else the value is false. + */ + private boolean bubbles; + + /** + * Used to indicate whether or not an event can have its default action prevented. If the + * default action can be prevented the value is true, else the value is false. + */ + private boolean cancelable; + + /** + * Used to specify the time (in milliseconds relative to the epoch) at which the event was + * created. Due to the fact that some systems may not provide this information the value of + * timeStamp may be not available for all events. When not available, a value of 0 will be + * returned. Examples of epoch time are the time of the system start or 0:0:0 UTC 1st January + * 1970. + */ + private long timeStamp; + + /** + * The name of the event (case-insensitive). The name must be an XML name. + */ + public String jsGet_type() + { + return type; + } + + /** + * Used to indicate whether or not an event is a bubbling event. If the event can bubble the + * value is true, else the value is false. + */ + public boolean jsGet_bubbles() + { + return bubbles; + } + + /** + * Used to specify the time (in milliseconds relative to the epoch) at which the event was + * created. Due to the fact that some systems may not provide this information the value of + * timeStamp may be not available for all events. When not available, a value of 0 will be + * returned. Examples of epoch time are the time of the system start or 0:0:0 UTC 1st January + * 1970. + */ + public boolean jsGet_cancelable() + { + return cancelable; + } + + /** + * Used to specify the time (in milliseconds relative to the epoch) at which the event was + * created. Due to the fact that some systems may not provide this information the value of + * timeStamp may be not available for all events. When not available, a value of 0 will be + * returned. Examples of epoch time are the time of the system start or 0:0:0 UTC 1st January + * 1970. + */ + public long jsGet_timeStamp() + { + return timeStamp; + } + + /** + * Used to indicate the EventTarget to which the event was originally dispatched. + */ + public abstract EventTarget jsGet_target(); + + /** + * Used to indicate the EventTarget whose EventListeners are currently being processed. This is + * particularly useful during capturing and bubbling. + */ + public abstract EventTarget jsGet_currentTarget(); + + /** + * Used to indicate which phase of event flow is currently being evaluated. + */ + public abstract short jsGet_eventPhase(); + + /** + * The stopPropagation method is used prevent further propagation of an event during event flow. + * If this method is called by any EventListener the event will cease propagating through the + * tree. The event will complete dispatch to all listeners on the current EventTarget before + * event flow stops. This method may be used during any stage of event flow. + */ + public abstract void jsFunction_stopPropagation(); + + /** + * If an event is cancelable, the preventDefault method is used to signify that the event is to + * be canceled, meaning any default action normally taken by the implementation as a result of + * the event will not occur. If, during any stage of event flow, the preventDefault method is + * called the event is canceled. Any default action associated with the event will not occur. + * Calling this method for a non-cancelable event has no effect. Once preventDefault has been + * called it will remain in effect throughout the remainder of the event's propagation. This + * method may be used during any stage of event flow. + */ + public abstract void jsFunction_preventDefault(); + + /** + * The initEvent method is used to initialize the value of an Event created through the + * DocumentEvent interface. This method may only be called before the Event has been dispatched + * via the dispatchEvent method, though it may be called multiple times during that phase if + * necessary. If called multiple times the final invocation takes precedence. If called from a + * subclass of Event interface only the values specified in the initEvent method are modified, + * all other attributes are left unchanged. + * + * @param eventTypeArg Specifies the event type. This type may be any event type currently + * defined in this specification or a new event type.. The string must be an XML name. + * Any new event type must not begin with any upper, lower, or mixed case version of the + * string "DOM". This prefix is reserved for future DOM event sets. It is also strongly + * recommended that third parties adding their own events use their own prefix to avoid + * confusion and lessen the probability of conflicts with other new events. + * @param canBubbleArg Specifies whether or not the event can bubble. + * @param cancelableArg Specifies whether or not the event's default action can be prevented. + */ + public void jsFunction_initEvent(String eventTypeArg, boolean canBubbleArg, + boolean cancelableArg) + { + type = eventTypeArg; + bubbles = canBubbleArg; + cancelable = cancelableArg; + } +} Added: trunk/httpunit/src/com/meterware/httpunit/javascript/events/EventException.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/javascript/events/EventException.java (rev 0) +++ trunk/httpunit/src/com/meterware/httpunit/javascript/events/EventException.java 2009-08-21 17:54:02 UTC (rev 1055) @@ -0,0 +1,68 @@ +/******************************************************************************************************************** + * $Id: FormScriptingTest.java 1031 2009-08-17 12:15:24Z wolfgang_fahl $ + * $URL: https://httpunit.svn.sourceforge.net/svnroot/httpunit/trunk/httpunit/test/com/meterware/httpunit/javascript/FormScriptingTest.java $ + * + * Copyright (c) 2005, Caltha - Gajda, Krzewski, Mach, Potempski Sp.J., + * Copyright (c) 2009, Wolfgang Fahl + * + * 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. + * + *******************************************************************************************************************/ +package com.meterware.httpunit.javascript.events; + +/** + * Event operations may throw an EventException as specified in their method descriptions. + * + * @author <a href="mailto:ra...@ca...">Rafal Krzewski</a> + * @version $Id$ + */ +public class EventException + extends Exception +{ + /** + * If the Event's type was not specified by initializing the event before the method was called. + * Specification of the Event's type as null or an empty string will also trigger this + * exception. + */ + private static final short UNSPECIFIED_EVENT_TYPE_ERR = 0; + + /** + * An integer indicating the type of error generated. + */ + private final short code; + + /** + * Creates new EventException instance. + * + * @param codeArg An integer indicating the type of error generated. + */ + public EventException(short codeArg) { + this.code = codeArg; + } + + /** + * An integer indicating the type of error generated. + */ + public short getCode() { + return code; + } + + /** + * {@inheritDoc} + */ + public String getMessage() { + return Short.toString(code); + } +} Added: trunk/httpunit/src/com/meterware/httpunit/javascript/events/EventListener.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/javascript/events/EventListener.java (rev 0) +++ trunk/httpunit/src/com/meterware/httpunit/javascript/events/EventListener.java 2009-08-21 17:54:02 UTC (rev 1055) @@ -0,0 +1,50 @@ +/******************************************************************************************************************** + * $Id: FormScriptingTest.java 1031 2009-08-17 12:15:24Z wolfgang_fahl $ + * $URL: https://httpunit.svn.sourceforge.net/svnroot/httpunit/trunk/httpunit/test/com/meterware/httpunit/javascript/FormScriptingTest.java $ + * + * Copyright (c) 2005, Caltha - Gajda, Krzewski, Mach, Potempski Sp.J., + * Copyright (c) 2009, Wolfgang Fahl + * + * 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. + * + *******************************************************************************************************************/ +package com.meterware.httpunit.javascript.events; + +import org.mozilla.javascript.Scriptable; + +/** + * The EventListener interface is the primary method for handling events. Users implement the + * EventListener interface and register their listener on an EventTarget using the AddEventListener + * method. The users should also remove their EventListener from its EventTarget after they have + * completed using the listener. When a Node is copied using the cloneNode method the EventListeners + * attached to the source Node are not attached to the copied Node. If the user wishes the same + * EventListeners to be added to the newly created copy the user must add them manually. + * + * @author <a href="mailto:ra...@ca...">Rafal Krzewski</a> + * @version $Id$ + */ +public interface EventListener + extends Scriptable +{ + /** + * This method is called whenever an event occurs of the type for which the EventListener + * interface was registered. + * + * @param evt The Event contains contextual information about the event. It also contains the + * stopPropagation and preventDefault methods which are used in determining the event's + * flow and default action. + */ + public void jsFunction_handleEvent(Scriptable evt); +} Added: trunk/httpunit/src/com/meterware/httpunit/javascript/events/EventTarget.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/javascript/events/EventTarget.java (rev 0) +++ trunk/httpunit/src/com/meterware/httpunit/javascript/events/EventTarget.java 2009-08-21 17:54:02 UTC (rev 1055) @@ -0,0 +1,91 @@ +/******************************************************************************************************************** + * $Id: FormScriptingTest.java 1031 2009-08-17 12:15:24Z wolfgang_fahl $ + * $URL: https://httpunit.svn.sourceforge.net/svnroot/httpunit/trunk/httpunit/test/com/meterware/httpunit/javascript/FormScriptingTest.java $ + * + * Copyright (c) 2005, Caltha - Gajda, Krzewski, Mach, Potempski Sp.J., + * Copyright (c) 2009, Wolfgang Fahl + * + * 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. + * + *******************************************************************************************************************/ +package com.meterware.httpunit.javascript.events; + +import org.mozilla.javascript.Scriptable; + +/** + * The EventTarget interface is implemented by all Nodes in an implementation which supports the DOM + * Event Model. Therefore, this interface can be obtained by using binding-specific casting methods + * on an instance of the Node interface. The interface allows registration and removal of + * EventListeners on an EventTarget and dispatch of events to that EventTarget. + * + * @author W3C + * @version $Id$ + */ +public interface EventTarget + extends Scriptable +{ + /** + * This method allows the registration of event listeners on the event target. If an + * EventListener is added to an EventTarget while it is processing an event, it will not be + * triggered by the current actions but may be triggered during a later stage of event flow, + * such as the bubbling phase. If multiple identical EventListeners are registered on the same + * EventTarget with the same parameters the duplicate instances are discarded. They do not cause + * the EventListener to be called twice and since they are discarded they do not need to be + * removed with the removeEventListener method. + * + * @param type The event type for which the user is registering. + * @param listener The listener parameter takes an interface implemented by the user which + * contains the methods to be called when the event occurs. + * @param useCapture If true, useCapture indicates that the user wishes to initiate capture. + * After initiating capture, all events of the specified type will be dispatched to the + * registered EventListener before being dispatched to any EventTargets beneath them in + * the tree. Events which are bubbling upward through the tree will not trigger an + * EventListener designated to use capture. + */ + public void jsFunction_addEventListener(String type, Scriptable listener, boolean useCapture); + + /** + * This method allows the removal of event listeners from the event target. If an EventListener + * is removed from an EventTarget while it is processing an event, it will not be triggered by + * the current actions. EventListeners can never be invoked after being removed. Calling + * removeEventListener with arguments which do not identify any currently registered + * EventListener on the EventTarget has no effect. + * + * @param type Specifies the event type of the EventListener being removed. + * @param listener The EventListener parameter indicates the EventListener to be removed. + * @param useCapture Specifies whether the EventListener being removed was registered as a + * capturing listener or not. If a listener was registered twice, one with capture and + * one without, each must be removed separately. Removal of a capturing listener does not + * affect a non-capturing version of the same listener, and vice versa. + */ + public void jsFunction_removeEventListener(String type, Scriptable listener, boolean useCapture); + + /** + * This method allows the dispatch of events into the implementations event model. Events + * dispatched in this manner will have the same capturing and bubbling behavior as events + * dispatched directly by the implementation. The target of the event is the EventTarget on + * which dispatchEvent is called. + * + * @param evt Specifies the event type, behavior, and contextual information to be used in + * processing the event. + * @return The return value of dispatchEvent indicates whether any of the listeners which + * handled the event called preventDefault. If preventDefault was called the value is + * false, else the value is true. + * @throws EventException UNSPECIFIED_EVENT_TYPE_ERR: Raised if the Event's type was not + * specified by initializing the event before dispatchEvent was called. Specification of + * the Event's type as null or an empty string will also trigger this exception. + */ + public boolean jsFunction_dispatchEvent(Scriptable evt) throws EventException; +} Modified: trunk/httpunit/test/com/meterware/httpunit/javascript/JavaScriptTestSuite.java =================================================================== --- trunk/httpunit/test/com/meterware/httpunit/javascript/JavaScriptTestSuite.java 2009-08-21 14:00:15 UTC (rev 1054) +++ trunk/httpunit/test/com/meterware/httpunit/javascript/JavaScriptTestSuite.java 2009-08-21 17:54:02 UTC (rev 1055) @@ -50,6 +50,7 @@ result.addTest( FormScriptingTest.suite() ); result.addTest( FrameScriptingTest.suite() ); result.addTest( HTMLElementTest.suite() ); + result.addTest( EventHandlingTest.suite()); return result; } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <wol...@us...> - 2009-09-10 05:24:00
|
Revision: 1061 http://httpunit.svn.sourceforge.net/httpunit/?rev=1061&view=rev Author: wolfgang_fahl Date: 2009-09-10 05:23:52 +0000 (Thu, 10 Sep 2009) Log Message: ----------- This patch adds support for creating and testing HTTP DELETE requests. - by Matthew M. Boedicker Modified Paths: -------------- trunk/httpunit/src/com/meterware/pseudoserver/PseudoServlet.java trunk/httpunit/test/com/meterware/httpunit/WebClientTest.java Added Paths: ----------- trunk/httpunit/src/com/meterware/httpunit/DeleteMethodWebRequest.java Added: trunk/httpunit/src/com/meterware/httpunit/DeleteMethodWebRequest.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/DeleteMethodWebRequest.java (rev 0) +++ trunk/httpunit/src/com/meterware/httpunit/DeleteMethodWebRequest.java 2009-09-10 05:23:52 UTC (rev 1061) @@ -0,0 +1,142 @@ +package com.meterware.httpunit; +/******************************************************************************************************************** +* $Id$ +* +* Copyright (c) 2009, Matthew M. Boedicker +* +* 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 org.w3c.dom.Element; + +import java.net.URL; + +/** + * An HTTP request using the DELETE method. + * RFC 2616 http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html defines: + * + * 9.7 DELETE + * + * The DELETE method requests that the origin server delete the resource identified + * by the Request-URI. This method MAY be overridden by human intervention (or other + * means) on the origin server. The client cannot be guaranteed that the operation + * has been carried out, even if the status code returned from the origin server + * indicates that the action has been completed successfully. However, the server + * SHOULD NOT indicate success unless, at the time the response is given, it + * intends to delete the resource or move it to an inaccessible location. + * + * A successful response SHOULD be 200 (OK) if the response includes an entity + * describing the status, 202 (Accepted) if the action has not yet been enacted, or + * 204 (No Content) if the action has been enacted but the response does not include + * an entity. + * + * If the request passes through a cache and the Request-URI identifies one or more + * currently cached entities, those entries SHOULD be treated as stale. Responses to + * this method are not cacheable. +**/ +public class DeleteMethodWebRequest extends HeaderOnlyWebRequest { + + /** + * initialize me - set method to DELETE + */ + private void init() { + super.setMethod("DELETE"); + } + + /** + * Constructs a web request using a specific absolute url string. + **/ + public DeleteMethodWebRequest( String urlString ) { + super( urlString ); + init(); + } + + + /** + * Constructs a web request using a base URL and a relative url string. + **/ + public DeleteMethodWebRequest( URL urlBase, String urlString ) { + super( urlBase, urlString ); + init(); + } + + + /** + * Constructs a web request with a specific target. + **/ + public DeleteMethodWebRequest( URL urlBase, String urlString, String target ) { + super( urlBase, urlString, target ); + init(); + } + + +//--------------------------------------- package members --------------------------------------------- + + + /** + * Constructs a web request for a form submitted from JavaScript. + **/ + DeleteMethodWebRequest( WebForm sourceForm ) { + super( sourceForm ); + init(); + } + + + /** + * Constructs a web request for a link or image. + **/ + DeleteMethodWebRequest( FixedURLWebRequestSource source ) { + super( source ); + init(); + } + + + /** + * Constructs a web request with a specific target. + **/ + DeleteMethodWebRequest( WebResponse referer, Element sourceElement, URL urlBase, String urlString, String target ) { + super( referer, sourceElement, urlBase, urlString, target ); + init(); + } + + + /** + * Constructs an initial web request for a frame. + **/ + DeleteMethodWebRequest( URL urlBase, String urlString, FrameSelector frame ) { + super( urlBase, urlString, frame ); + init(); + } + + + /** + * Constructs a web request for a javascript open call. + **/ + DeleteMethodWebRequest( URL urlBase, String urlString, FrameSelector frame, String target ) { + super( urlBase, urlString, frame, target ); + init(); + } + + + /** + * Constructs a web request for a form. + **/ + DeleteMethodWebRequest( WebForm sourceForm, ParameterHolder parameterHolder, SubmitButton button, int x, int y ) { + super( sourceForm, parameterHolder, button, x, y ); + init(); + } + + +} Property changes on: trunk/httpunit/src/com/meterware/httpunit/DeleteMethodWebRequest.java ___________________________________________________________________ Added: svn:keywords + Id Author HeadURL Modified: trunk/httpunit/src/com/meterware/pseudoserver/PseudoServlet.java =================================================================== --- trunk/httpunit/src/com/meterware/pseudoserver/PseudoServlet.java 2009-08-26 06:20:18 UTC (rev 1060) +++ trunk/httpunit/src/com/meterware/pseudoserver/PseudoServlet.java 2009-09-10 05:23:52 UTC (rev 1061) @@ -42,6 +42,8 @@ return getPutResponse(); } else if (methodType.equalsIgnoreCase( "POST" )) { return getPostResponse(); + } else if (methodType.equalsIgnoreCase( "DELETE" )) { + return getDeleteResponse(); } else { throw new UnknownMethodException( methodType ); } @@ -72,6 +74,14 @@ } + /* + * Returns a resource object as a result of a delete request. + **/ + public WebResource getDeleteResponse() throws IOException { + throw new UnknownMethodException( "DELETE" ); + } + + void init( HttpRequest requestStream ) { _request = requestStream; } Modified: trunk/httpunit/test/com/meterware/httpunit/WebClientTest.java =================================================================== --- trunk/httpunit/test/com/meterware/httpunit/WebClientTest.java 2009-08-26 06:20:18 UTC (rev 1060) +++ trunk/httpunit/test/com/meterware/httpunit/WebClientTest.java 2009-09-10 05:23:52 UTC (rev 1061) @@ -1121,4 +1121,28 @@ assertEquals( "Submitted cookie header", "found cookies: type=short", wr.getText() ); } + + /** + * test for Delete Response patch by Matthew M. Boedicker" + * @throws Exception + */ + public void testDelete() throws Exception { + String resourceName = "something/to/delete"; + final String responseBody = "deleted"; + final String contentType = "text/plain"; + + defineResource( resourceName, new PseudoServlet() { + public WebResource getDeleteResponse() { + return new WebResource( responseBody, contentType ); + } + } ); + + WebConversation wc = new WebConversation(); + WebRequest request = new DeleteMethodWebRequest( getHostPath() + '/' + resourceName ); + WebResponse response = wc.getResponse( request ); + + assertEquals( "requested resource", responseBody, response.getText().trim() ); + assertEquals( "content type", contentType, response.getContentType() ); + } + } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <wol...@us...> - 2009-12-22 15:34:37
|
Revision: 1062 http://httpunit.svn.sourceforge.net/httpunit/?rev=1062&view=rev Author: wolfgang_fahl Date: 2009-12-22 15:34:27 +0000 (Tue, 22 Dec 2009) Log Message: ----------- Patch for issue when server returns empty content type value + workaround for regression problem - do not try to redefine resources Modified Paths: -------------- trunk/httpunit/src/com/meterware/httpunit/HttpUnitUtils.java trunk/httpunit/src/com/meterware/pseudoserver/PseudoServer.java trunk/httpunit/test/com/meterware/httpunit/EncodingTest.java trunk/httpunit/test/com/meterware/httpunit/MessageBodyRequestTest.java trunk/httpunit/test/com/meterware/httpunit/WebClientTest.java trunk/httpunit/test/com/meterware/httpunit/javascript/NekoEnhancedScriptingTest.java Modified: trunk/httpunit/src/com/meterware/httpunit/HttpUnitUtils.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/HttpUnitUtils.java 2009-09-10 05:23:52 UTC (rev 1061) +++ trunk/httpunit/src/com/meterware/httpunit/HttpUnitUtils.java 2009-12-22 15:34:27 UTC (rev 1062) @@ -75,16 +75,18 @@ **/ public static String[] parseContentTypeHeader( String header ) { String[] result = new String[] { "text/plain", null }; - StringTokenizer st = new StringTokenizer( header, ";=" ); - result[0] = st.nextToken(); - while (st.hasMoreTokens()) { - String parameter = st.nextToken(); - if (st.hasMoreTokens()) { - String value = stripQuotes( st.nextToken() ); - if (parameter.trim().equalsIgnoreCase( "charset" )) { - result[1] = value; - } - } + if (header.trim().length()>0){ + StringTokenizer st = new StringTokenizer( header, ";=" ); + result[0] = st.nextToken(); + while (st.hasMoreTokens()) { + String parameter = st.nextToken(); + if (st.hasMoreTokens()) { + String value = stripQuotes( st.nextToken() ); + if (parameter.trim().equalsIgnoreCase( "charset" )) { + result[1] = value; + } + } + } } return result; } Modified: trunk/httpunit/src/com/meterware/pseudoserver/PseudoServer.java =================================================================== --- trunk/httpunit/src/com/meterware/pseudoserver/PseudoServer.java 2009-09-10 05:23:52 UTC (rev 1061) +++ trunk/httpunit/src/com/meterware/pseudoserver/PseudoServer.java 2009-12-22 15:34:27 UTC (rev 1062) @@ -266,7 +266,7 @@ private boolean _active = true; - private boolean _debug; + private boolean _debug=true; private String asResourceName( String rawName ) { Modified: trunk/httpunit/test/com/meterware/httpunit/EncodingTest.java =================================================================== --- trunk/httpunit/test/com/meterware/httpunit/EncodingTest.java 2009-09-10 05:23:52 UTC (rev 1061) +++ trunk/httpunit/test/com/meterware/httpunit/EncodingTest.java 2009-12-22 15:34:27 UTC (rev 1062) @@ -62,6 +62,7 @@ */ public void testParseContentHeader() throws Exception { String headers[]={ + "", "text/plain", "text/html; charset=Cp1252", "text/html; charset=iso-8859-8", @@ -69,6 +70,7 @@ }; String expected[][]={ {"text/plain",null}, + {"text/plain",null}, {"text/html","Cp1252"}, {"text/html","iso-8859-8"}, {"text/html","EUC-JP"} Modified: trunk/httpunit/test/com/meterware/httpunit/MessageBodyRequestTest.java =================================================================== --- trunk/httpunit/test/com/meterware/httpunit/MessageBodyRequestTest.java 2009-09-10 05:23:52 UTC (rev 1061) +++ trunk/httpunit/test/com/meterware/httpunit/MessageBodyRequestTest.java 2009-12-22 15:34:27 UTC (rev 1062) @@ -27,6 +27,7 @@ import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.IOException; +import java.io.UnsupportedEncodingException; import junit.framework.Test; import junit.framework.TestSuite; @@ -51,21 +52,49 @@ public void setUp() throws Exception { super.setUp(); } - - public void testGenericPostRequest() throws Exception { - defineResource("ReportData", new BodyEcho()); - String sourceData = "This is an interesting test\nWith two lines"; + + /** + * make a Request from the given parameters + * @param resourceName + * @param sourceData + * @param contentType + * @return the new WebRequest + * @throws UnsupportedEncodingException + */ + public WebRequest makeRequest(String resourceName,String sourceData, String contentType) throws UnsupportedEncodingException{ + defineResource(resourceName, new BodyEcho()); InputStream source = new ByteArrayInputStream(sourceData .getBytes("iso-8859-1")); + WebRequest wr = new PostMethodWebRequest(getHostPath() + "/"+resourceName, + source, contentType); + return wr; + } + /** + * test a generic Post request + * @throws Exception + */ + public void testGenericPostRequest() throws Exception { WebConversation wc = new WebConversation(); - WebRequest wr = new PostMethodWebRequest(getHostPath() + "/ReportData", - source, "text/sample"); + String sourceData="This is an interesting test\nWith two lines"; + WebRequest wr = makeRequest("ReportData",sourceData, "text/sample"); WebResponse response = wc.getResponse(wr); assertEquals("Body response", "\nPOST\n" + sourceData, response .getText()); assertEquals("Content-type", "text/sample", response.getContentType()); } + + /** + * test for Patch by Serge Maslyukov for empty content Types + * @throws Exception + */ + public void testEmptyContentType() throws Exception { + WebConversation wc = new WebConversation(); + String emptyContentType=""; // this is an emptyContentType + WebRequest wr = makeRequest("something","some data",emptyContentType); + WebResponse response = wc.getResponse(wr); + assertEquals("Content-type", "",wr.getContentType()); + } public void testPutRequest() throws Exception { defineResource("ReportData", new BodyEcho()); Modified: trunk/httpunit/test/com/meterware/httpunit/WebClientTest.java =================================================================== --- trunk/httpunit/test/com/meterware/httpunit/WebClientTest.java 2009-09-10 05:23:52 UTC (rev 1061) +++ trunk/httpunit/test/com/meterware/httpunit/WebClientTest.java 2009-12-22 15:34:27 UTC (rev 1062) @@ -643,7 +643,7 @@ * @throws Exception */ public void dotestRefererHeader(boolean refererEnabled) throws Exception { - String resourceName = "tellMe"; + String resourceName = "tellMe"+refererEnabled; String linkSource = "fromLink"; String formSource = "fromForm"; @@ -651,8 +651,8 @@ String page1 = getHostPath() + '/' + linkSource; String page2 = getHostPath() + '/' + formSource; - defineResource( linkSource, "<html><head></head><body><a href=\"tellMe\">Go</a></body></html>" ); - defineResource( formSource, "<html><body><form action=\"tellMe\"><input type=submit></form></body></html>" ); + defineResource( linkSource, "<html><head></head><body><a href=\""+resourceName+"\">Go</a></body></html>" ); + defineResource( formSource, "<html><body><form action=\""+resourceName+"\"><input type=submit></form></body></html>" ); defineResource( resourceName, new PseudoServlet() { public WebResource getGetResponse() { String referer = getHeader( "Referer" ); Modified: trunk/httpunit/test/com/meterware/httpunit/javascript/NekoEnhancedScriptingTest.java =================================================================== --- trunk/httpunit/test/com/meterware/httpunit/javascript/NekoEnhancedScriptingTest.java 2009-09-10 05:23:52 UTC (rev 1061) +++ trunk/httpunit/test/com/meterware/httpunit/javascript/NekoEnhancedScriptingTest.java 2009-12-22 15:34:27 UTC (rev 1062) @@ -49,7 +49,7 @@ public void testEmbeddedDocumentWrite() throws Exception { - defineResource( "OnCommand.html", "<html><head><title>something</title></head>" + + defineResource( "OnCommandWrite.html", "<html><head><title>something</title></head>" + "<body>" + "<script language='JavaScript'>" + "document.write( '<a id=here href=about:blank>' );" + @@ -58,7 +58,7 @@ "</script>" + "</body></html>" ); WebConversation wc = new WebConversation(); - WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" ); + WebResponse response = wc.getResponse( getHostPath() + "/OnCommandWrite.html" ); WebLink link = response.getLinkWithID( "here" ); assertNotNull( "The link was not found", link ); assertEquals( "Link contents", "something", link.getText() ); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <wol...@us...> - 2010-05-07 12:13:02
|
Revision: 1067 http://httpunit.svn.sourceforge.net/httpunit/?rev=1067&view=rev Author: wolfgang_fahl Date: 2010-05-07 12:12:22 +0000 (Fri, 07 May 2010) Log Message: ----------- patch for parseContentTypeHeader by Serge Maslyukov Modified Paths: -------------- trunk/httpunit/src/com/meterware/httpunit/HttpUnitUtils.java trunk/httpunit/test/com/meterware/httpunit/EncodingTest.java Modified: trunk/httpunit/src/com/meterware/httpunit/HttpUnitUtils.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/HttpUnitUtils.java 2010-05-07 11:58:36 UTC (rev 1066) +++ trunk/httpunit/src/com/meterware/httpunit/HttpUnitUtils.java 2010-05-07 12:12:22 UTC (rev 1067) @@ -71,12 +71,12 @@ * Returns the content type and encoding as a pair of strings. * If no character set is specified, the second entry will be null. * @param header the header to parse - * @return a string array with the content type and the content charset + * @return a string array with the content type and the content char set **/ public static String[] parseContentTypeHeader( String header ) { String[] result = new String[] { "text/plain", null }; if (header.trim().length()>0){ - StringTokenizer st = new StringTokenizer( header, ";=" ); + StringTokenizer st = new StringTokenizer( header, ";= " ); result[0] = st.nextToken(); while (st.hasMoreTokens()) { String parameter = st.nextToken(); Modified: trunk/httpunit/test/com/meterware/httpunit/EncodingTest.java =================================================================== --- trunk/httpunit/test/com/meterware/httpunit/EncodingTest.java 2010-05-07 11:58:36 UTC (rev 1066) +++ trunk/httpunit/test/com/meterware/httpunit/EncodingTest.java 2010-05-07 12:12:22 UTC (rev 1067) @@ -66,23 +66,31 @@ "text/plain", "text/html; charset=Cp1252", "text/html; charset=iso-8859-8", - "text/html; charset=EUC-JP" + "text/html; charset=EUC-JP", + "text/html charset=windows-1251", + "text/html; charset=utf-8", + "text/html; charset = utf-8", + "text/html; charset=\"iso-8859-8\"" }; String expected[][]={ {"text/plain",null}, {"text/plain",null}, {"text/html","Cp1252"}, {"text/html","iso-8859-8"}, - {"text/html","EUC-JP"} + {"text/html","EUC-JP"}, + {"text/html","windows-1251"}, + {"text/html","utf-8"}, + {"text/html","utf-8"}, + {"text/html","iso-8859-8"} }; for (int i=0;i<headers.length;i++) { String result[]=HttpUnitUtils.parseContentTypeHeader(headers[i]); + assertEquals(2, result.length); assertEquals( "header "+i , expected[i][0] , result[0]); assertEquals( "header "+i , expected[i][1] , result[1]); } // for } - public void testSpecifiedEncoding() throws Exception { String hebrewTitle = "\u05d0\u05d1\u05d2\u05d3"; String page = "<html><head><title>" + hebrewTitle + "</title></head>\n" + This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <wol...@us...> - 2010-05-07 12:39:10
|
Revision: 1068 http://httpunit.svn.sourceforge.net/httpunit/?rev=1068&view=rev Author: wolfgang_fahl Date: 2010-05-07 12:39:04 +0000 (Fri, 07 May 2010) Log Message: ----------- patch by Serge Maslyukov for Triple dotted path handling Modified Paths: -------------- trunk/httpunit/src/com/meterware/httpunit/WebRequest.java trunk/httpunit/test/com/meterware/httpunit/NormalizeURLTest.java Modified: trunk/httpunit/src/com/meterware/httpunit/WebRequest.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/WebRequest.java 2010-05-07 12:12:22 UTC (rev 1067) +++ trunk/httpunit/src/com/meterware/httpunit/WebRequest.java 2010-05-07 12:39:04 UTC (rev 1068) @@ -142,7 +142,7 @@ private String getNormalizedPath( String path ) { if (path.lastIndexOf( "//" ) > path.lastIndexOf( "://" ) + 1) return getNormalizedPath( stripDoubleSlashes( path ) ); - if (path.indexOf( "/.." ) > 0) return getNormalizedPath( stripUpNavigation( path ) ); + if (path.indexOf( "/../" )>0 || path.endsWith("/..")) return getNormalizedPath( stripUpNavigation( path ) ); if (path.indexOf( "/./" ) > 0) return getNormalizedPath( stripInPlaceNavigation( path ) ); return path; } Modified: trunk/httpunit/test/com/meterware/httpunit/NormalizeURLTest.java =================================================================== --- trunk/httpunit/test/com/meterware/httpunit/NormalizeURLTest.java 2010-05-07 12:12:22 UTC (rev 1067) +++ trunk/httpunit/test/com/meterware/httpunit/NormalizeURLTest.java 2010-05-07 12:39:04 UTC (rev 1068) @@ -238,6 +238,15 @@ WebRequest request = new GetMethodWebRequest( "http://host.name/directory1/directory2/../../file.html" ); assertEquals( "URL", request.getURL().toExternalForm(), "http://host.name/file.html" ); } + + /** + * patch by Serge Maslyukov + * @throws Exception + */ + public void testTripleDottedPath() throws Exception { + WebRequest request = new GetMethodWebRequest( "http://en.wikipedia.org/wiki/...And_Found" ); + assertEquals( "URL", request.getURL().toExternalForm(), "http://en.wikipedia.org/wiki/...And_Found" ); + } /* This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <wol...@us...> - 2011-01-29 08:27:03
|
Revision: 1077 http://httpunit.svn.sourceforge.net/httpunit/?rev=1077&view=rev Author: wolfgang_fahl Date: 2011-01-29 08:26:57 +0000 (Sat, 29 Jan 2011) Log Message: ----------- fix of BR2822484 by gcc with supplied patch file httpunit-textarea-090923.patch Modified Paths: -------------- trunk/httpunit/src/com/meterware/httpunit/dom/HTMLTextAreaElementImpl.java trunk/httpunit/src/com/meterware/httpunit/protocol/MimeEncodedMessageBody.java trunk/httpunit/test/com/meterware/servletunit/PostTest.java Modified: trunk/httpunit/src/com/meterware/httpunit/dom/HTMLTextAreaElementImpl.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/dom/HTMLTextAreaElementImpl.java 2011-01-29 08:17:17 UTC (rev 1076) +++ trunk/httpunit/src/com/meterware/httpunit/dom/HTMLTextAreaElementImpl.java 2011-01-29 08:26:57 UTC (rev 1077) @@ -64,7 +64,17 @@ public String getDefaultValue() { Node node = getFirstChild(); - if (node == null || node.getNodeType() != Node.TEXT_NODE) return null; + + if (node == null) + { + return ""; + } + + if (node.getNodeType() != Node.TEXT_NODE) + { + return null; + } + return node.getNodeValue(); } Modified: trunk/httpunit/src/com/meterware/httpunit/protocol/MimeEncodedMessageBody.java =================================================================== --- trunk/httpunit/src/com/meterware/httpunit/protocol/MimeEncodedMessageBody.java 2011-01-29 08:17:17 UTC (rev 1076) +++ trunk/httpunit/src/com/meterware/httpunit/protocol/MimeEncodedMessageBody.java 2011-01-29 08:26:57 UTC (rev 1077) @@ -102,7 +102,7 @@ */ public void addParameter( String name, String value, String characterSet ) throws IOException { if (name == null || name.length() == 0) return; - if (value == null || value.length() == 0) return; + if (value == null) return; writeLn( _outputStream, "--" + BOUNDARY ); writeLn( _outputStream, "Content-Disposition: form-data; name=\"" + name + '"' ); // XXX need to handle non-ascii names here writeLn( _outputStream, "Content-Type: text/plain; charset=" + getCharacterSet() ); Modified: trunk/httpunit/test/com/meterware/servletunit/PostTest.java =================================================================== --- trunk/httpunit/test/com/meterware/servletunit/PostTest.java 2011-01-29 08:17:17 UTC (rev 1076) +++ trunk/httpunit/test/com/meterware/servletunit/PostTest.java 2011-01-29 08:26:57 UTC (rev 1077) @@ -126,6 +126,23 @@ } } + public void testMultiPartPost() throws Exception { + TestServlet.location="http://localhost/"; + + ServletRunner sr = new ServletRunner(); + sr.registerServlet(resourceName, TestServlet.class.getName()); + + WebRequest request = new GetMethodWebRequest(TestServlet.location+resourceName); + WebResponse response = sr.getResponse(request); + + WebForm form = response.getFormWithID("multipart-bug"); + response = form.submit(); + + assertEquals(true, response.getText().contains("name=\"empty\"")); + assertEquals(true, response.getText().contains("name=\"empty_textarea\"")); + //check(response); + } + /** * a Servlet that counts the posts being done */ @@ -139,7 +156,19 @@ response .getWriter() .println( - "<html><body><form action='"+location+resourceName+"' method='post' id='bug'><input name='handle'/><input name='brainz'/></form></body></html>"); + "<html>" + + "<body>" + + "<form action='"+location+resourceName+"' method='post' id='bug'>" + + "<input name='handle'/>" + + "<input name='brainz'/>" + + "</form>" + + "<form id='multipart-bug' method='post' action='"+location+resourceName+"' enctype='multipart/form-data'>" + + "<input name='empty' value=''>" + + "<input name='notempty' value='1'>" + + "<textarea name='empty_textarea'></textarea>" + + "</form>" + + "</body>" + + "</html>"); /* if (request instanceof Request) ((Request) request).setHandled(true); @@ -149,6 +178,13 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { postCount++; + InputStream is = request.getInputStream(); + OutputStream os = response.getOutputStream(); + byte [] buffer = new byte [4096]; + for (int length = is.read(buffer); length > 0; length = is.read(buffer)) + { + os.write(buffer, 0, length); + } } } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |