KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > commons > digester > DigesterTestCase


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

17
18
19 package org.apache.commons.digester;
20
21 import java.math.BigDecimal JavaDoc;
22 import java.net.URL JavaDoc;
23 import java.io.StringReader JavaDoc;
24 import java.util.Iterator JavaDoc;
25 import java.util.List JavaDoc;
26 import java.util.Map JavaDoc;
27 import java.util.EmptyStackException JavaDoc;
28
29 import junit.framework.Test;
30 import junit.framework.TestCase;
31 import junit.framework.TestSuite;
32
33 import org.xml.sax.ErrorHandler JavaDoc;
34 import org.xml.sax.Attributes JavaDoc;
35 import org.xml.sax.helpers.AttributesImpl JavaDoc;
36 import org.xml.sax.InputSource JavaDoc;
37
38
39 /**
40  * <p>Test Case for the Digester class. These tests exercise the individual
41  * methods of a Digester, but do not attempt to process complete documents.
42  * </p>
43  *
44  * @author Craig R. McClanahan
45  * @version $Revision$ $Date: 2005-03-07 02:12:40 -0800 (Mon, 07 Mar 2005) $
46  */

47
48 public class DigesterTestCase extends TestCase {
49
50
51     // ----------------------------------------------------- Instance Variables
52

53
54     /**
55      * The digester instance we will be processing.
56      */

57     protected Digester digester = null;
58
59
60     /**
61      * The set of public identifiers, and corresponding resource names,
62      * for the versions of the DTDs that we know about. There
63      * <strong>MUST</strong> be an even number of Strings in this array.
64      */

65     protected static final String JavaDoc registrations[] = {
66         "-//Netscape Communications//DTD RSS 0.9//EN",
67         "/org/apache/commons/digester/rss/rss-0.9.dtd",
68         "-//Netscape Communications//DTD RSS 0.91//EN",
69         "/org/apache/commons/digester/rss/rss-0.91.dtd",
70     };
71
72
73     // ----------------------------------------------------------- Constructors
74

75
76     /**
77      * Construct a new instance of this test case.
78      *
79      * @param name Name of the test case
80      */

81     public DigesterTestCase(String JavaDoc name) {
82
83         super(name);
84
85     }
86
87
88     // -------------------------------------------------- Overall Test Methods
89

90
91     /**
92      * Set up instance variables required by this test case.
93      */

94     public void setUp() {
95
96         digester = new Digester();
97         digester.setRules(new RulesBase());
98
99     }
100
101
102     /**
103      * Return the tests included in this test suite.
104      */

105     public static Test suite() {
106
107         return (new TestSuite(DigesterTestCase.class));
108
109     }
110
111
112     /**
113      * Tear down instance variables required by this test case.
114      */

115     public void tearDown() {
116
117         digester = null;
118
119     }
120
121
122
123     // ------------------------------------------------ Individual Test Methods
124

125
126     /**
127      * Test the basic property getters and setters.
128      */

129     public void testProperties() {
130
131         assertNull("Initial error handler is null",
132                 digester.getErrorHandler());
133         digester.setErrorHandler((ErrorHandler JavaDoc) digester);
134         assertTrue("Set error handler is digester",
135                 digester.getErrorHandler() == digester);
136         digester.setErrorHandler(null);
137         assertNull("Reset error handler is null",
138                 digester.getErrorHandler());
139
140         assertTrue("Initial namespace aware is false",
141                 !digester.getNamespaceAware());
142         digester.setNamespaceAware(true);
143         assertTrue("Set namespace aware is true",
144                 digester.getNamespaceAware());
145         digester.setNamespaceAware(false);
146         assertTrue("Reset namespace aware is false",
147                 !digester.getNamespaceAware());
148
149         assertTrue("Initial validating is false",
150                 !digester.getValidating());
151         digester.setValidating(true);
152         assertTrue("Set validating is true",
153                 digester.getValidating());
154         digester.setValidating(false);
155         assertTrue("Reset validating is false",
156                 !digester.getValidating());
157
158     }
159
160
161     /**
162      * Test registration of URLs for specified public identifiers.
163      */

164     public void testRegistrations() {
165
166         Map JavaDoc map = digester.getRegistrations();
167         assertEquals("Initially zero registrations", 0, map.size());
168         int n = 0;
169         for (int i = 0; i < registrations.length; i += 2) {
170             URL JavaDoc url = this.getClass().getResource(registrations[i + 1]);
171             if (url != null) {
172                 digester.register(registrations[i], url.toString());
173                 n++;
174             }
175         }
176         map = digester.getRegistrations();
177         assertEquals("Registered two URLs", n, map.size());
178
179         int count[] = new int[n];
180         for (int i = 0; i < n; i++)
181             count[i] = 0;
182         Iterator JavaDoc keys = map.keySet().iterator();
183         while (keys.hasNext()) {
184             String JavaDoc key = (String JavaDoc) keys.next();
185             for (int i = 0; i < n; i++) {
186                 if (key.equals(registrations[i * 2])) {
187                     count[i]++;
188                     break;
189                 }
190             }
191         }
192         for (int i = 0; i < n; i++)
193             assertEquals("Count for key " + registrations[i * 2],
194                     1, count[i]);
195
196     }
197
198
199     /**
200      * Basic test for rule creation and matching.
201      */

202     public void testRules() {
203
204         List JavaDoc list = null;
205
206         assertEquals("Initial rules list is empty",
207                 0, digester.getRules().match(null, "a").size());
208         digester.addSetProperties("a");
209         assertEquals("Add a matching rule",
210                 1, digester.getRules().match(null, "a").size());
211         digester.addSetProperties("b");
212         assertEquals("Add a non-matching rule",
213                 1, digester.getRules().match(null, "a").size());
214         digester.addSetProperties("a/b");
215         assertEquals("Add a non-matching nested rule",
216                 1, digester.getRules().match(null, "a").size());
217         digester.addSetProperties("a/b");
218         assertEquals("Add a second matching rule",
219                 2, digester.getRules().match(null, "a/b").size());
220
221     }
222
223
224     /**
225      * <p>Test matching rules in {@link RulesBase}.</p>
226      *
227      * <p>Tests:</p>
228      * <ul>
229      * <li>exact match</li>
230      * <li>tail match</li>
231      * <li>longest pattern rule</li>
232      * </ul>
233      */

234     public void testRulesBase() {
235
236         assertEquals("Initial rules list is empty",
237                 0, digester.getRules().rules().size());
238
239         // We're going to set up
240
digester.addRule("a/b/c/d", new TestRule("a/b/c/d"));
241         digester.addRule("*/d", new TestRule("*/d"));
242         digester.addRule("*/c/d", new TestRule("*/c/d"));
243
244         // Test exact match
245
assertEquals("Exact match takes precedence 1",
246                 1, digester.getRules().match(null, "a/b/c/d").size());
247         assertEquals("Exact match takes precedence 2",
248                 "a/b/c/d",
249                 ((TestRule) digester.getRules().match(null, "a/b/c/d").iterator().next()).getIdentifier());
250
251         // Test wildcard tail matching
252
assertEquals("Wildcard tail matching rule 1",
253                 1, digester.getRules().match(null, "a/b/d").size());
254         assertEquals("Wildcard tail matching rule 2",
255                 "*/d",
256                 ((TestRule) digester.getRules().match(null, "a/b/d").iterator().next()).getIdentifier());
257
258         // Test the longest matching pattern rule
259
assertEquals("Longest tail rule 1",
260                 1, digester.getRules().match(null, "x/c/d").size());
261         assertEquals("Longest tail rule 2",
262                 "*/c/d",
263                 ((TestRule) digester.getRules().match(null, "x/c/d").iterator().next()).getIdentifier());
264
265     }
266
267
268     /**
269      * Test the basic stack mechanisms.
270      */

271     public void testStackMethods() {
272
273         Object JavaDoc value = null;
274
275         // New stack must be empty
276
assertEquals("New stack is empty", 0, digester.getCount());
277         value = digester.peek();
278         assertNull("New stack peek() returns null", value);
279         value = digester.pop();
280         assertNull("New stack pop() returns null", value);
281
282         // Test pushing and popping activities
283
digester.push("First Item");
284         assertEquals("Pushed one item size", 1, digester.getCount());
285         value = digester.peek();
286         assertNotNull("Peeked first item is not null", value);
287         assertEquals("Peeked first item value", "First Item", (String JavaDoc) value);
288
289         digester.push("Second Item");
290         assertEquals("Pushed two items size", 2, digester.getCount());
291         value = digester.peek();
292         assertNotNull("Peeked second item is not null", value);
293         assertEquals("Peeked second item value", "Second Item", (String JavaDoc) value);
294
295         value = digester.pop();
296         assertEquals("Popped stack size", 1, digester.getCount());
297         assertNotNull("Popped second item is not null", value);
298         assertEquals("Popped second item value", "Second Item", (String JavaDoc) value);
299         value = digester.peek();
300         assertNotNull("Remaining item is not null", value);
301         assertEquals("Remaining item value", "First Item", (String JavaDoc) value);
302         assertEquals("Remaining stack size", 1, digester.getCount());
303
304         // Cleared stack is empty
305
digester.push("Dummy Item");
306         digester.clear();
307         assertEquals("Cleared stack is empty", 0, digester.getCount());
308         value = digester.peek();
309         assertNull("Cleared stack peek() returns null", value);
310         value = digester.pop();
311         assertNull("Cleared stack pop() returns null", value);
312
313     }
314
315     public void testOnceAndOnceOnly() throws Exception JavaDoc {
316         
317         class TestConfigureDigester extends Digester {
318             public int called=0;
319             public TestConfigureDigester() {}
320             
321             protected void initialize() {
322                 called++;
323             }
324         }
325         
326         TestConfigureDigester digester = new TestConfigureDigester();
327         
328         String JavaDoc xml = "<?xml version='1.0'?><document/>";
329         digester.parse(new StringReader JavaDoc(xml));
330         
331         assertEquals("Initialize should be called once and only once", 1, digester.called);
332     }
333     
334     public void testBasicSubstitution() throws Exception JavaDoc {
335         class TestSubRule extends Rule {
336             public String JavaDoc body;
337             public Attributes JavaDoc attributes;
338             
339             public void begin(String JavaDoc namespace, String JavaDoc name, Attributes JavaDoc attributes) {
340                 this.attributes = new AttributesImpl JavaDoc(attributes);
341             }
342             
343             public void body(String JavaDoc namespace, String JavaDoc name, String JavaDoc text) {
344                 this.body = text;
345             }
346         }
347         
348         TestSubRule tsr = new TestSubRule();
349         Digester digester = new Digester();
350         digester.addRule("alpha/beta", tsr);
351             
352         // it's not easy to transform dirty harry into the mighty circus - but let's give it a try
353
String JavaDoc xml = "<?xml version='1.0'?><alpha><beta forname='Dirty' surname='Harry'>Do you feel luck punk?</beta></alpha>";
354         InputSource JavaDoc in = new InputSource JavaDoc(new StringReader JavaDoc(xml));
355         
356         digester.parse(in);
357         
358         assertEquals("Unsubstituted body text", "Do you feel luck punk?", tsr.body);
359         assertEquals("Unsubstituted number of attributes", 2, tsr.attributes.getLength());
360         assertEquals("Unsubstituted forname attribute value", "Dirty", tsr.attributes.getValue("forname"));
361         assertEquals("Unsubstituted surname attribute value", "Harry", tsr.attributes.getValue("surname"));
362
363         digester.setSubstitutor(
364             new Substitutor() {
365                 public Attributes JavaDoc substitute(Attributes JavaDoc attributes) {
366                     AttributesImpl JavaDoc results = new AttributesImpl JavaDoc();
367                     results.addAttribute("", "python", "python", "CDATA", "Cleese");
368                     return results;
369                 }
370                 
371                 public String JavaDoc substitute(String JavaDoc bodyText) {
372                     return "And now for something completely different...";
373                 }
374             });
375         
376         // now transform into the full monty
377
in = new InputSource JavaDoc(new StringReader JavaDoc(xml));
378         digester.parse(in);
379         
380         assertEquals("Substituted body text", "And now for something completely different...", tsr.body);
381         assertEquals("Substituted number of attributes", 1, tsr.attributes.getLength());
382         assertEquals("Substituted python attribute value", "Cleese", tsr.attributes.getValue("", "python"));
383     }
384     
385     /** Tests the push-peek-pop cycle for a named stack */
386     public void testNamedStackPushPeekPop() throws Exception JavaDoc
387     {
388         BigDecimal JavaDoc archimedesAveragePi = new BigDecimal JavaDoc("3.1418");
389         String JavaDoc testStackName = "org.apache.commons.digester.tests.testNamedStackPushPeekPop";
390         Digester digester = new Digester();
391         assertTrue("Stack starts empty:", digester.isEmpty(testStackName));
392         digester.push(testStackName, archimedesAveragePi);
393         assertEquals("Peeked value:", archimedesAveragePi, digester.peek(testStackName));
394         assertEquals("Popped value:", archimedesAveragePi, digester.pop(testStackName));
395         assertTrue("Stack ends empty:", digester.isEmpty(testStackName));
396         
397         digester.push(testStackName, "1");
398         digester.push(testStackName, "2");
399         digester.push(testStackName, "3");
400         
401         assertEquals("Peek#1", "1", digester.peek(testStackName, 2));
402         assertEquals("Peek#2", "2", digester.peek(testStackName, 1));
403         assertEquals("Peek#3", "3", digester.peek(testStackName, 0));
404         assertEquals("Peek#3a", "3", digester.peek(testStackName));
405         
406         try {
407             // peek beyond stack
408
digester.peek(testStackName, 3);
409             fail("Peek#4 failed to throw an exception.");
410         } catch(EmptyStackException JavaDoc ex) {
411             // ok, expected
412
}
413         
414         try {
415             // peek a nonexistent named stack
416
digester.peek("no.such.stack", 0);
417             fail("Peeking a non-existent stack failed to throw an exception.");
418         } catch(EmptyStackException JavaDoc ex) {
419             // ok, expected
420
}
421     }
422     
423     /** Tests that values are stored independently */
424     public void testNamedIndependence()
425     {
426         String JavaDoc testStackOneName = "org.apache.commons.digester.tests.testNamedIndependenceOne";
427         String JavaDoc testStackTwoName = "org.apache.commons.digester.tests.testNamedIndependenceTwo";
428         Digester digester = new Digester();
429         digester.push(testStackOneName, "Tweedledum");
430         digester.push(testStackTwoName, "Tweedledee");
431         assertEquals("Popped value one:", "Tweedledum", digester.pop(testStackOneName));
432         assertEquals("Popped value two:", "Tweedledee", digester.pop(testStackTwoName));
433     }
434     
435     /** Tests popping named stack not yet pushed */
436     public void testPopNamedStackNotPushed()
437     {
438         String JavaDoc testStackName = "org.apache.commons.digester.tests.testPopNamedStackNotPushed";
439         Digester digester = new Digester();
440         try {
441         
442             digester.pop(testStackName);
443             fail("Expected an EmptyStackException");
444             
445         } catch (EmptyStackException JavaDoc e) {
446             // expected
447
}
448         
449         try {
450         
451             digester.peek(testStackName);
452             fail("Expected an EmptyStackException");
453             
454         } catch (EmptyStackException JavaDoc e) {
455             // expected
456
}
457     }
458     
459     /** Tests for isEmpty */
460     public void testNamedStackIsEmpty()
461     {
462         String JavaDoc testStackName = "org.apache.commons.digester.tests.testNamedStackIsEmpty";
463         Digester digester = new Digester();
464         assertTrue(
465             "A named stack that has no object pushed onto it yet should be empty",
466             digester.isEmpty(testStackName));
467             
468         digester.push(testStackName, "Some test value");
469         assertFalse(
470             "A named stack that has an object pushed onto it should be not empty",
471             digester.isEmpty(testStackName));
472             
473         digester.peek(testStackName);
474         assertFalse(
475             "Peek should not effect whether the stack is empty",
476             digester.isEmpty(testStackName));
477         
478         digester.pop(testStackName);
479         assertTrue(
480             "A named stack that has it's last object popped is empty",
481             digester.isEmpty(testStackName));
482     }
483
484     /**
485      * Test the Digester.getRoot method.
486      */

487     public void testGetRoot() throws Exception JavaDoc {
488         Digester digester = new Digester();
489         digester.addRule("root", new ObjectCreateRule(TestBean.class));
490             
491         String JavaDoc xml = "<root/>";
492         InputSource JavaDoc in = new InputSource JavaDoc(new StringReader JavaDoc(xml));
493         
494         digester.parse(in);
495         
496         Object JavaDoc root = digester.getRoot();
497         assertNotNull("root object not retrieved", root);
498         assertTrue("root object not a TestRule instance", (root instanceof TestBean));
499     }
500 }
501
Popular Tags