JaVa
   

Package com.meterware.httpunit

This package contains all the classes that comprise the HttpUnit framework. The key classes in the framework are WebConversation (and its parent class WebClient), WebRequest, and WebResponse. A few classes represent elements of an HTML page (e.g., WebLink and WebTable), others sublclass one of the three central players (e.g., PostMethodWebRequest) to provide specific functionality, and a final few act in a supporting role (HttpUnitException, for instance.)

Class AuthorizationRequiredException

public class AuthorizationRequiredException extends RuntimeException


Inheritance Information

Extends: Object

Implements: Serializable

Description

AuthorizationRequiredException is thrown when the server returns a response that indicates the user must be authorized to view the resource. (See the section on WebClient for an example.)

Methods

getAuthenticationParameter(String parameterName)
public String getAuthenticationParameter(String parameterName)


This method returns the authentication value for the specified parameter. Under the Basic authentication scheme, there is only one parameter: "realm".

getAuthenticationScheme()
public String getAuthenticationScheme()


This method returns the authentication scheme used for this resource: Basic or Digest.

getMessage()
public String getMessage()


Class GetMethodWebRequest

public class GetMethodWebRequest


Inheritance Information

Extends: WebRequestDescription

GetMethodWebRequest is a WebRequest that uses the GET method (see the section on WebRequest for more details).

Constructors

GetMethodWebRequest(String urlString)
public GetMethodWebRequest(String urlString)
GetMethodWebRequest(URL urlBase, String urlString)
public GetMethodWebRequest(URL urlBase, String urlString)
GetMethodWebRequest(URL urlBase, String urlString, String target)
public GetMethodWebRequest(URL urlBase, String urlString, String target)


See the section on WebRequest for a description of these constructors.

Methods

getMethod()
public String getMethod()


This method returns the HTTP method of the request (in this case, GET).

getURLString()
protected String getURLString()


This method returns the full URL of the request, including all the parameters set with setParameter encoded in the query string.

Class HTMLSegment

public interface HTMLSegment


Inheritance Information

Known implementing classes: WebResponse, TableCellDescription HTMLSegment defines the public interface for a chunk of parsed HTML. This interface specifies finder methods for elements of HTML represented in HttpUnit: forms, tables, and links. All the methods in this interface will throw org.xml.sax.SAXExceptions if errors occur when the underlying HTML is parsed. Many of the examples in this chapter use functionality contained in this interface. See the sections on WebForm, WebLink, and WebTable to see its methods in use.

Much of the functionality contained in WebResponse is described in this section.

Methods

getForms()
public WebForm[] getForms() throws SAXException;


This method returns an array corresponding to the forms found within the HTML segment, in the order in which they occur.

getFormWithID(String ID)
public WebForm getFormWithID(String ID) throws SAXException


This method gets the form with the specified “id” attribute.

getFormWithName(String name) 
public WebForm getFormWithName(String name) throws SAXException


This method gets the form with the specified “name” attribute.

getLinks()
public WebLink[] getLinks() throws SAXException


This method returns an array corresponding to the links found within the HTML segment, in the order in which they appear.

getLinkWith(String text) 
public WebLink getLinkWith(String text) throws SAXException


This method gets the first link with the specified user-clickable text in the underlying HTML.

getLinkWithImageText(String text)
public WebLink getLinkWithImageText(String text) throws SAXException


This method gets the first image link with the specified text as its “alt” attribute in the underlying HTML.

getTables()
public WebTable[] getTables() throws SAXException


This method returns an array corresponding to the top-level tables found within the HTML segment, in the order in which they appear.

getTableStartingWith(String text)
public WebTable getTableStartingWith(final String text) throws
 SAXException


This method returns the first table in the HTML segment that has the specified text as the entire contents of its first non-blank row and non-blank column (no partial matches are allowed). Both getTableStartingWith(final String text) and getTableStarting- WithPrefix(String text) will recurse into any nested tables in an attempt to match their search criteria.

getTableStartingWithPrefix(String text)
public WebTable getTableStartingWithPrefix(String text) throws SAXException


This method returns the first table in the HTML segment that has the specified text as the beginning of the contents of its first non-blank row and non-blank column (in other words, partial matches are allowed). See the following list for an example.

/* Supposing that the response object was based on the following HTML:
<!--begin-->
<table>
 <tr>
 <td>
 Pizza Hut
 </td>
 <td>
 restaurant
 </td>
 </tr>
</table>
<table>
 <tr>
 <td>
 Pizza
 </td>
 <td>
 Food
 </td>
 </tr>
</table>
<!--end-->
The following test would pass:
*/
public void testTableMatching() throws Exception{
 /*will retrieve the second table because a full match is required*/
 WebTable foodTable = response.getTableStartingWith("Pizza");
 /*will retrieve the first table as the prefix matches*/
 WebTable restaurantTable = response.getTableStartingWithPrefix("Pizza");
 assertEquals("Food", foodTable.getCellAsText(0,1));
 assertEquals("restaurant", restaurantTable.getCellAsText(0,1));
}
getTableWithSummary(String summary)
public WebTable getTableWithSummary(String summary) throws SAXException


This method returns the first table with the specified String as its "summary" attribute.

getTableWithID(final String ID)
public WebTable getTableWithID(final String ID) throws SAXException


This method returns the first table with the specified String as its "id" attribute.

Class HttpException

public class HttpException


Inheritance Information

Extends: RuntimeException

Direct known subclasses: HttpInternalErrorException, HttpNotFoundException

Description

HttpException is thrown when the Web server under test would return a status code corresponding to a client or server error (4xx or 5xx):

public void testIllegalPageAccess() throws Exception{
 WebConversation wc = new WebConversation();
 try{
 wc.getResponse("http://www.junit.org/thispagedoesnotexist.jsp");
 }
 catch (HttpException e){
 System.out.println(e);
 assertEquals(404, e.getResponseCode());
 } }


Methods

getResponseCode()
public int getResponseCode()


This method returns the HTTP status code of the response that caused the exception.

getMessage()
public String getMessage()


This method returns a String containing the status code as well as the reason given (if any) for the error.

Class HttpInternalErrorException

public class HttpInternalErrorExceptionInheritance Information


Inheritance Information

Extends: HttpExceptionDescription

HttpInternalErrorException is thrown when a request results in a response with a status code of 5xx (server error). See the section on HttpException for details.

Class HttpNotFoundException

public class HttpNotFoundException


Inheritance Information

Extends: HttpException

Description

HttpNotFoundException is thrown when a request results in a response with a status code of 4xx (client error, generally a “not found” error). See the section on HttpException for details.

Class HttpUnitOptions

public abstract class HttpUnitOptions


Description

This class provides static setters and getters for a variety of properties that parameterize the behavior of HttpUnit. Because the options are stored in static member variables (and will thus affect all HttpUnit tests) , we advise you to take care in setting them. The preferred strategy is to use setUp() to set the parameter and tearDown() to reset it to its default value:

public void setUp(){
 HttpUnitOptions.setParserWarningsEnabled(true); }
public void tearDown(){
 HttpUnitOptions.setParserWarningsEnabled(false);
}


For options that should be set for entire suites of tests, you can use junit.extensions.TestSetup to make the setting and resetting of the property apply to the suite as a whole.

Methods

This “Methods” section is presented a little differently than others because HttpUnitOptions essentially consists of a set of exposed properties. Therefore, we’ve grouped the setters and getters instead of presenting them in alphabetical order.

autoRefresh
public static boolean getAutoRefresh()
public static void setAutoRefresh(boolean autoRefresh)


Default = false. This option specifies whether the WebClient automatically follows page refresh requests (that is, immediately calls getResponse() on the refresh request if latestResponse.getRefreshRequest() does not return null). The default of false allows for the redirect page to be inspected before the next page appears. Setting this property to true could result in an infinite loop if a page refreshes itself.

defaultCharacterSet
public static String getDefaultCharacterSet()
public static void setDefaultCharacterSet(String characterSet) public static void resetDefaultCharacterSet()


Default = "iso-8859-1". This option specifies the character encoding that will be used for responses that do not specify encoding in their content-type header. resetDefaultCharacterSet() resets the default character set to iso-8859-1.

imagesTreatedAsAltText
public static boolean getImagesTreatedAsAltText()
public static void setImagesTreatedAsAltText(boolean asText)


Default = false. If this option is set to true, images will be treated as the value of their "alt" attribute for the purpose of searches (for example, WebResponse.getLinkWith(String)) and displays.

loggingHttpHeaders
public static boolean isLoggingHttpHeaders()
public static void setLoggingHttpHeaders(boolean enabled)


Default = false. If this option is set to true, both incoming and outgoing HTTP headers are logged to the System.out stream.

matchesIgnoreCase
public static boolean getMatchesIgnoreCase()
public static void setMatchesIgnoreCase( boolean ignoreCase )


Default = true (matches are case insensitive). This option controls whether methods such as WebResponse.getTableStartingWith() are case-sensitive in their attempts to match the arguments to the returned HTML.

parameterValuesValidated
public static boolean getParameterValuesValidated()
public static void setParameterValuesValidated(boolean validated)


Default = true. This option specifies whether the values that are set in a WebRequest are checked against the legal values that the underlying form (if any) would allow.

parserWarningsEnabled
public static boolean getParserWarningsEnabled()
public static void setParserWarningsEnabled(boolean enabled)


Default = false. If this option is set to true, JTidy (the HTML parser used by HttpUnit) will print warnings to the System.out stream when it encounters HTML that is not structured according to the specification. This option can be useful in debugging unexpected results from HttpUnit. (See the section on WebForm for more information.)

redirectDelay
public static int getRedirectDelay()
public static void setRedirectDelay(int delayInMilliseconds)


Default = 0 milliseconds. This option controls how long WebClient will wait before following a redirect. It may need to be set higher if the server will not be ready for the redirect request immediately after the redirect is sent (an uncommon occurrence).

Class HttpUnitUtils

public class HttpUnitUtils


Description

HttpUnitUtils is used internally by WebResponse; it provides a static method to parse a header for content type and encoding information. Content type can also be retrieved from WebResponse.getContentType():

public void testContentAndEncoding()throws Exception{
 WebConversation wc = new WebConversation();
 WebResponse response = wc.getResponse("http://www.objectmentor.com/");
 String header = response.getHeaderField("Content-type");
 String[] typeAndEncoding = HttpUnitUtils.parseContentTypeHeader(header);
 assertEquals("text/html", typeAndEncoding[0]);
 /*don't expect encoding to be included*/
 assertNull(typeAndEncoding[1]);
}


Method

parseContentTypeHeader(String header)
public static String[] parseContentTypeHeader(String header)


The returned array contains the content type and the character encoding contained in the header (in that order). If no character encoding information is included, the second entry will be null.

Class IllegalRequestParameterException

public abstract class IllegalRequestParameterException


Inheritance Information

Extends: RuntimeException

Direct known subclasses: IllegalFileParameterException, IllegalNonFileParameterException, IllegalParameterValueException, IllegalSubmitButtonException, IllegalUnnamedSubmitButtonException, MultipartFormRequiredException, NoSuchParameterException, SingleValuedParameterException

Description

IllegalRequestParameterException is thrown when code attempts to set a request parameter that could not be set in a Web browser. See the section on WebForm for a description of how to create a request associated with an HTML form. Various inner exception classes extend IllegalRequestParameterException to provide more specific information about the exact violation of the form’s potential parameters. Most of the exceptions are self-explanatory and include helpful information in their messages (see the “Inheritance Information” section for a list of these exceptions). Following is an example of using IllegalRequestParameterException:

public void testIllegalSetting() throws Exception {
 WebConversation wc = new WebConversation();
 WebResponse resp = wc.getResponse("http://www.flimflam.com/order");
 WebForm form = response.getFormWithName("product_choice");
 WebRequest submit = form.getRequest();
 submit.setParameter("product_id", "101");//ok
 try{
 submit.setParameter("shipping_method", "Ultra-quick");
 fail("Ultra-quick shipping only availaible to logged-in users.");
 }
 catch(IllegalRequestParameterException e){}
}


Class MessageBodyWebRequest

public abstract class MessageBodyWebRequest


Inheritance Information

Extends: WebRequest

Direct known subclasses: PostMethodWebRequest, PutMethodWebRequest

Description

This class is used internally to support the stream-handling needs of PostMethodWebRequest and PutMethodWebRequest.

Methods

MessageBody newMessageBody();
protected abstract MessageBody newMessageBody();
completeRequest(URLConnection connection)
protected void completeRequest(URLConnection connection)


Class PostMethodWebRequest

public abstract class PostMethodWebRequestInheritance Information


Inheritance Information

Extends: MessageBodyWebRequest

Description

PostMethodWebRequest represents a request using the POST method. Tests will usually interact with this object through its superclass WebRequest (see the section on that class for details).

Constructors

PostMethodWebRequest(String urlString)
public PostMethodWebRequest(String urlString)
PostMethodWebRequest(String urlString, InputStream source,
 String contentType)
public PostMethodWebRequest(String urlString, InputStream source, String contentType)


This constructor constructs a PostMethodWebRequest that uses the specified InputStream as the message body, overriding any parameters/files set by other means. The “contentType” parameter specifies the content type of the body, including any character set information.

PostMethodWebRequest(URL urlBase, String urlString, String target)
public PostMethodWebRequest(URL urlBase, String urlString, String target)


Methods

MessageBody newMessageBody();
protected MessageBody newMessageBody();


This method returns a MessageBody containing the stream specified by the constructor (if any), or an encoded representation of the parameters and files set so far on this request. newMessageBody() is used by the framework to select how the request will be written to the java.net.URLConnection.

String getMethod()
public String getMethod()


This method returns the method of this request (in this case, POST).

selectFile(String parameterName, File file)
public void selectFile( String parameterName, File file )
selectFile(String parameterName, File file, String contentType)
public void selectFile(String parameterName, File file,String contentType)


These methods specify a file to be included in the request. They will throw an IllegalRequestParameter if the “parameterName” does not correspond to an expected file parameter.

Class PutMethodWebRequest

public class PutMethodWebRequest


Inheritance Information

Extends: MessageBodyWebRequest

Description

PutMethodWebRequest represents a request using the PUT method.

Any parameters or files specified with selectFile() or setParameter() will be ignored. The content of the request is solely specified by the InputStream provided to the constructor.

Constructor

PutMethodWebRequest(String url, InputStream source, String contentType)
public PutMethodWebRequest(String url, InputStream source, String contentType)


This constructor constructs a request with the specified InputStream forming the body of the request (the request headers are the only other information that will be sent). The “contentType” parameter specifies the content type of the body, including any character set information.

Methods

String getMethod()
public String getMethod()


This method returns the method of this request (in this case, PUT).

MessageBody newMessageBody()
protected MessageBody newMessageBody()


This method returns a MessageBody based solely on the InputStream provided in the constructor.

Class SubmitButton

public class SubmitButtonInheritance 


Information

Extends: Object

Description

SubmitButton represents a submit button in an HTML form. It’s used with WebForm to create form submissions that simulate the user clicking a particular button. (See the section on WebForm for details and an example.)

Methods

getName()
public String getName()


This method returns the name of the button.

getValue()
public String getValue()


This method returns the value of the button.

isImageButton()
public boolean isImageButton()


This method returns true if the button is an image map.

Class TableCell

public class TableCell


Inheritance Information

Extends: ParsedHTML (package-access-level class)

Implements: HTMLSegment

Description

TableCell represents a cell in an HTML table. This class implements the HTMLSegment interface (see the section on that interface for more details), so test developers can interact with it through the methods (getLinks, getForms, getTables, and so on) defined there. In addition, TableCell provides a few methods specific to table cells (see the section on WebTable for an example).

Methods

asText()
public String asText()


This method returns the contents of the cell as a String.

getColSpan()
public int getColSpan()


This method returns the value of the “colspan” attribute of this cell in the underlying HTML document.

getDOM()
public org.w3c.dom.Node getDOM()


This method returns an org.w3c.dom.Node corresponding to the contents of this table cell represented as a DOM.

getRowSpan()
public int getRowSpan()


This method returns the value of the “rowspan” attribute of this cell in the underlying HTML document.

Class WebClient

public abstract class WebClient


Inheritance Information

Extends: ObjectDescription WebClient emulates a Web browser for the purpose of maintaining context for a series of HTTP requests. It manages cookies, computes relative URLs, and presents a single object interface for sending requests to and retrieving responses from a server. Generally, every test method in an HttpUnit-based test case will need to access a WebClient. WebClient is an abstract class with a single concrete subclass (WebConversation) within the HttpUnit framework; the closely related ServletUnit framework defines another one. As such, you will primarily use instances of WebConversation to access the functionality of WebClient. The following example illustrates the basic use of WebClient/WebConversation:

public void testSiteAuthorization() throws Exception {
 WebConversation wc = new WebConversation();
 String siteUrl = "http://www.eDogFood.com/ordering.jsp";
 boolean caught = false;
 try{
 WebResponse resp = wc.getResponse(siteUrl);
 }
 catch(AuthorizationRequiredException e){
 System.out.println(e);
 caught = true;
 }
 assertTrue(caught);
 wc.setAuthorization("Jane Tester", "TestPassword123");
 WebResponse resp = wc.getResponse(siteUrl);
 assertEquals("Logged In - Welcome", resp.getTitle());
}


Methods

addCookie(String name, String value)
public void addCookie(String name, String value)


This method adds the specified name/value pair to the list of cookies to be sent with every request to the server. The server may also set such cookies:

public void testCookieLogonTransfer() throws Exception{
 WebConversation wc = new WebConversation();
 String siteUrl = "http://www.eDogFood.com/ordering.jsp";
 wc.setAuthorization("Jane Tester", "TestPassword123");
 WebResponse resp = wc.getResponse(siteUrl);
 String sessionIdKey = resp.getNewCookieNames()[0];
 String sessionIdValue = resp.getNewCookieValue(sessionKey);
 WebConversation newBrowser = new WebConversation();
 newBrowser.addCookie(sessionKey, sessionValue);
 newBrowser.getResponse(siteUrl);
 /*--would throw AuthorizationRequiredException if not logged in*/
}
getCookieHeaderField()
protected String getCookieHeaderField()


This method returns the value of the cookie header as a String. It appears to be used internally by WebClient, but it could be used externally for validation purposes.

getCookieNames()
public String[] getCookieNames()
getCookieValue(String name)
public String getCookieValue(String name)


These methods return the names and values of the active cookies that will be sent to the server with each request. (See addCookie() for an example.)

getFrameContents(String frameName)
public WebResponse getFrameContents(String frameName)


This method gets the contents of the frame with the specified name as a WebResponse. (See getFrameNames() for an example.)

getFrameNames()
public String[] getFrameNames()


This method returns a String[] containing the names of all the currently active frames in the virtual Web browser represented by the WebClient. The topmost frame can be retrieved with the keyword _top. As each request is made, the contents of the appropriate frame are replaced with the WebResponse resulting from the request. Assuming the String “fooFrame” is the target of the WebRequest request, resp and frame would refer to the same object after these lines were executed:

WebResponse resp = conversation.getResponse(request);
WebResponse frame = conversation.getFrameContents("fooFrame");


The next listing details how you can use frame interaction with HttpUnit. It may help to review the page the example is based on: http://java.oracle.com/j2se/1.3/docs/api/index.html (the Javadoc for class URLConnection in java.net).

public void testFrameInteraction() throws Exception{
 /*Note: uses collections from java.util*/
 String site = "http://java.oracle.com/j2se/1.3/docs/api/index.html";
 WebClient wc = new WebConversation();
 WebResponse response = wc.getResponse(site);
 /*assert that all of the expected frames exist*/
 String[] frameNames = wc.getFrameNames();
 List frameList = Arrays.asList(frameNames);
 assertTrue(frameList.contains("classFrame"));
 assertTrue(frameList.contains("packageListFrame"));
 assertTrue(frameList.contains("packageFrame"));
 assertTrue(frameList.contains("_top"));
 /*get the frame with the name 'packageFrame'*/
 response = wc.getFrameContents("packageFrame");
 /*follow a link which updates the classFrame
 *and assert that we end up in the correct place
 */
 WebLink link = response.getLinkWith("URLConnection");
 assertEquals("classFrame", link.getTarget());
 response = wc.getResponse(link.getRequest());
 String frameString = response.getText();
 assertTrue(frameString.indexOf("URLConnection") > -1);
 /*check that the frame that was updated was actually the classFrame */
 WebResponse frameContents = wc.getFrameContents("classFrame");
 assertSame(response, frameContents);
}
protected java.util.Dictionary getHeaderFields()


This method returns a Dictionary containing all the active headers that will be sent to the server (including headers set by earlier responses and also those set by calls to setHeaderField).

getResponse(java.lang.String urlString)
public WebResponse getResponse(java.lang.String urlString)
 throws java.net.MalformedURLException,
 java.io.IOException,
 org.xml.sax.SAXException


This method returns a WebResponse containing the result of a GET method request to the specified URL. It’s essentially a convenience method for getResponse(new GetMethodWebRequest(urlString)) (see that method for details).

getResponse(WebRequest request)
public WebResponse getResponse(WebRequest request)
 throws java.net.MalformedURLException,
 java.io.IOException,
 org.xml.sax.SAXException


One of the key methods in the HttpUnit API, getResponse() embodies a Web-browser request and server response. Functionally, it sends the specified WebRequest to the server using all the state information (cookies, headers, and so on) stored in the WebClient. The list of exceptions is large but manageable. In most test methods, you’ll want to declare that the test method throws Exception and allow JUnit to treat these occurrences as test failures. The java exceptions are simply passed on from classes in the java.net package (representing an illegal URL and IO problem during network connection respectively). The SAXException occurs when an error occurs while parsing the received page as XML.

getUserAgent()
public String getUserAgent()


This method gets the User-Agent header (the type of browser this WebClient is emulating) that is sent to the server.

newResponse(WebRequest request) 
protected abstract WebResponse newResponse(WebRequest request)
 throws java.net.MalformedURLException,
 java.io.IOException


This method is used internally to talk to the server and create a new WebResponse from the results.

setAuthorization(String userName, String password)
public void setAuthorization(String userName, String password)


This method sets the Authorization header using the basic authorization scheme. (See the “Description” section of this class for an example.)

setHeaderField(String fieldName, String fieldValue)
public void setHeaderField(String fieldName, String fieldValue)


This method sets a header that will be sent to the server with every request. If a header is set to null, that header is removed from future requests:

conversation.setHeaderField("Cache-Control", "Cache-Control : no-cache");
setUserAgent(String userAgent)
public void setUserAgent(String userAgent)


This method sets the User-Agent header (used to emulate a type of browser).

updateClient(WebResponse response)
protected final void updateClient(WebResponse response)
 throws java.net.MalformedURLException,
 java.io.IOException,
 org.xml.sax.SAXException


This method is used internally to update the state of the WebClient to reflect the results of the latest transaction.

Class WebConversation

public class WebConversation


Inheritance Information

Extends: WebClient

Description

WebConversation is the concrete implementation of WebClient; it provides no new external behavior. See the section on WebClient for details and examples.

Constructor

WebConversation()
public WebConversation()


Method

newResponse(WebRequest request)
protected WebResponse newResponse(WebRequest request)
 throws java.net.MalformedURLException,
 java.io.IOException


Class WebForm

public class WebForm


Inheritance Information

Extends: ObjectDescription This class represents an HTML form present in a Web page. It provides a variety of shortcut methods that make examining the form and writing assertions against it easier. It also provides the facility to create a WebRequest that simulates the submission of this form. (See the section on WebRequest for more details.)

A listing we discussed earlier (in the section on WebRequest) contains an example of using WebForm and WebRequest to access a form, verify it, and simulate a user’s submission to that form.

Methods

getCharacterSet()
public String getCharacterSet()


This method gets the character set encoding for this form. This information is contained in the Content-type header for the parent page.

getDOMSubtree()
public org.w3c.dom.Node getDOMSubtree()


This method returns a copy of the DOM Node representing this form in the underlying page.

getID()
public String getID()


This method gets the “id” attribute of this form from the underlying HTML.

getName()
public String getName()


This method gets the HTML form name.

getOptions(String name)
public String[] getOptions(String name)


This method gets an array of Strings corresponding to the displayed options for the specified parameter name.

getOptionValues(String name)
public String[] getOptionValues(String name)


This method gets an array of Strings corresponding to the option values for the specified parameter name.

getParameterNames()
public String[] getParameterNames()


This method returns the names of all of the input parameters in the form in order.

String getParameterValue(String name)
public String getParameterValue(String name)


This method gets the default value associated with the given input parameter, or the first default value if multiple values are possible.

getParameterValues(String name)
public String[] getParameterValues(String name)


This method gets an array corresponding to the default values of the given input parameter. (If the input parameter supports only one value, the array will contain a single element.)

getRequest()
public WebRequest getRequest() 


This method gets a request that simulates a submission of this form using the default button (see getRequest(SubmitButton button) for more information).

getRequest(String submitButtonName, String submitButtonValue)
public WebRequest getRequest(String submitButtonName, String submitButtonValue)


This method gets a request that simulates a submission of this form using a submit button with the specified name and value. It will throw an IllegalSubmitButtonException if no such button exists.

getRequest(String submitButtonName)
public WebRequest getRequest(String submitButtonName)


This method gets a request that simulates a submission of this form using a submit button with the specified name. It will throw an IllegalSubmitButtonException if no such button exists.

getRequest(SubmitButton button)
public WebRequest getRequest(SubmitButton button)


This method gets a request that simulates a submission of this form using the specified submit button. If the “button” argument is null, getRequest() will attempt to submit using the default button (either the unnamed form button or the only button available in the form).

getRequest(SubmitButton button, int x, int y)
public WebRequest getRequest(SubmitButton button, int x, int y)


This method acts like getRequest(SubmitButton button) except it also sets the submit position on the button to the specified coordinates. This method will have an effect only if the button is an image button.

getSubmitButton(String name)
public SubmitButton getSubmitButton(String name)


This method gets the submit button for this form with the specified name (or null if there is no such button).

getSubmitButton(String name, String value)
public SubmitButton getSubmitButton(String name, String value)


This method gets the submit button for this form with the specified name and value (or null if there is no such button).

getSubmitButtons()
public SubmitButton[] getSubmitButtons()


This method gets an array of all the buttons declared in this form.

getTarget()
public String getTarget()


This method returns the “target” attribute of the underlying HTML form, or the parent page’s target if no such attribute exists.

isFileParameter(String name)
public boolean isFileParameter(String name)


This method returns true if the named input parameter is of type “file”, or false if not.

isMultiValuedParameter(String name)
public boolean isMultiValuedParameter(String name)


This method returns true if the named input parameter accepts multiple values, or false if not.

isSubmitAsMime()
public boolean isSubmitAsMime()


This method returns true if the form should be submitted with MIME encoding (URLEncoding is the default setting).

isTextParameter(String name)
public boolean isTextParameter(String name)


This method returns true if the named input parameter accepts raw text, false if not.

Class WebLink

public class WebLink


Inheritance Information

Extends: ObjectDescription This class represents a link in an HTML page. You can retrieve the text of the link, the URL it points to, its target, or its DOM structure. WebLink also provides a method to get a WebRequest version of the link that can be fed back into a WebConversation/WebClient. The following example gets all the links on a page and follows each one. If no exceptions are thrown, the link is assumed to be good:

public void testAllLinks() throws Exception {
 WebConversation wc = new WebConversation();
 WebResponse response = wc.getResponse("http://www.objectmentor.com/");
 WebLink[] links = response.getLinks();
 for(int i =0; i < links.length; i++){
 WebResponse resp = wc.getResponse(links[i].getRequest());
 System.out.println(i+ " followed link " + links[i].getRequest().getURL());
 /*no exceptions, page is OK!*/
 }
}


Methods

asText()
public String asText()


This method returns the user-clickable text corresponding to this link.

getDOMSubtree()
public org.w3c.dom.Node getDOMSubtree()


This method returns a copy of the DOM Node representing this form in the underlying page.

getRequest()
public WebRequest getRequest()


This method gets a new WebRequest equivalent to a user click on the link.

getTarget()
public String getTarget()


This method gets the target frame for this link.

getURLString()
public String getURLString()


This method returns the “href” attribute of the underlying HTML tag.

Class WebRequest

public abstract class WebRequest


Inheritance Information

Extends: Object

Direct known subclasses: GetMethodWebRequest, MessageBodyWebRequest

Description

WebRequest represents a generic HTTP request to a Web server. This class is one of the most frequently used in the HttpUnit framework. Several other classes declare methods that return WebRequests representing specific types of requests (such as form submissions and link-clicks). WebRequests can also be 655 constructed from a String representing aURL. In all cases, you can set request parameters and inspect various properties of the request before sending it to the server through a WebClient. If you use a WebForm to create a WebRequest (and the parameterValuesValidated property of HttpUnitOptions is set to true), then the WebForm will restrict the possible values a given parameter can be set to. The following code snippet would not work unless jojoForm contained a parameter named “mojo” that accepted “zombo” as an input value:

WebForm jojoForm = response.getFormWithName("jojoForm");
WebRequest request = jojoForm.getRequest();
request.setParameter("mojo", "zombo");


As a result, some of the methods exposed as public in this class will always throw exceptions in certain subclasses (selectFile will never work in a GetMethodWebRequest, which cannot be based on a form). The listing below gives an example of using WebRequest and WebForm to simulate a user’s form submission.

//<form enctype="multipart/form-data" method="post">
//Name of Your Dog:<INPUT type="text" VALUE="Rover">
//<BR>
//Type Of Dog Food:
//<SELECT multiple>
//<OPTION VALUE="1">1. Kibbles & Bits</OPTION>
//<OPTION VALUE="2">2. Feisty Brand</OPTION>
//<OPTION VALUE="3" SELECTED>3. Chelmore Dog Crunch</OPTION>
//</SELECT>
//<BR>
//Tell us some activities your dog likes:<SELECT >
//<OPTION VALUE="frisbee">frisbee</OPTION>
//<OPTION VALUE="walks">walks</OPTION>
//<OPTION VALUE="dogGolf">Dog Golf!</OPTION>
//</select>
//<BR>
//Upload a Cute Dog Picture!:<input type="file" />
//<p>
//<input type="submit" value="Bark!"/>
//<input type="submit" value="Woof!"/>
//
//</form>
public void testFormSubmission() throws Exception{
 WebConversation wc = new WebConversation();
 WebResponse response = wc.getResponse("http://www.eDogFood.com");
 WebForm form = response.getFormWithName("dogInfo");
 /*check important parameters*/
 assertTrue(form.isFileParameter("dogPicture"));
 String[] activities = form.getParameterValues("activities");
 assertEquals("frisbee", activities[0]);
 /*Note: only gets the *selected* parameter values.*/
 assertTrue(form.isMultiValuedParameter("dogFood"));
 submitForm(form);
}
private void submitForm(WebForm form) throws Exception{
 /*could also use the shortcut methods to get a request*/
 SubmitButton button = form.getSubmitButton("submit", "Bark!");
 WebRequest request = form.getRequest(button);
 /*would throw an IllegalRequestParameterException-- activity is not in the list of acceptable values.*/
 //request.setParameter("activities", "canineBowling");
 request.selectFile("dogPicture", new java.io.File("C:\\edgar.jpg"));
 request.setParameter("dogFood", new String[]{"1","3"});
 /*Test submission without the Dog's name:*/
 request.removeParameter("name");
 WebResponse response = conversation.getResponse(request);
 /*do assertions on the response*/
}
WebRequest(String urlString)
protected WebRequest(String urlString)


This constructor constructs a new WebRequest to point to the specified URL (represented as a String).

WebRequest(URL urlBase, String urlString)
protected WebRequest(URL urlBase, String urlString)


This constructor constructs a WebRequest by concatenating the base URL with the relative urlString.

WebRequest(URL urlBase, String urlString, String target)
protected WebRequest(URL urlBase, String urlString, String target)


This constructor is the same as WebRequest(URL urlBase, String urlString), except it also specifies the target frame of the request.

WebRequest(URL urlBase, String urlString, String target, 
 WebForm sourceForm, SubmitButton button)
protected WebRequest(URL urlBase, String urlString, String target, WebForm sourceForm, SubmitButton button)
WebRequest(WebRequest baseRequest, String urlString, String target) protected WebRequest (WebRequest baseRequest, String urlString, String target) throws MalformedURLException


These two protected constructors are used internally by the framework to build requests out of forms and other requests.

Methods

completeRequestURLConnection connection)
protected void completeRequest(URLConnection connection) throws IOException


This method is meant to be overridden to provide the actual machinery for sending the request to the server using different methods (POST, GET, PUT, and so on).

getCharacterSet()
protected final String getCharacterSet()
getMethod()
public abstract String getMethod()


This method returns the method of the HTTP request (POST, GET, PUT, and so on).

getParameter(String name)
public String getParameter(String name)


This method returns the value of the named parameter in the request, or null if one has not been set.

getParameterNames()
public java.util.Enumeration getParameterNames()


This method returns an Enumeration containing the names of all the parameters set in the request so far (either using the methods of WebRequest or specified as defaults in the form on which this request is based).

getParameterString()
protected final String getParameterString()


See getQueryString().

getParameterValues(String name)
public String[] getParameterValues(String name)


This method returns all the values set so far for the named parameter as a String array.

getQueryString()
public String getQueryString()


This method returns the query string for this request. It will work even if the request would not generate a visible query string in real life. The number of characters in the query string is limited only by the capacity of the java String.

getTarget()
public String getTarget()


This method returns the target frame for this request.

getURL()
public java.net.URL getURL() throws MalformedURLException


This method returns a new URL corresponding to the URL that will be used to submit this request.

getURLBase()
protected final URL getURLBase()
getURLString()
protected String getURLString()
hasNoParameters()
protected final boolean hasNoParameters()
isFileParameter(String name)
protected boolean isFileParameter(String name)
isMimeEncoded()
protected final boolean isMimeEncoded()


These methods are all used internally by WebRequest and its subclasses.

removeParameter(String name)
public void removeParameter(String name)


This method removes a previously set parameter from the request.

selectFile(String parameterName, File file)
public void selectFile(String parameterName, File file)
selectFile(String parameterName, File file, String contentType)
public void selectFile(String parameterName, File file, String contentType)


These methods select a file for upload if the form this WebRequest is based on supports the named parameter as a file upload parameter.

setParameter(String name, String value)
public void setParameter(String name, String value)
setParameter(String name, String[] values)
public void setParameter(String name, String[] values)


These methods set the named parameter either to the single value or the String array, depending on which method is called. If the underlying form (if any) would not allow such a value to be set, an IllegalRequestParameterException will be thrown.

toString()
public String toString()


This method returns the method type and URL string for this request.

Class WebResponse

public abstract class WebResponse


Inheritance Information

Extends: Object

Implements: HTMLSegment

Description

WebResponse represents the response from the Web server to a request. It is one of the core abstractions of the HttpUnit framework. This class provides a variety of methods that expose properties of the underlying response for inspection. Users of the class can get a DOM tree representing the HTML document, get newly set cookie names and values, inspect header fields, and so on. A variety of examples of WebResponse use appear throughout this chapter. Because WebResponse is abstract, WebResponse objects that appear in HttpUnit tests will likely be of type HttpWebResponse (a package-level access class).

WebResponse implements the HTML segment interface. For the sake of brevity, methods belonging to that interface are defined and described there. WebResponse also declares several methods as protected. Because WebResponse is not meant to be subclassed as part of ordinary development, these methods are listed but not described.

Constructor

WebResponse(String target, URL url)
protected WebResponse(String target, URL url)


Methods

defineRawInputStream(InputStream inputStream)
protected final void defineRawInputStream(InputStream inputStream)
getCharacterSet()
public String getCharacterSet()


This method returns the charset portion (if any) of the HTTP Content-type header for this response.

getContentType()
public String getContentType()


This method returns the content type portion (as distinct from the character set portion) of the HTTP Content type header for this response.

getDOM()
public org.w3c.dom.Document getDOM() throws org.xml.SAXException


This method attempts to return the DOM tree associated with this response. If the response is determined to be HTML, a special HTML-savvy parser (JTidy) will be used. If not, a regular SAX parser will be used on the response text. If errors are encountered during parsing (for instance, if the response contains neither HTML nor XML), a SAXException will be thrown.

getFrameNames()
public String[] getFrameNames() throws SAXException


This method returns an array containing the names of all the frames contained in this page. You can retrieve the contents of individual frames by these names from the WebClient (see that section for details).

getHeaderField(String fieldName)
public String getHeaderField(String fieldName)


This method gets the contents of the header field specified by the given name:

public void testContentLength() throws Exception{
 WebConversation conversation = new WebConversation();
 WebResponse response = conversation.getResponse("http://www.junit.org");
 assertEquals("6575", response.getHeaderField("CONTENT-LENGTH"));
}
getInputStream()
public InputStream getInputStream()


This method returns the textual contents of this response as an input stream.

getNewCookieNames()
public String[] getNewCookieNames()


This method returns all the cookie names defined as part of this response. (See the section on WebClient.addCookie for an example of this method in action.)

getNewCookieValue(String name)
public String getNewCookieValue(String name)


This method returns the value associated with the given new cookie name (see getNewCookieNames()).

getRefreshDelay()
public int getRefreshDelay()


This method returns the delay specified by the refresh metatag contained in the header (or 0 if none is found). This delay corresponds the waiting period before a standard browser would follow the refresh request.

getRefreshRequest()
public WebRequest getRefreshRequest()


This method gets the WebRequest embodying the refresh URL contained in the refresh metatag in the header (or null if none exists).

getResponseCode()
public abstract int getResponseCode()


This method returns the HTTP response code for this request.

getTarget()
public String getTarget()


This method gets the frame in which the WebResponse resides (the default frame for any WebRequests originating from this response).

getTitle()
public String getTitle() throws SAXException


This method returns the title element of the underlying HTML page.

getText()
public String getText() throws IOException


This method returns a String representation of the underlying HTML page (roughly equivalent to calling “view source” in a traditional browser). This method is preferred over toString() for the retrieval of page contents.

getURL()
public java.net.URL getURL()


This method returns the URL of the request that generated this response.

isHTML()
public boolean isHTML()


This method returns true if the content type for the underlying page is specified as “text/html”.

loadResponseText()
protected void loadResponseText() throws IOException
newResponse(URLConnection connection)
public static WebResponse newResponse(URLConnection connection) throws IOException
readRefreshRequest(String contentTypeHeader)
protected final void readRefreshRequest(String contentTypeHeader)
setContentTypeHeaderString value)
protected void setContentTypeHeaderString value)
toString()
public String toString()


In the default implementation, this method returns the response text. In HttpWebResponse (the only concrete subclass in the HttpUnit API), it returns only the response headers.

Class WebTable

public class WebTable


Inheritance Information

Extends: ObjectDescription

WebTable represents an HTML table. It provides methods to get various attributes of a table (row count, column count, id, and summary) and methods to get single table cells (as TableCells or as text), and also lets you convert the entire table into a arraybased representation.

Methods

asText()
public String[][] asText()


This method returns the entire table as a two-dimensional String array. The first dimension contains the rows, and the second dimension contains the cells.

getCell(int row, int column) Deprecated
public String getCell(int row, int column)


Use getCellAsText(int row, int column).

getCellAsText(int row, int column)
public String getCellAsText(int row, int column)


This method returns the contents of the cell in the given position as text. The row and column numbers are zero based, and this method will throw an IndexOutOfBoundsException if the parameters are not within the table's range.

getColumnCount()
public int getColumnCount()
getID()
public String getID()
getRowCount()
public int getRowCount()
getSummary()
public String getSummary()
getTableCell(int row, int column)
public TableCell getTableCell(int row, int column)


This method returns the contents of the cell in the given position as a TableCell. The row and column numbers are zero based, and this method will throw an IndexOutOfBoundsException if the parameters are not within the table's range.

purgeEmptyCells()
public void purgeEmptyCells()


This method removes from this table all rows and columns in that do not contain anything.


JaVa
   
Comments