KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > gargoylesoftware > htmlunit > html > AttributesTest


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.html;
39
40 import java.lang.reflect.Constructor;
41 import java.lang.reflect.InvocationTargetException;
42 import java.lang.reflect.Method;
43 import java.util.ArrayList;
44 import java.util.List;
45 import java.util.Map;
46
47 import junit.framework.Test;
48 import junit.framework.TestSuite;
49
50 import com.gargoylesoftware.htmlunit.WebTestCase;
51
52 /**
53  * <p>Tests for all the generated attribute accessors. This test case will
54  * dynamically generate tests for all the various attributes. The code
55  * is fairly complicated but doing it this way is much easier than writing
56  * individual tests for all the attributes.
57  * </p>
58  * With the new custom DOM, this test has somewhat lost its significance.
59  * We simply set and get the attributes and compare the results.
60  *
61  * @version $Revision: 1.13 $
62  * @author <a HREF="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
63  * @author Christian Sell
64  * @author Marc Guillemot
65  */

66 public class AttributesTest extends WebTestCase {
67
68     private final Class classUnderTest_;
69     private final Method method_;
70     private final HtmlPage page_;
71     private final String attributeName_;
72
73     private static final List EXCLUDED_METHODS = new ArrayList();
74     static {
75         EXCLUDED_METHODS.add("getHtmlElementsByAttribute");
76         EXCLUDED_METHODS.add("getOneHtmlElementByAttribute");
77     }
78
79     /**
80      * Return a test suite containing a seperate test for each attribute
81      * on each element.
82      *
83      * @return The test suite
84      * @throws Exception If the tests cannot be created.
85      */

86     public static Test suite() throws Exception {
87         final HtmlPage page = loadPage("<html><head><title>foo</title></head><body></body></html>");
88
89         final TestSuite suite = new TestSuite();
90         final String[] classesToTest = new String[] {
91             "HtmlAddress", "HtmlAnchor", "HtmlApplet", "HtmlArea",
92             "HtmlBase", "HtmlBaseFont", "HtmlBidirectionalOverride",
93             "HtmlBlockQuote", "HtmlBody", "HtmlBreak", "HtmlButton",
94             "HtmlButtonInput", "HtmlCaption", "HtmlCenter",
95             "HtmlCheckBoxInput", "HtmlDefinitionDescription",
96             "HtmlDefinitionList", "HtmlDefinitionTerm",
97             "HtmlDeletedText", "HtmlDivision", "HtmlElement",
98             "HtmlFieldSet", "HtmlFileInput", "HtmlFont", "HtmlForm",
99             "HtmlFrame", "HtmlFrameSet", "HtmlHead", "HtmlHeader1",
100             "HtmlHeader2", "HtmlHeader3", "HtmlHeader4", "HtmlHeader5",
101             "HtmlHeader6", "HtmlHiddenInput", "HtmlHorizontalRule",
102             "HtmlImage", "HtmlImageInput", "HtmlInlineFrame",
103             "HtmlInlineQuotation",
104             "HtmlInsertedText", "HtmlIsIndex", "HtmlLabel",
105             "HtmlLegend", "HtmlLink", "HtmlListItem", "HtmlMap",
106             "HtmlMenu", "HtmlMeta", "HtmlNoFrames", "HtmlNoScript",
107             "HtmlObject", "HtmlOption", "HtmlOptionGroup", "HtmlOrderedList",
108             /*"HtmlPage",*/ "HtmlParagraph", "HtmlParameter", "HtmlPasswordInput",
109             "HtmlPreformattedText", "HtmlRadioButtonInput", "HtmlResetInput",
110             "HtmlScript", "HtmlSelect", "HtmlSpan", "HtmlStyle", "HtmlSubmitInput",
111             "HtmlTable", "HtmlTableBody", /*"HtmlTableCell",*/ "HtmlTableColumn",
112             "HtmlTableColumnGroup", "HtmlTableDataCell",
113             "HtmlTableFooter", "HtmlTableHeader", "HtmlTableHeaderCell",
114             "HtmlTableRow", "HtmlTextArea", "HtmlTextDirection", "HtmlTextInput",
115             "HtmlTitle", "HtmlUnorderedList"
116         };
117         for( int i=0; i<classesToTest.length; i++ ) {
118             final Class clazz = Class.forName(
119                 "com.gargoylesoftware.htmlunit.html."+classesToTest[i]);
120             addTestsForClass( clazz, page, suite );
121         }
122         return suite;
123     }
124
125     /**
126      * Add all the tests for a given class.
127      *
128      * @param clazz The class to create tests for.
129      * @param page The HtmlPage that will be passed into the constructor of the
130      * objects to be tested.
131      * @param suite The suite that all the tests will be placed inside.
132      * @throws Exception If the tests cannot be created.
133      */

134     private static void addTestsForClass(
135             final Class clazz,
136             final HtmlPage page,
137             final TestSuite suite )
138         throws
139             Exception {
140
141         final Method[] methods = clazz.getMethods();
142         for( int i=0; i<methods.length; i++ ) {
143             final String methodName = methods[i].getName();
144             if( methodName.startsWith("get")
145                 && methodName.endsWith("Attribute")
146                 && !EXCLUDED_METHODS.contains(methodName)) {
147
148                 String attributeName = methodName.substring(3, methodName.length()-9).toLowerCase();
149                 if( attributeName.equals("xmllang") ) {
150                     attributeName = "xml:lang";
151                 }
152                 else if( attributeName.equals("columns") ) {
153                     attributeName = "cols";
154                 }
155                 else if( attributeName.equals("columnspan") ) {
156                     attributeName = "colspan";
157                 }
158                 else if( attributeName.equals("textdirection") ) {
159                     attributeName = "dir";
160                 }
161                 else if( attributeName.equals("httpequiv") ) {
162                     attributeName = "http-equiv";
163                 }
164                 else if( attributeName.equals("acceptcharset") ) {
165                     attributeName = "accept-charset";
166                 }
167                 else if( attributeName.equals("htmlfor") ) {
168                     attributeName = "for";
169                 }
170                 suite.addTest( new AttributesTest(attributeName, clazz, methods[i], page) );
171             }
172         }
173     }
174
175     /**
176      * Create an instance of the test. This will test one specific attribute
177      * on one specific class.
178      * @param attributeName The name of the attribute to test.
179      * @param classUnderTest The class containing the attribute.
180      * @param method The "getter" method for the specified attribute.
181      * @param page The page that will be passed into the constructor of the object
182      * to be tested.
183      */

184     public AttributesTest (
185             final String attributeName,
186             final Class classUnderTest,
187             final Method method,
188             final HtmlPage page ) {
189
190         super( createTestName(classUnderTest, method) );
191         classUnderTest_ = classUnderTest;
192         method_ = method;
193         page_ = page;
194         attributeName_ = attributeName;
195     }
196
197     /**
198      * Create a name for this particular test that reflect the attribute being tested.
199      * @param clazz The class containing the attribute.
200      * @param method The getter method for the attribute.
201      * @return The new name.
202      */

203     private static String createTestName( final Class clazz, final Method method ) {
204         String className = clazz.getName();
205         final int index = className.lastIndexOf('.');
206         className = className.substring(index+1);
207
208         return "testAttributes_"+className+"_"+method.getName();
209     }
210
211     /**
212      * Run the actual test.
213      * @throws Exception If the test fails.
214      */

215     protected void runTest() throws Exception {
216         final String value = new String("value");
217
218         final HtmlElement objectToTest = (HtmlElement)getNewInstanceForClassUnderTest();
219         objectToTest.setAttributeValue(attributeName_, value);
220
221         final Object noObjects[] = new Object[0];
222         final Object result = method_.invoke( objectToTest, noObjects );
223         assertSame( value, result );
224     }
225
226     /**
227      * Create a new instance of the class being tested.
228      * @return The new instance.
229      * @throws Exception If the new object cannot be created.
230      */

231     private Object getNewInstanceForClassUnderTest() throws Exception {
232         final Object newInstance;
233         if( classUnderTest_ == HtmlTableRow.class ) {
234             newInstance = new HtmlTableRow( page_, null);
235         }
236         else if( classUnderTest_ == HtmlTableHeaderCell.class ) {
237             newInstance = new HtmlTableHeaderCell(page_, null );
238         }
239         else if( classUnderTest_ == HtmlTableDataCell.class ) {
240             newInstance = new HtmlTableDataCell(page_, null );
241         }
242         else {
243             final Constructor constructor = classUnderTest_.getDeclaredConstructor(
244                 new Class[]{ HtmlPage.class, Map.class } );
245             try {
246                 newInstance = constructor.newInstance(
247                     new Object[]{page_, null});
248             }
249             catch( final InvocationTargetException e ) {
250                 final Throwable targetException = e.getTargetException();
251                 if( targetException instanceof Exception ) {
252                     throw (Exception)targetException;
253                 }
254                 else if( targetException instanceof Error ) {
255                     throw (Error)targetException;
256                 }
257                 else {
258                     throw e;
259                 }
260             }
261         }
262
263         return newInstance;
264     }
265 }
266
Popular Tags