KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tonbeller > tbutils > httpunit > HttpUnitTestBase


1 package com.tonbeller.tbutils.httpunit;
2
3 import java.io.IOException JavaDoc;
4 import java.io.UnsupportedEncodingException JavaDoc;
5 import java.net.MalformedURLException JavaDoc;
6 import java.net.URLEncoder JavaDoc;
7 import java.util.Iterator JavaDoc;
8 import java.util.List JavaDoc;
9
10 import javax.xml.transform.TransformerException JavaDoc;
11
12 import junit.framework.TestCase;
13
14 import org.apache.log4j.Logger;
15 import org.jaxen.JaxenException;
16 import org.jaxen.XPath;
17 import org.jaxen.dom.DOMXPath;
18 import org.w3c.dom.Document JavaDoc;
19 import org.w3c.dom.Node JavaDoc;
20 import org.xml.sax.SAXException JavaDoc;
21
22 import com.meterware.httpunit.GetMethodWebRequest;
23 import com.meterware.httpunit.HttpUnitOptions;
24 import com.meterware.httpunit.SubmitButton;
25 import com.meterware.httpunit.TableCell;
26 import com.meterware.httpunit.WebConversation;
27 import com.meterware.httpunit.WebForm;
28 import com.meterware.httpunit.WebRequest;
29 import com.meterware.httpunit.WebResponse;
30 import com.meterware.httpunit.WebTable;
31
32 public abstract class HttpUnitTestBase extends TestCase {
33   private static Logger logger = Logger.getLogger(HttpUnitTestBase.class);
34
35   private String JavaDoc servletUrl;
36   private String JavaDoc jspName;
37   protected WebConversation wc;
38   protected HttpUnitUtils utils;
39
40   protected String JavaDoc formID = "form01";
41   private boolean checkHtmlErrors;
42
43   public HttpUnitTestBase(String JavaDoc name, String JavaDoc jspName) {
44     super(name);
45     this.jspName = jspName;
46   }
47
48   protected String JavaDoc getJspUrl() {
49     return servletUrl + "/" + jspName;
50   }
51
52   protected String JavaDoc getJspUrl(String JavaDoc paramName, String JavaDoc paramValue) {
53     if (paramName == null)
54       paramName = "";
55     if (paramValue == null)
56       paramValue = "";
57     try {
58       StringBuffer JavaDoc result = new StringBuffer JavaDoc();
59       result.append(servletUrl);
60       result.append("/");
61       result.append(jspName);
62       result.append("?");
63       result.append(paramName);
64       result.append("=");
65       result.append(URLEncoder.encode(paramValue, "ISO-8859-1"));
66
67       return result.toString();
68     } catch (UnsupportedEncodingException JavaDoc e) {
69       logger.error("exception caught", e);
70       fail(e.toString());
71       return null;
72     }
73   }
74
75   protected WebResponse submitForm(String JavaDoc buttonName) throws IOException JavaDoc, SAXException JavaDoc {
76     WebForm form = getForm();
77     SubmitButton sb = form.getSubmitButton(buttonName);
78     assertNotNull("submit button not found", sb);
79     form.submit(sb);
80     return wc.getCurrentPage();
81   }
82
83   protected WebForm getForm() throws SAXException JavaDoc {
84     return wc.getCurrentPage().getFormWithID(formID);
85   }
86
87   protected WebForm getForm(String JavaDoc formId) throws SAXException JavaDoc {
88     return wc.getCurrentPage().getFormWithID(formId);
89   }
90
91   protected void assertTableSize(String JavaDoc tableID, int rows, int cols) throws SAXException JavaDoc {
92     WebTable table = wc.getCurrentPage().getTableWithID(tableID);
93     assertEquals("Table RowCount", rows, table.getRowCount());
94     assertEquals("Table ColumnCount", cols, table.getColumnCount());
95   }
96
97   protected void assertCellValue(String JavaDoc tableID, int row, int col, String JavaDoc value)
98       throws SAXException JavaDoc {
99     WebTable table = wc.getCurrentPage().getTableWithID(tableID);
100     TableCell cell = table.getTableCell(row, col);
101     assertEquals("cellValue", value, cell.asText());
102   }
103
104   /**
105    * speichert die aktuelle Seite als HTML Datei.
106    * Auf der aktuellen seite muss eine Element mit ID = <code>id</code>
107    * vorhanden sein, dieses Element wird ueber das XSLT Stylesheet <code>xslName</code>
108    * konvertiert und ebenfalls (als XML Datei) gespeichert. Die XML Datei
109    * wird mit einer Soll-Version verglichen, bei Unterschieden
110    * wird der Test mit Fehler abgebrochen.
111    * @param fileName - Name der Datei (ohne Endung .xml bzw .html)
112    * @param xslName - Name des Stylesheets, z.B. filter.xsl. Das Stylesheet wird
113    * ueber Class.getResource geladen, dh. muss in diesem Package liegen oder
114    * voll qualifiziert sein.
115    * @param id - id parameter an das Stylesheet (waehlt z.B. das Element aus, das gespeichert
116    * und geprueft werden soll)
117    * @throws IOException
118    * @throws TransformerException
119    * @throws SAXException
120    */

121   protected void check(String JavaDoc fileName, String JavaDoc xslName, String JavaDoc id) throws IOException JavaDoc,
122       TransformerException JavaDoc, SAXException JavaDoc {
123     utils.saveHTML(fileName);
124     utils.saveXML(fileName, xslName, id, getCurrentDOM(fileName));
125     assertTrue("XML Files \"" + fileName + "\" differ", utils.equalsXML(fileName));
126   }
127
128   protected Document JavaDoc getCurrentDOM(String JavaDoc message) throws SAXException JavaDoc {
129     HtmlListener hl = HtmlListener.instance();
130     try {
131       hl.setCheckErrors(checkHtmlErrors);
132       Document JavaDoc dom = wc.getCurrentPage().getDOM();
133       hl.failOnError(message);
134       return dom;
135     } finally {
136       hl.reset();
137     }
138   }
139
140   protected void tearDown() throws Exception JavaDoc {
141     super.tearDown();
142   }
143
144   protected void setUp() throws Exception JavaDoc {
145     super.setUp();
146
147     HttpUnitOptions.setScriptingEnabled(false);
148     servletUrl = System.getProperty("httpunit.url");
149     if (servletUrl == null)
150       throw new RuntimeException JavaDoc(
151           "missing JVM Parameter httpunit.url, e.g. -Dhttpunit.url=http://localhost:8080/appname");
152     wc = new WebConversation();
153     wc.setHeaderField("accept-language", getLanguage());
154     setAuthorization(wc);
155
156     WebRequest wreq = getStartRequest();
157     if (wreq != null)
158       wc.sendRequest(wreq);
159
160     utils = new HttpUnitUtils(wc);
161   }
162
163   protected void setAuthorization(WebConversation wc) {
164     wc.setAuthorization("tdiuser", "tdiuser");
165   }
166
167   /**
168    * @return the initial request
169    */

170   protected abstract WebRequest getStartRequest();
171
172   /** liefert Sprache, eg. "en", "en-US", "de", "de-DE" usw */
173   protected String JavaDoc getLanguage() {
174     return "en-US";
175   }
176
177   /**
178    * @return String
179    */

180   public String JavaDoc getJspName() {
181     return jspName;
182   }
183
184   /**
185    * Sets the jspName.
186    * @param jspName The jspName to set
187    */

188   public void setJspName(String JavaDoc jspName) {
189     this.jspName = jspName;
190   }
191
192   /**
193    * @return
194    */

195   public String JavaDoc getFormID() {
196     return formID;
197   }
198
199   /**
200    * @param string
201    */

202   public void setFormID(String JavaDoc string) {
203     formID = string;
204   }
205
206   /**
207    * @return
208    */

209   public String JavaDoc getServletUrl() {
210     return servletUrl;
211   }
212
213   /**
214    * @return
215    */

216   public WebConversation getWc() {
217     return wc;
218   }
219
220   /**
221    * @param string
222    */

223   public void setServletUrl(String JavaDoc string) {
224     servletUrl = string;
225   }
226
227   /**
228    * @param conversation
229    */

230   public void setWc(WebConversation conversation) {
231     wc = conversation;
232   }
233
234   /**
235    * counts the number of nodes in the current page that match xpathExpr
236    *
237    * @param msg
238    * error message
239    * @param xpathExpr
240    * xpath expression
241    * @param nodeCount
242    * expected node count
243    */

244   public void xpath(String JavaDoc msg, String JavaDoc xpathExpr, int nodeCount) throws SAXException JavaDoc,
245       JaxenException {
246     Document JavaDoc dom = getCurrentDOM(msg);
247     XPath xpath = new DOMXPath(xpathExpr);
248     List JavaDoc list = xpath.selectNodes(dom);
249     if (list.size() != nodeCount) {
250       StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
251       sb.append("\n").append(msg).append("\n");
252       sb.append(" Node count for expression '").append(xpathExpr).append(" does not match");
253       if (list.size() > 0) {
254         sb.append("\nFound Nodes: ");
255         for (Iterator JavaDoc it = list.iterator(); it.hasNext();) {
256           Node JavaDoc node = (Node JavaDoc) it.next();
257           sb.append(node.getNodeName());
258           if (it.hasNext())
259             sb.append(", ");
260         }
261         sb.append("\n");
262       }
263       assertEquals(sb.toString(), nodeCount, list.size());
264     }
265   }
266
267   public int countNodes(String JavaDoc xpathExpr) throws JaxenException, SAXException JavaDoc {
268     DOMXPath dx = new DOMXPath(xpathExpr);
269     return dx.selectNodes(getCurrentDOM(xpathExpr)).size();
270   }
271
272   /**
273    * compares node content with a value. Example:
274    * <code>&lt;div id='test'&gt;OK&lt;/div&gt;</code> can be cecked via
275    * <code>xpath("text should be 'OK'", "//div[@id='test']/text()", "OK");
276    *
277    * @param msg Error Message
278    * @param xpathExpr XPath to Text Node or Attribute
279    * @param nodeValue Value of Text Node or Attribute
280    */

281   public void xpath(String JavaDoc msg, String JavaDoc xpathExpr, String JavaDoc nodeValue) throws SAXException JavaDoc,
282       JaxenException {
283     xpath(msg, xpathExpr, 1);
284     Document JavaDoc dom = getCurrentDOM(msg);
285     XPath xpath = new DOMXPath(xpathExpr);
286     Node JavaDoc n = (Node JavaDoc) xpath.selectSingleNode(dom);
287     assertEquals(msg, nodeValue, n.getNodeValue());
288   }
289
290   public void xpath(String JavaDoc msg, String JavaDoc xpathExpr) throws SAXException JavaDoc, JaxenException {
291     xpath(msg, xpathExpr, 1);
292   }
293
294   protected WebResponse showPage(String JavaDoc page) throws MalformedURLException JavaDoc, IOException JavaDoc, SAXException JavaDoc {
295     // doppelter slash in URL ist immer falsch
296
if (!page.startsWith("/"))
297       page = "/" + page;
298     WebRequest req = new GetMethodWebRequest(getServletUrl() + page);
299     return wc.sendRequest(req);
300   }
301
302   protected WebResponse followLink(String JavaDoc text, int nth) throws JaxenException, IOException JavaDoc, SAXException JavaDoc {
303     return utils.followXPath("//a[contains(., '" + text + "')]", nth);
304   }
305
306   protected WebResponse followLink(String JavaDoc text) throws JaxenException, IOException JavaDoc, SAXException JavaDoc {
307     return followLink(text, 0);
308   }
309
310   public boolean isCheckHtmlErrors() {
311     return checkHtmlErrors;
312   }
313
314   public void setCheckHtmlErrors(boolean checkErros) {
315     this.checkHtmlErrors = checkErros;
316   }
317
318 }
319
Popular Tags