KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > xml > xmlc > driver > XmlcTestCaseBase


1 /*
2  * Enhydra Java Application Server Project
3  *
4  * The contents of this file are subject to the Enhydra Public License
5  * Version 1.1 (the "License"); you may not use this file except in
6  * compliance with the License. You may obtain a copy of the License on
7  * the Enhydra web site ( http://www.enhydra.org/ ).
8  *
9  * Software distributed under the License is distributed on an "AS IS"
10  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
11  * the License for the specific terms governing rights and limitations
12  * under the License.
13  *
14  * The Initial Developer of the Enhydra Application Server is Lutris
15  * Technologies, Inc. The Enhydra Application Server and portions created
16  * by Lutris Technologies, Inc. are Copyright Lutris Technologies, Inc.
17  * All Rights Reserved.
18  *
19  * Contributor(s):
20  *
21  * $Id: XmlcTestCaseBase.java,v 1.2 2005/01/26 08:29:25 jkjome Exp $
22  */

23
24 package org.enhydra.xml.xmlc.driver;
25
26 import java.io.File JavaDoc;
27 import java.io.IOException JavaDoc;
28 import java.lang.reflect.Field JavaDoc;
29 import java.lang.reflect.Method JavaDoc;
30
31 import org.enhydra.xml.driver.TestCaseBase;
32 import org.enhydra.xml.driver.TestError;
33 import org.enhydra.xml.driver.TestException;
34 import org.enhydra.xml.xmlc.XMLCFactory;
35 import org.enhydra.xml.xmlc.XMLCLogger;
36 import org.enhydra.xml.xmlc.XMLCStdFactory;
37 import org.enhydra.xml.xmlc.XMLObject;
38 import org.enhydra.xml.xmlc.deferredparsing.XMLCDeferredParsingFactory;
39 import org.w3c.dom.Document JavaDoc;
40 import org.w3c.dom.Element JavaDoc;
41
42 /**
43  * Base class for XMLC test case classes. The <CODE>suite()<CODE> method
44  * creates instances of this test case for all combinations of the params
45  * object.
46  */

47 public class XmlcTestCaseBase extends TestCaseBase {
48     //FIXME: test an alternative naming
49
public static final boolean ALT_NAMES = true;
50
51     /** Standard result file extensions */
52     public static final String JavaDoc COMPILE_OUTPUT_EXT = "compile.out";
53     public static final String JavaDoc LOAD_DOM_EXT = "load.dom";
54     public static final String JavaDoc PARSE_GEN_OUTPUT_EXT = "parsegen.out";
55     public static final String JavaDoc PARSE_DOM_DUMP_EXT = "parse.dom";
56     public static final String JavaDoc DOC_DOM_DUMP_EXT = "doc.dom";
57
58     /** Empty arrays used to call reflection */
59     private static final Class JavaDoc[] NO_PARAMS = new Class JavaDoc[0];
60     private static final Class JavaDoc[] STR_PARAM = new Class JavaDoc[]{
61         String JavaDoc.class
62     };
63     private static final Object JavaDoc[] NO_ARGS = new Object JavaDoc[0];
64
65     /** Object containing test parameters */
66     protected final XmlcTestParams fParams;
67
68     /** Source output directory when keeping generate file */
69     private static final String JavaDoc SOURCE_DIR = "src";
70
71     /**
72      * Indicates if an implementaion/interface is being used instead of
73      * class. Set automatically is reloading testing, otherwise must
74      * be set explictly
75      */

76     private boolean fUsingImplInterface;
77
78     /** Factory for creating document objects. */
79     private XMLCFactory fXMLCFactory;
80
81     /** Test package name derived from parameters (lazy) */
82     private String JavaDoc fTestPackage;
83
84     /** Reload invarient expected results result dir (lazy) */
85     private File JavaDoc fLoadInvarExpectedDir;
86
87     /** Make a test id that includes that parameters */
88     private static String JavaDoc mkTestId(Method JavaDoc method,
89                                    XmlcTestParams params) {
90         if (ALT_NAMES) {
91             return method.getName() + "." + params.getParamsStr();
92         } else {
93             return params.getParamsStr() + "." + method.getName();
94         }
95     }
96
97     /** Constructor. */
98     public XmlcTestCaseBase(Method JavaDoc method,
99                             XmlcTestParams params) {
100         super(mkTestId(method, params), method);
101         fParams = params;
102         if (fParams.getReloading()) {
103             setUsingImplInterface();
104         }
105     }
106
107     /**
108      * Get the parameters.
109      */

110     public XmlcTestParams getParams() {
111         return fParams;
112     }
113
114     /** Set the XMLC factory to use for test */
115     public void setFactory(XMLCFactory factory) {
116         fXMLCFactory = factory;
117     }
118
119     /** Set the XMLC factory to use for test */
120     private XMLCFactory createFactory(ClassLoader JavaDoc loader, XMLCLogger logger) {
121     XMLCFactory factory;
122
123         if (fParams.getIsDeferredParsing()) {
124         factory = new XMLCDeferredParsingFactory (null, loader, logger); // use reloading loader
125
} else {
126         factory = new XMLCStdFactory(loader, logger); // use standard loader
127
}
128
129     return factory;
130     }
131
132     /** Indicate that an implementation/interface is being used. */
133     public void setUsingImplInterface() {
134         fUsingImplInterface = true;
135         if (fXMLCFactory == null) {
136             // Must go through factory to get object
137
fXMLCFactory = createFactory(getTestClassLoader(), null);
138         }
139     }
140
141     /**
142      * Get the test package, this merges in the test parameters to create
143      * a package uniqu to this parameterization. This override changes
144      * the value of all of the other directories.
145      */

146     public String JavaDoc getTestPackage() {
147         if (fTestPackage == null) {
148             if (ALT_NAMES) {
149                 // Need to add `Pkg' to prevent conflict with class name
150
fTestPackage = getClass().getName() + "Pkg" + "."
151                     + fParams.getParamsStr();
152                 
153             } else {
154             // Split test case class name, inserting paramter info before
155
// unqual class name. This good parameterizations together.
156
String JavaDoc clName = getClass().getName();
157             int dotIdx = clName.lastIndexOf('.');
158             String JavaDoc clFirst = clName.substring(0, dotIdx);
159             String JavaDoc clLast = clName.substring(dotIdx+1);
160
161             fTestPackage = clFirst + "." + fParams.getParamsStr() + "."
162                 + clLast;
163             }
164         }
165         return fTestPackage;
166     }
167     
168     /**
169      * Get the test document class name. This is the name to specify to the
170      * compiler, it maybe the name of the generated class or interface
171      * dependening on the compile options.
172      */

173     public String JavaDoc getTestClass() {
174         return getTestPackage() + "." + getTestName();
175     }
176
177     /**
178      * Get the test document implementation. This is the Impl name
179      * if seperated interfaces and implementations are being generated,
180      * otherwise it is the plain class name.
181      */

182     public String JavaDoc getTestClassImpl() {
183         if (fUsingImplInterface) {
184             return getTestClass() + "Impl";
185         } else {
186             return getTestClass();
187         }
188     }
189
190     /**
191      * Get the test document interface, if seperate interface and
192      * implementation is being generated.
193      */

194     public String JavaDoc getTestClassInterface() {
195         if (!fUsingImplInterface) {
196             throw new TestError("request for interface when one is not being used");
197         }
198         return getTestClass();
199     }
200
201     /**
202      * Get the test expected results directory for reloading-invarient
203      * expected files.
204      */

205     public File JavaDoc getLoadInvarExpectedDir() {
206         if (fLoadInvarExpectedDir == null) {
207             // Remove last directory entry
208
fLoadInvarExpectedDir
209                 = new File JavaDoc(getExpectedRoot(),
210                            getRelResultsDir().getParentFile().getPath());
211         }
212         return fLoadInvarExpectedDir;
213     }
214     
215     /** Get reload-invarient expected file name. */
216     public File JavaDoc getLoadInvarExpectedFile(String JavaDoc fname,
217                                          String JavaDoc suffix) {
218         return new File JavaDoc(getLoadInvarExpectedDir(),
219                         fname + "." + suffix);
220     }
221
222     /** Get an expected file name. */
223     public File JavaDoc getLoadInvarExpectedFile(String JavaDoc suffix) {
224         return getLoadInvarExpectedFile(getTestName(), suffix);
225     }
226
227
228     /** Get source output directory using when keeping generate file */
229     public File JavaDoc getGenSourceDir() {
230         return new File JavaDoc(getOutputRoot(), SOURCE_DIR);
231     }
232     
233     /** Get the class name as a path */
234     public String JavaDoc getClassNameAsPath() {
235         return getTestClass().replace('.', File.separatorChar);
236     }
237
238     /** Get the name of the generated source file for this test */
239     public File JavaDoc getGenSrcFile() {
240         return new File JavaDoc(getGenSourceDir(), getClassNameAsPath() + ".java");
241     }
242
243     /** Get the name of the generated class file for this test */
244     public File JavaDoc getGenClassFile() {
245         return new File JavaDoc(getClassRoot(), getClassNameAsPath() + ".class");
246     }
247
248     /** Remove a file, making sure it was deleted */
249     public void removeFile(File JavaDoc file) {
250         file.delete();
251         if (file.exists()) {
252             throw new TestException("file still exists after deleting: "
253                                     + file);
254         }
255     }
256
257     /** Check that a file exists file, generate error if it doesn't */
258     public void verifyExists(File JavaDoc file) {
259         if (!file.exists()) {
260             throw new TestException("file was not created: " + file);
261         }
262     }
263
264     /**
265      * Load a document with the XMLC factory, creating one if one is not
266      * defined in the class.
267      */

268     private XMLObject loadDocWithFactory(Object JavaDoc spec)
269         throws IOException JavaDoc, ClassNotFoundException JavaDoc {
270         XMLCFactory factory = fXMLCFactory;
271         if (factory == null) {
272             // Create a new factory
273
factory = createFactory(getTestClassLoader(), null);
274         }
275         if (spec instanceof String JavaDoc) {
276             return factory.create((String JavaDoc)spec);
277         } else {
278             return factory.create((Class JavaDoc)spec);
279         }
280     }
281
282     /**
283      * Get a document test class. This returns the class, not the
284      * document object.
285      */

286     public Class JavaDoc loadDocClass(String JavaDoc className) {
287         try {
288             return getTestClassLoader().loadClass(className);
289         } catch (ClassNotFoundException JavaDoc except) {
290             throw new TestException(except);
291         }
292     }
293     
294     /**
295      * Get the document class.
296      */

297     public Class JavaDoc loadDocClass() {
298         return loadDocClass(getTestClassImpl());
299     }
300     
301     /**
302      * Get the document interface.
303      */

304     public Class JavaDoc loadDocClassInterface() {
305         return loadDocClass(getTestClassInterface());
306     }
307     
308     /**
309      * Load a document with a classloader. This simulates a new
310      * in compiled code.
311      */

312     private XMLObject loadDocWithClassLoader(Object JavaDoc spec)
313         throws IllegalAccessException JavaDoc, InstantiationException JavaDoc,
314                IOException JavaDoc, ClassNotFoundException JavaDoc {
315         Class JavaDoc objClass = getTestClassLoader().loadClass((String JavaDoc)spec);
316         return (XMLObject)objClass.newInstance();
317     }
318
319     /**
320      * Get an instance of a XMLC document class.
321      *
322      * @param spec Can be either the name of the class name, interface name
323      * or inteface object.
324      */

325     public XMLObject loadTestDocument(Object JavaDoc spec) {
326         try {
327         return loadDocWithFactory(spec);
328         } catch (Throwable JavaDoc except) {
329             // Catch everything, this is a common failure point
330
throw new TestException("failed to load XMLC document class: \""
331                                     + spec + "\"", except);
332         }
333     }
334
335     /**
336      * Get an instance of the XMLC document class defined by the
337      * current test id.
338      */

339     public XMLObject loadTestDocument() {
340         return loadTestDocument(getTestClass());
341     }
342
343     /**
344      * Compile and load a test document
345      * @param unqualClassName maybe null
346      * @param impls Interface to implement, maybe null.
347      */

348     public XMLObject compileLoadDoc(File JavaDoc srcFile,
349                                     String JavaDoc unqualClassName,
350                                     Class JavaDoc impls) {
351         // FIXME: could this be replaced with TEstDOMSource factory>>
352
ExecXmlc execXmlc = new ExecXmlc(this);
353         String JavaDoc className = (unqualClassName != null)
354             ? (getTestPackage() + "." + unqualClassName)
355             : getTestClass();
356         execXmlc.addOpt(ExecXmlc.OPT_CLASS, className);
357         if (impls != null) {
358             execXmlc.addOpt(ExecXmlc.OPT_IMPLEMENTS,
359                             impls.getClass().getName());
360         }
361         execXmlc.setSrcFile(srcFile);
362         execXmlc.compile(getResultFile(COMPILE_OUTPUT_EXT));
363         return loadTestDocument(className);
364     }
365
366     /**
367      * Dump the DOM to a file and verify against an expected.
368      */

369     public void dumpVerifyDom(Document JavaDoc doc,
370                               File JavaDoc resultFile,
371                               File JavaDoc expectFile) {
372         OutputDocument.dump(doc, resultFile);
373         getDiffer().diff(expectFile, resultFile);
374     }
375
376     /**
377      * Dump the DOM to a file and verify against an expected.
378      */

379     public void dumpVerifyDom(Document JavaDoc doc,
380                               String JavaDoc resultFileExt) {
381         dumpVerifyDom(doc, getResultFile(resultFileExt),
382                       getExpectedFile(resultFileExt));
383     }
384
385     /**
386      * Dump the DOM without verification
387      */

388     public void dumpDom(Document JavaDoc doc,
389                         String JavaDoc resultFileExt) {
390         OutputDocument.dump(doc, getResultFile(resultFileExt));
391     }
392
393     /**
394      * Parse a document with XMLC and dump the DOM to a file and verify
395      * against an expected.
396      */

397     public void parseVerifyDom(File JavaDoc srcDoc) {
398         // Use XMLC to parse and dump the DOM.
399
ExecXmlc dumper = new ExecXmlc(this);
400         dumper.addOpt(ExecXmlc.OPT_DUMP);
401         dumper.addOpt(ExecXmlc.OPT_METHODS);
402         dumper.addOpt(ExecXmlc.OPT_NO_COMPILE);
403         dumper.addOpt(ExecXmlc.OPT_CLASS, getTestClass());
404         dumper.setSrcFile(srcDoc);
405         dumper.compile(getResultFile(PARSE_DOM_DUMP_EXT));
406         getDiffer().diff(getExpectedFile(PARSE_DOM_DUMP_EXT),
407                          getResultFile(PARSE_DOM_DUMP_EXT));
408     }
409
410     /**
411      * Get the value of a string field.
412      * @param obj is either the object or a class object to get a static
413      * fiels.
414      */

415     public String JavaDoc getStringField(Object JavaDoc obj,
416                                  String JavaDoc fieldName) {
417         try {
418             if (obj instanceof Class JavaDoc) {
419                 Field JavaDoc field = ((Class JavaDoc)obj).getField(fieldName);
420                 return (String JavaDoc)field.get(null);
421             } else {
422                 Field JavaDoc field = obj.getClass().getField(fieldName);
423                 return (String JavaDoc)field.get(obj);
424             }
425         } catch (Throwable JavaDoc except) {
426             Class JavaDoc cl = (obj instanceof Class JavaDoc) ? (Class JavaDoc)obj
427                 : obj.getClass();
428             throw new TestException("error getting field \"" + fieldName
429                                     + "\" of class \"" + cl);
430         }
431     }
432
433     /** Verify the return type of a method */
434     private void verifyReturnType(Method JavaDoc method,
435                                   Class JavaDoc returnInstanceOf) {
436         if (!returnInstanceOf.isAssignableFrom(method.getReturnType())) {
437             throw new TestException("return type of \"" + method.getName()
438                                     + "\", \"" + method.getReturnType()
439                                     + "\", is not an instance of \""
440                                     + returnInstanceOf + "\"");
441         }
442     }
443
444     /**
445      * Call a getElement method via reflection.
446      * @param nameSuffix Is the method name less the `getElement'.
447      * @param returnInstanceOf If not null, verify that the return type
448      * is an instance of this class.
449      */

450     public Element JavaDoc callGetElement(XMLObject xmlObj,
451                                   String JavaDoc nameSuffix,
452                                   Class JavaDoc returnInstanceOf) {
453         String JavaDoc methodName = "getElement" + nameSuffix;
454         try {
455             Method JavaDoc method = xmlObj.getClass().getMethod(nameSuffix, NO_PARAMS);
456             if (returnInstanceOf != null) {
457                 verifyReturnType(method, returnInstanceOf);
458             }
459             return (Element JavaDoc)method.invoke(xmlObj, NO_ARGS);
460         } catch (Throwable JavaDoc except) {
461             throw new TestException("error calling \"" + methodName
462                                     + "\" of class \""
463                                     + xmlObj.getClass().getName());
464         }
465     }
466
467     /**
468      * Call a setTest method via reflection.
469      * @param nameSuffix Is the method name less the `setText'.
470      */

471     public void callSetText(XMLObject xmlObj,
472                             String JavaDoc nameSuffix,
473                             String JavaDoc value) {
474         String JavaDoc methodName = "setText" + nameSuffix;
475         try {
476             Method JavaDoc method = xmlObj.getClass().getMethod(nameSuffix, STR_PARAM);
477             verifyReturnType(method, Void JavaDoc.class);
478             method.invoke(xmlObj, (Object JavaDoc[])new String JavaDoc[]{value});
479         } catch (Throwable JavaDoc except) {
480             throw new TestException("error calling \"" + methodName
481                                     + "\" of class \""
482                                     + xmlObj.getClass().getName());
483         }
484     }
485
486     /** Load a class by name */
487     private Class JavaDoc loadClass(String JavaDoc name) {
488         try {
489             return getClass().getClassLoader().loadClass(name);
490         } catch (ClassNotFoundException JavaDoc except) {
491             throw new TestException(except);
492         }
493     }
494
495     /** check is a class is an instance of a specified class */
496     public void verifyInstanceOf(Class JavaDoc testClass,
497                                  Class JavaDoc expectClass) {
498         if (!expectClass.isAssignableFrom(testClass)) {
499             throw new TestException(testClass + " is not an instance of "
500                                     + expectClass);
501         }
502     }
503
504     /** check is a class is an instance of a specified class name */
505     public void verifyInstanceOf(Class JavaDoc testClass,
506                                  String JavaDoc expectClass) {
507         verifyInstanceOf(testClass, loadClass(expectClass));
508     }
509
510     /** check is a class is an instance of all classes in a list */
511     public void verifyInstanceOf(Class JavaDoc testClass,
512                                  String JavaDoc[] expectClasses) {
513         for (int i = 0; i < expectClasses.length; i++) {
514             verifyInstanceOf(testClass, expectClasses[i]);
515         }
516     }
517
518     /** check is a class is not an instance of a specified class */
519     public void verifyNotInstanceOf(Class JavaDoc testClass,
520                                     Class JavaDoc expectClass) {
521         if (expectClass.isAssignableFrom(testClass)) {
522             throw new TestException(testClass
523                                     + " should not be an instance of "
524                                     + expectClass);
525         }
526     }
527
528     /** check is a class is not an instance of a specified class name */
529     public void verifyNotInstanceOf(Class JavaDoc testClass,
530                                     String JavaDoc expectClass) {
531         verifyNotInstanceOf(testClass, loadClass(expectClass));
532     }
533
534     /** check is a class is not an instance of all classes in a list */
535     public void verifyNotInstanceOf(Class JavaDoc testClass,
536                                     String JavaDoc[] expectClasses) {
537         for (int i = 0; i < expectClasses.length; i++) {
538             verifyNotInstanceOf(testClass, expectClasses[i]);
539         }
540     }
541
542     /* Verify that a class object is an interface */
543     public void verifyIsInterface(Class JavaDoc testClass) {
544         if (!testClass.isInterface()) {
545             throw new TestException("class is not an interface:"
546                                     + testClass);
547         }
548     }
549
550     /* Verify that a class object is an class (not an interface) */
551     public void verifyIsClass(Class JavaDoc testClass) {
552         if (testClass.isInterface() || testClass.isPrimitive()) {
553             throw new TestException("class is not an class:"
554                                     + testClass);
555         }
556     }
557 }
558
Popular Tags