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