KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > gargoylesoftware > htmlunit > HttpWebConnectionTest


1 /*
2  * Copyright (c) 2002, 2005 Gargoyle Software Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are met:
6  *
7  * 1. Redistributions of source code must retain the above copyright notice,
8  * this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright notice,
10  * this list of conditions and the following disclaimer in the documentation
11  * and/or other materials provided with the distribution.
12  * 3. The end-user documentation included with the redistribution, if any, must
13  * include the following acknowledgment:
14  *
15  * "This product includes software developed by Gargoyle Software Inc.
16  * (http://www.GargoyleSoftware.com/)."
17  *
18  * Alternately, this acknowledgment may appear in the software itself, if
19  * and wherever such third-party acknowledgments normally appear.
20  * 4. The name "Gargoyle Software" must not be used to endorse or promote
21  * products derived from this software without prior written permission.
22  * For written permission, please contact info@GargoyleSoftware.com.
23  * 5. Products derived from this software may not be called "HtmlUnit", nor may
24  * "HtmlUnit" appear in their name, without prior written permission of
25  * Gargoyle Software Inc.
26  *
27  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
28  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
29  * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARGOYLE
30  * SOFTWARE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
31  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
32  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
33  * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
34  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
35  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
36  * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37  */

38 package com.gargoylesoftware.htmlunit;
39
40 import java.io.BufferedInputStream;
41 import java.io.ByteArrayInputStream;
42 import java.io.IOException;
43 import java.io.InputStream;
44 import java.lang.reflect.Field;
45 import java.lang.reflect.Method;
46 import java.net.MalformedURLException;
47 import java.net.URL;
48 import java.util.Map;
49
50 import org.apache.commons.httpclient.HttpClient;
51 import org.apache.commons.httpclient.HttpMethod;
52 import org.apache.commons.httpclient.HttpMethodBase;
53 import org.apache.commons.httpclient.HttpState;
54 import org.apache.commons.httpclient.methods.GetMethod;
55
56 import com.gargoylesoftware.base.testing.BaseTestCase;
57
58
59
60 /**
61  * Tests methods in {@link HttpWebConnection} class.
62  *
63  * @author David D. Kilzer
64  * @version $Revision: 1.7 $
65  */

66 public class HttpWebConnectionTest extends BaseTestCase {
67
68     /**
69      * Assert that the two byte arrays are equal
70      * @param expected The expected value
71      * @param actual The actual value
72      */

73     public static void assertEquals(final byte[] expected, final byte[] actual) {
74         assertEquals(null, expected, actual);
75     }
76
77
78     /**
79      * Assert that the two byte arrays are equal
80      * @param message The message to display on failure
81      * @param expected The expected value
82      * @param actual The actual value
83      */

84     public static void assertEquals(
85             final String message, final byte[] expected, final byte[] actual) {
86         assertEquals(message, expected, actual, expected.length);
87     }
88
89
90     /**
91      * Assert that the two byte arrays are equal
92      * @param message The message to display on failure
93      * @param expected The expected value
94      * @param actual The actual value
95      * @param length How many characters at the beginning of each byte array will be compared.
96      */

97     public static void assertEquals(
98             final String message, final byte[] expected, final byte[] actual,
99             final int length) {
100         if (expected == null && actual == null) {
101             return;
102         }
103         if (expected == null || actual == null) {
104             fail(message);
105         }
106         if (expected.length < length || actual.length < length) {
107             fail(message);
108         }
109         for (int i = 0; i < length; i++) {
110             assertEquals(message, expected[i], actual[i]);
111         }
112     }
113
114     /**
115      * Assert that the two input streams are the same.
116      * @param expected The expected value
117      * @param actual The actual value
118      * @throws IOException If an IO problem occurs during comparison
119      */

120     public static void assertEquals(final InputStream expected, final InputStream actual) throws IOException {
121         assertEquals(null, expected, actual);
122     }
123
124     /**
125      * Assert that the two input streams are the same.
126      * @param message The message to display on failure
127      * @param expected The expected value
128      * @param actual The actual value
129      * @throws IOException If an IO problem occurs during comparison
130      */

131     public static void assertEquals(
132             final String message, final InputStream expected,
133             final InputStream actual)
134         throws IOException {
135
136         if (expected == null && actual == null) {
137             return;
138         }
139
140         if (expected == null || actual == null) {
141             try {
142                 fail(message);
143             }
144             finally {
145                 try {
146                     if (expected != null) {
147                         expected.close();
148                     }
149                 }
150                 finally {
151                     if (actual != null) {
152                         actual.close();
153                     }
154                 }
155             }
156         }
157
158         InputStream expectedBuf = null;
159         InputStream actualBuf = null;
160         try {
161             expectedBuf = new BufferedInputStream(expected);
162             actualBuf = new BufferedInputStream(actual);
163
164             final byte[] expectedArray = new byte[2048];
165             final byte[] actualArray = new byte[2048];
166
167             int expectedLength = expectedBuf.read(expectedArray);
168             while(true) {
169
170                 final int actualLength = actualBuf.read(actualArray);
171                 assertEquals(message, expectedLength, actualLength);
172
173                 if (expectedLength == -1) {
174                     break;
175                 }
176
177                 assertEquals(message, expectedArray, actualArray, expectedLength);
178                 expectedLength = expectedBuf.read(expectedArray);
179             }
180         }
181         finally {
182             try {
183                 if (expectedBuf != null) {
184                     expectedBuf.close();
185                 }
186             }
187             finally {
188                 if (actualBuf != null) {
189                     actualBuf.close();
190                 }
191             }
192         }
193     }
194
195
196     /**
197      * Create an instance.
198      *
199      * @param name The name of the test.
200      */

201     public HttpWebConnectionTest(final String name) {
202         super(name);
203     }
204
205
206     /**
207      * Tests {@link HttpWebConnection#getStateForUrl(java.net.URL)} using a url with hostname
208      * <code>gargoylesoftware.com</code>.
209      */

210     public void testGetStateForUrl_gargoylesoftware_com() {
211         assertGetStateForUrl("gargoylesoftware.com");
212     }
213
214
215     /**
216      * Tests {@link HttpWebConnection#getStateForUrl(java.net.URL)} using a url with hostname
217      * <code>www.gargoylesoftware.com</code>.
218      */

219     public void testGetStateForUrl_www_gargoylesoftware_com() {
220         assertGetStateForUrl("www.gargoylesoftware.com");
221     }
222
223
224     /**
225      * Tests {@link HttpWebConnection#getStateForUrl(java.net.URL)} using a url with hostname
226      * <code>www.sub.gargoylesoftware.com</code>.
227      */

228     public void testGetStateForUrl_www_sub_gargoylesoftware_com() {
229         assertGetStateForUrl("www.sub.gargoylesoftware.com");
230     }
231
232
233     /**
234      * Tests {@link HttpWebConnection#getStateForUrl(java.net.URL)} using a url with hostname
235      * <code>localhost</code>.
236      */

237     public void testGetStateForUrl_localhost() {
238         assertGetStateForUrl("localhost");
239     }
240
241
242     /**
243      * Tests {@link HttpWebConnection#getStateForUrl(java.net.URL)} using a url with hostname
244      * <code>GARGOYLESOFTWARE.COM</code>.
245      */

246     public void testGetStateForUrl_GARGOYLESOFTWARE_COM() {
247         assertGetStateForUrl("GARGOYLESOFTWARE.COM");
248     }
249
250
251     /**
252      * Tests {@link HttpWebConnection#getStateForUrl(java.net.URL)} using a url with hostname
253      * <code>WWW.GARGOYLESOFTWARE.COM</code>.
254      */

255     public void testGetStateForUrl_WWW_GARGOYLESOFTWARE_COM() {
256         assertGetStateForUrl("WWW.GARGOYLESOFTWARE.COM");
257     }
258
259
260     /**
261      * Tests {@link HttpWebConnection#getStateForUrl(java.net.URL)} using a url with hostname
262      * <code>WWW.SUB.GARGOYLESOFTWARE.COM</code>.
263      */

264     public void testGetStateForUrl_WWW_SUB_GARGOYLESOFTWARE_COM() {
265         assertGetStateForUrl("WWW.SUB.GARGOYLESOFTWARE.COM");
266     }
267
268
269     /**
270      * Tests {@link HttpWebConnection#getStateForUrl(java.net.URL)} using a url with hostname
271      * <code>LOCALHOST</code>.
272      */

273     public void testGetStateForUrl_LOCALHOST() {
274         assertGetStateForUrl("LOCALHOST");
275     }
276
277     /**
278      * Test creation of a web response
279      * @throws Exception If the test fails
280      */

281     public void testMakeWebResponse() throws Exception {
282
283         final URL url = new URL("http://htmlunit.sourceforge.net/");
284         final String content = "<html><head></head><body></body></html>";
285         final int httpStatus = 200;
286         final long loadTime = 500L;
287
288         final HttpMethod httpMethod = new GetMethod(url.toString());
289         final Field field = HttpMethodBase.class.getDeclaredField("responseBody");
290         field.setAccessible(true);
291         field.set(httpMethod, content.getBytes());
292
293         final HttpWebConnection connection = new HttpWebConnection(new WebClient());
294         final Method method =
295                 connection.getClass().getDeclaredMethod("makeWebResponse", new Class[]{
296                     int.class, HttpMethod.class, URL.class, long.class});
297         method.setAccessible(true);
298
299         final WebResponse response =
300                 (WebResponse) method.invoke(connection, new Object[]{
301                     new Integer(httpStatus), httpMethod, url, new Long(loadTime)});
302
303         assertEquals(httpStatus, response.getStatusCode());
304         assertEquals(url, response.getUrl());
305         assertEquals(loadTime, response.getLoadTimeInMilliSeconds());
306         assertEquals(content, response.getContentAsString());
307         assertEquals(content.getBytes(), response.getResponseBody());
308         assertEquals(new ByteArrayInputStream(content.getBytes()), response.getContentAsStream());
309     }
310
311
312     /**
313      * Tests the {@link HttpWebConnection#getStateForUrl(java.net.URL)} using reflection.
314      *
315      * @param hostname The hostname of the url to test
316      */

317     private void assertGetStateForUrl(final String hostname) {
318
319         final HttpWebConnection connection = new HttpWebConnection(new WebClient());
320         try {
321
322             final Field httpClients = connection.getClass().getDeclaredField("httpClients_");
323             httpClients.setAccessible(true);
324             final Map map = (Map) httpClients.get(connection);
325
326             final HttpState expectedHttpState = new HttpState();
327
328             final HttpClient httpClient = new HttpClient();
329             final Field httpState = httpClient.getClass().getDeclaredField("state");
330             httpState.setAccessible(true);
331             httpState.set(httpClient, expectedHttpState);
332
333             map.put("http://" + hostname.toLowerCase(), httpClient);
334
335             final URL url = new URL("http://" + hostname + "/context");
336             final HttpState actualHttpState = connection.getStateForUrl(url);
337             assertSame(expectedHttpState, actualHttpState);
338         }
339         catch (final NoSuchFieldException e) {
340             throw new RuntimeException(e);
341         }
342         catch (final IllegalAccessException e) {
343             throw new RuntimeException(e);
344         }
345         catch (final MalformedURLException e) {
346             throw new RuntimeException(e);
347         }
348     }
349 }
350
Popular Tags