View Javadoc
1   /*
2    * Copyright 2006 Edward Kuns
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   * $Id: TestWithRandomDocument.java 0000 2006-10-19 22:00:00Z ekuns $
17   */
18  package org.castor.xmlctf;
19  
20  import java.io.File;
21  import java.io.FileWriter;
22  
23  import junit.framework.TestCase;
24  
25  import org.exolab.castor.tests.framework.testDescriptor.FailureType;
26  import org.exolab.castor.tests.framework.testDescriptor.types.FailureStepType;
27  import org.exolab.castor.xml.XMLContext;
28  
29  /**
30   * Implements a test case that tests code written by the XML source generator.
31   * This class uses the generated source to write a randomly generated XML
32   * element to a file.
33   * <p>
34   * The test follows this sequence:
35   * <ol>
36   *   <li>Instantiates a random object model using the randomize function.</li>
37   *   <li>Marshals it to a file.</li>
38   *   <li>Unmarshals the created file.</li>
39   *   <li>Check that the result object is equal to the start object.</li>
40   * </ol>
41   *
42   * @author <a href="mailto:gignoux@kernelcenter.org">Sebastien Gignoux</a>
43   * @author <a href="mailto:blandin@intalio.com">Arnaud Blandin</a>
44   * @author <a href="mailto:edward.kuns@aspect.com">Edward Kuns</a>
45   * @version $Revision: 0000 $ $Date: $
46   */
47  class TestWithRandomObject extends TestCase {
48      /** We add this fixed string to the end of our testcase name. */
49      private static final String RANDOM = "_RandomObject";
50  
51      /** We delegate all actions to this test case. */
52      private final XMLTestCase   _delegate;
53  
54      /** The failure object that is not null is the test intends to fail. */
55      protected final FailureType _failure;
56      /** File name of our marshaled output. */
57      protected final String      _outputName;
58  
59      /**
60       * Blank constructor for this test case.  This contructor is not useful, since
61       * no delegate test case is provided
62       * @param name Name of our delegate test case
63       */
64      TestWithRandomObject(String name) {
65          super(name+RANDOM);
66          throw new IllegalArgumentException("You cannot use the name-only constructor");
67      }
68  
69      /**
70       * Constructs a test case that when invoked will delegate to the provided
71       * test case.
72       * @param name Name of our delegate test case
73       * @param tc
74       */
75      TestWithRandomObject(String name, XMLTestCase tc) {
76          super(name+RANDOM);
77          _delegate   = tc;
78          _failure    = tc._failure;
79          _outputName = _delegate._name.replace(' ', '_') + "-testWithRandomObject";
80      }
81  
82      /**
83       * Provides setup for our delegated test case, depending on the type of
84       * test case we are delegating for.
85       * @throws Exception if anything goes wrong during setup
86       */
87      protected void setUp() throws Exception {
88          _delegate.setXMLContext(new XMLContext());
89          _delegate.setUp();
90  //        if (_delegate instanceof MarshallingFrameworkTestCase) {
91  //            ((MarshallingFrameworkTestCase)_delegate).setUp();
92  //        } else if (_delegate instanceof SourceGeneratorTestCase) {
93  //            ((SourceGeneratorTestCase)_delegate).setUp();
94  //        }
95      }
96  
97      /**
98       * Provides tear down for our delegated test case, depending on the type of
99       * test case we are delegating for.
100      * @throws Exception if anything goes wrong during teardown
101      */
102     protected void tearDown() throws Exception {
103         _delegate.setUp();
104 //        if (_delegate instanceof MarshallingFrameworkTestCase) {
105 //            ((MarshallingFrameworkTestCase)_delegate).tearDown();
106 //        } else if (_delegate instanceof SourceGeneratorTestCase) {
107 //            ((SourceGeneratorTestCase)_delegate).tearDown();
108 //        }
109     }
110 
111     /**
112      * Runs our test case using our delegate object where necessary.
113      */
114     public void runTest() throws Exception { // FIXME - temporarily throws Exception
115         verbose("\n------------------------------");
116         verbose("Test with randomly generated object");
117         verbose("------------------------------\n");
118         if (_delegate._skip) {
119             verbose("-->Skipping the test");
120             return;
121         }
122 
123         // Randomize an object model instance
124         CastorTestable randomizedObject = getRandomizedReference();
125 
126         // Dump the new random object to a file
127         if (_delegate._hasDump) {
128             verbose("----> Dump the object to '" + _outputName + "-ref.dump" +"'");
129             FileWriter writer = new FileWriter(new File(_delegate._outputRootFile, _outputName + "-ref.dump"));
130             writer.write(randomizedObject.dumpFields());
131             writer.close();
132         }
133 
134         // Marshal our reference object to disk
135         File marshal_output = _delegate.testMarshal(randomizedObject, _outputName + ".xml");
136         if (marshal_output == null) {
137             return;
138         }
139 
140         // Unmarshal from disk
141         Object unmarshaledRandomizedObject;
142         try {
143             unmarshaledRandomizedObject = _delegate.testUnmarshal(marshal_output);
144         } catch (Exception e) {
145             if (!_delegate.checkExceptionWasExpected(e, FailureStepType.SECOND_UNMARSHAL)) {
146                 fail("Exception Unmarshaling from disk " + e);
147             }
148             return;
149         }
150 
151         if (_failure != null && _failure.getContent() && _failure.getFailureStep() != null &&
152             _failure.getFailureStep().equals(FailureStepType.SECOND_UNMARSHAL)) {
153             fail("Unmarshaling the marshaled random document was expected to fail, but succeeded");
154         }
155 
156         // Dump the unmarshaled object to a file
157         if (_delegate._hasDump) {
158             verbose("---->Dump the object to '" + _outputName + "-unmar.dump" +"'");
159             FileWriter writer = new FileWriter(new File(_delegate._outputRootFile, _outputName + "-unmar.dump"));
160             writer.write(((CastorTestable)unmarshaledRandomizedObject).dumpFields());
161             writer.close();
162         }
163 
164         // Compare unmarshaled output file to our initial randomized instance
165         boolean result = unmarshaledRandomizedObject.equals(randomizedObject);
166         verbose("----> Compare unmarshaled document to reference object: " + ((result)?"OK":"### Failed ### "));
167 
168         final FailureStepType step = _failure != null ? _failure.getFailureStep() : null;
169         final boolean expectedToFail = _failure != null && _failure.getContent()
170                    && (step == null || step.equals(FailureStepType.COMPARE_TO_REFERENCE));
171 
172         if (_failure == null || !_failure.getContent()) {
173             assertTrue("The initial randomized object and the one resulting of the" +
174                        " marshal/unmarshal process are different", result);
175         } else if (expectedToFail) {
176             assertFalse("Comparing the random object to the marshal+unmarshaled one" +
177                         " was expected to fail, but succeeded", result);
178         }
179 
180         if (expectedToFail ^ result) {
181             return;
182         }
183 
184         if (_failure != null && _failure.getContent()) {
185             fail("The test with random document was expected to fail, but passed");
186         }
187     }
188 
189     /**
190      * Creates and returns a new instance of the root object set with random values.
191      * @return a new instance of the root object set with random values.
192      * @throws InstantiationException
193      * @throws IllegalAccessException
194      */
195     private CastorTestable getRandomizedReference() throws InstantiationException, IllegalAccessException {
196         verbose("--> Randomize an object model for the root '" + _delegate._rootClassName + "'.");
197         CastorTestable randomizedObject = ((CastorTestable)_delegate._rootClass.newInstance());
198         assertNotNull("Randomized object model is null", randomizedObject);
199         randomizedObject.randomizeFields();
200         return randomizedObject;
201     }
202 
203     private void verbose(String message) {
204         _delegate.verbose(message);
205     }
206 
207 }