KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > HtmlUnitTestCase


1 /*
2  * Copyright 1999-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.apache.cocoon;
17
18 import com.gargoylesoftware.htmlunit.Page;
19 import com.gargoylesoftware.htmlunit.SubmitMethod;
20 import com.gargoylesoftware.htmlunit.WebClient;
21 import com.gargoylesoftware.htmlunit.WebResponse;
22 import com.gargoylesoftware.htmlunit.html.DomNode;
23 import com.gargoylesoftware.htmlunit.html.HtmlPage;
24 import com.gargoylesoftware.htmlunit.html.xpath.HtmlUnitXPath;
25 import com.gargoylesoftware.htmlunit.xml.XmlPage;
26
27 import junit.framework.TestCase;
28
29 import org.apache.avalon.framework.logger.ConsoleLogger;
30 import org.apache.avalon.framework.logger.Logger;
31
32 import org.apache.commons.httpclient.methods.DeleteMethod;
33 import org.apache.commons.httpclient.methods.PutMethod;
34 import org.apache.commons.httpclient.methods.StringRequestEntity;
35
36 import org.apache.commons.io.FileUtils;
37
38 import org.jaxen.SimpleNamespaceContext;
39 import org.jaxen.XPath;
40 import org.jaxen.dom.DOMXPath;
41
42 import org.w3c.dom.Document JavaDoc;
43 import org.w3c.dom.Node JavaDoc;
44
45 import java.io.File JavaDoc;
46 import java.net.URL JavaDoc;
47 import java.util.ArrayList JavaDoc;
48 import java.util.HashMap JavaDoc;
49 import java.util.Map JavaDoc;
50
51 /**
52  * Base class to run test cases on Cocoon samples.
53  * <p>
54  * This class extends the JUnit TestCase class to setup an environment which
55  * makes it possible to easily test Cocoon pages.
56  * First call one of the load methods and then assert on the response object,
57  * XML document (@see loadXmlPage), or HTML document (@see loadHtmlPage).
58  * </p>
59  * <p>
60  * Examples:
61  * </p>
62  * <pre>
63  * public void testStatus() {
64  * loadResponse("/samples/test/status");
65  * assertEquals("Status code", 200, response.getStatusCode());
66  * }
67  *
68  * public void testTitle() {
69  * loadHtmlPage("/samples/test/title");
70  * assertXPath("html/head/title"", "The Title");
71  * }
72  * </pre>
73  *
74  * <p>
75  * For loading XML and HTML documents currently on GET requests with
76  * optional querystring are supported. Please add POST requests and
77  * request parameters when you need them.
78  * </p>
79  * @version $Id: $
80  */

81 public abstract class HtmlUnitTestCase
82     extends TestCase
83 {
84     /**
85      * Logger for informative output by test cases.
86      * The default log level is WARN but may be changed by setting the
87      * property junit.test.loglevel to a different numeric value.
88      */

89     protected Logger logger;
90
91     /**
92      * Base URL of the running Cocoon server which is to be tested.
93      * Set by property htmlunit.test.baseurl usually as http://localhost:8888/.
94      */

95     protected URL JavaDoc baseURL;
96
97     /**
98      * Low-level access to WebClient object.
99      */

100     protected WebClient webClient;
101
102     /**
103      * Low-level access to WebResponse object.
104      */

105     protected WebResponse response;
106
107     /**
108      * Low-level access to XML document (org.w3c.dom.Document) or HTML document
109      * (com.gargoylesoftware.htmlunit.html.HtmlPage).
110      */

111     protected Object JavaDoc document;
112
113     /**
114      * Low-level access to namespace mappings for XPath expressions.
115      */

116     protected Map JavaDoc namespaces = new HashMap JavaDoc();
117
118     /* (non-Javadoc)
119      * @see junit.framework.TestCase#setUp()
120      */

121     protected void setUp()
122         throws Exception JavaDoc
123     {
124         super.setUp();
125
126         String JavaDoc level = System.getProperty("junit.test.loglevel", "" + ConsoleLogger.LEVEL_WARN);
127         this.logger = new ConsoleLogger(Integer.parseInt(level));
128
129         String JavaDoc baseurl = System.getProperty("htmlunit.test.baseurl");
130         this.baseURL = new URL JavaDoc(baseurl);
131         this.webClient = new WebClient();
132         this.webClient.setRedirectEnabled(false);
133         this.namespaces.clear();
134     }
135
136     /* (non-Javadoc)
137      * @see junit.framework.TestCase#tearDown()
138      */

139     protected void tearDown()
140         throws Exception JavaDoc
141     {
142         this.response = null;
143         this.document = null;
144
145         super.tearDown();
146     }
147
148     /**
149      * Sends HTTP GET request and loads response object.
150      */

151     protected void loadResponse(String JavaDoc pageURL)
152         throws Exception JavaDoc
153     {
154         URL JavaDoc url = new URL JavaDoc(baseURL, pageURL);
155         this.response = webClient.loadWebResponse(url, SubmitMethod.GET, new ArrayList JavaDoc(0));
156     }
157
158     /**
159      * Sends HTTP DELETE request and loads response object.
160      */

161     protected void loadDeleteResponse(String JavaDoc pageURL)
162         throws Exception JavaDoc
163     {
164         URL JavaDoc url = new URL JavaDoc(baseURL, pageURL);
165         DeleteMethod method = new DeleteMethod(url.toExternalForm());
166         this.response = new HttpClientResponse(url, method);
167     }
168
169     /**
170      * Sends HTTP PUT request and loads response object.
171      */

172     protected void loadPutResponse(String JavaDoc pageURL, String JavaDoc content)
173         throws Exception JavaDoc
174     {
175         URL JavaDoc url = new URL JavaDoc(baseURL, pageURL);
176         PutMethod method = new PutMethod(url.toExternalForm());
177         method.setRequestEntity(new StringRequestEntity(content));
178         this.response = new HttpClientResponse(url, method);
179     }
180
181     /**
182      * Sends HTTP request and parses response as HTML document.
183      */

184     protected void loadHtmlPage(String JavaDoc pageURL)
185         throws Exception JavaDoc
186     {
187         URL JavaDoc url = new URL JavaDoc(baseURL, pageURL);
188         Page page = webClient.getPage(url);
189         this.response = page.getWebResponse();
190         assertTrue("Response should be an HTML page", page instanceof HtmlPage);
191         this.document = page;
192         assertNotNull("Response contains invalid HTML", this.document);
193     }
194
195     /**
196      * Sends HTTP request and parses response as XML document.
197      */

198     protected void loadXmlPage(String JavaDoc pageURL)
199         throws Exception JavaDoc
200     {
201         URL JavaDoc url = new URL JavaDoc(baseURL, pageURL);
202         Page page = webClient.getPage(url);
203         this.response = page.getWebResponse();
204         assertTrue("Response should be an XML page", page instanceof XmlPage);
205         XmlPage xmlPage = (XmlPage)page;
206         this.document = xmlPage.getXmlDocument();
207         assertNotNull("Response contains invalid XML", this.document);
208     }
209
210     /**
211      * Returns XPath expression as string.
212      *
213      * @param xpathExpr XPath expression
214      *
215      * @return Value of XPath expression in current document.
216      * Empty string if XPath not matched.
217      */

218     protected String JavaDoc evalXPath(String JavaDoc xpathExpr)
219         throws Exception JavaDoc
220     {
221         XPath xpath = null;
222         if( document == null )
223             return null;
224         else if( document instanceof HtmlPage )
225             xpath = new HtmlUnitXPath(xpathExpr);
226         else if( document instanceof Document JavaDoc )
227             xpath = new DOMXPath(xpathExpr);
228         else
229             fail("Document type "+document.getClass().getName());
230
231         xpath.setNamespaceContext(new SimpleNamespaceContext(namespaces));
232
233         return xpath.stringValueOf(document);
234     }
235
236     /**
237      * Add a namespace mapping for XPath expressions.
238      */

239     protected void addNamespace(String JavaDoc prefix, String JavaDoc uri)
240         throws Exception JavaDoc
241     {
242         namespaces.put(prefix, uri);
243     }
244
245     /**
246      * Assert that XPath expression result matches exactly expected value.
247      */

248     protected void assertXPath(String JavaDoc xpathExpr, String JavaDoc expected)
249         throws Exception JavaDoc
250     {
251         assertEquals(xpathExpr, expected, evalXPath(xpathExpr));
252     }
253
254     /**
255      * Copy file from webapp source to deployment area filtering content
256      * to replace parameter by value.
257      * The source and deployment directories are defined by the properties
258      * htmlunit.test.source-dir and htmlunit.test.deploy-dir.
259      *
260      * This method is most useful for testing the automatic reloading of
261      * changed files.
262      */

263     protected void copyWebappFile(String JavaDoc filename, String JavaDoc param, String JavaDoc value)
264         throws Exception JavaDoc
265     {
266         String JavaDoc srcdir = System.getProperty("htmlunit.test.source-dir");
267         String JavaDoc dstdir = System.getProperty("htmlunit.test.deploy-dir");
268         File JavaDoc srcfile = new File JavaDoc(srcdir+"/"+filename);
269         File JavaDoc dstfile = new File JavaDoc(dstdir+"/"+filename);
270
271         final String JavaDoc encoding = "ISO-8859-1";
272         StringBuffer JavaDoc content = new StringBuffer JavaDoc(FileUtils.readFileToString(srcfile, encoding));
273
274         int index = content.indexOf(param);
275         while( index != -1 ) {
276             content.replace(index, index+param.length(), value);
277             index = content.indexOf(param, index+1);
278         }
279
280         FileUtils.writeStringToFile(dstfile, content.toString(), encoding);
281
282         // Leave server some time to realize that file has changed.
283

284         Thread.sleep(1000);
285     }
286 }
287
Popular Tags