KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > commons > collections > AbstractTestObject


1 /*
2  * Copyright 2001-2004 The Apache Software Foundation
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 package org.apache.commons.collections;
17
18 import java.io.ByteArrayInputStream JavaDoc;
19 import java.io.ByteArrayOutputStream JavaDoc;
20 import java.io.File JavaDoc;
21 import java.io.FileInputStream JavaDoc;
22 import java.io.FileOutputStream JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.io.InputStream JavaDoc;
25 import java.io.ObjectInputStream JavaDoc;
26 import java.io.ObjectOutputStream JavaDoc;
27 import java.io.OutputStream JavaDoc;
28 import java.io.Serializable JavaDoc;
29
30 /**
31  * Abstract test class for {@link java.lang.Object} methods and contracts.
32  * <p>
33  * To use, simply extend this class, and implement
34  * the {@link #makeObject()} method.
35  * <p>
36  * If your {@link Object} fails one of these tests by design,
37  * you may still use this base set of cases. Simply override the
38  * test case (method) your {@link Object} fails.
39  *
40  * @version $Revision: 1.7 $ $Date: 2004/06/01 22:55:14 $
41  *
42  * @author Rodney Waldhoff
43  * @author Stephen Colebourne
44  * @author Anonymous
45  */

46 public abstract class AbstractTestObject extends BulkTest {
47
48     /** Current major release for Collections */
49     public static final int COLLECTIONS_MAJOR_VERSION = 3;
50     
51     /**
52      * JUnit constructor.
53      *
54      * @param testName the test class name
55      */

56     public AbstractTestObject(String JavaDoc testName) {
57         super(testName);
58     }
59
60     //-----------------------------------------------------------------------
61
/**
62      * Implement this method to return the object to test.
63      *
64      * @return the object to test
65      */

66     public abstract Object JavaDoc makeObject();
67
68     /**
69      * Override this method if a subclass is testing an object
70      * that cannot serialize an "empty" Collection.
71      * (e.g. Comparators have no contents)
72      *
73      * @return true
74      */

75     public boolean supportsEmptyCollections() {
76         return true;
77     }
78
79     /**
80      * Override this method if a subclass is testing an object
81      * that cannot serialize a "full" Collection.
82      * (e.g. Comparators have no contents)
83      *
84      * @return true
85      */

86     public boolean supportsFullCollections() {
87         return true;
88     }
89
90     /**
91      * Is serialization testing supported.
92      * Default is true.
93      */

94     public boolean isTestSerialization() {
95         return true;
96     }
97
98     /**
99      * Returns true to indicate that the collection supports equals() comparisons.
100      * This implementation returns true;
101      */

102     public boolean isEqualsCheckable() {
103         return true;
104     }
105
106     //-----------------------------------------------------------------------
107
public void testObjectEqualsSelf() {
108         Object JavaDoc obj = makeObject();
109         assertEquals("A Object should equal itself", obj, obj);
110     }
111
112     public void testEqualsNull() {
113         Object JavaDoc obj = makeObject();
114         assertEquals(false, obj.equals(null)); // make sure this doesn't throw NPE either
115
}
116
117     public void testObjectHashCodeEqualsSelfHashCode() {
118         Object JavaDoc obj = makeObject();
119         assertEquals("hashCode should be repeatable", obj.hashCode(), obj.hashCode());
120     }
121
122     public void testObjectHashCodeEqualsContract() {
123         Object JavaDoc obj1 = makeObject();
124         if (obj1.equals(obj1)) {
125             assertEquals(
126                 "[1] When two objects are equal, their hashCodes should be also.",
127                 obj1.hashCode(), obj1.hashCode());
128         }
129         Object JavaDoc obj2 = makeObject();
130         if (obj1.equals(obj2)) {
131             assertEquals(
132                 "[2] When two objects are equal, their hashCodes should be also.",
133                 obj1.hashCode(), obj2.hashCode());
134             assertTrue(
135                 "When obj1.equals(obj2) is true, then obj2.equals(obj1) should also be true",
136                 obj2.equals(obj1));
137         }
138     }
139
140     public void testSerializeDeserializeThenCompare() throws Exception JavaDoc {
141         Object JavaDoc obj = makeObject();
142         if (obj instanceof Serializable JavaDoc && isTestSerialization()) {
143             ByteArrayOutputStream JavaDoc buffer = new ByteArrayOutputStream JavaDoc();
144             ObjectOutputStream JavaDoc out = new ObjectOutputStream JavaDoc(buffer);
145             out.writeObject(obj);
146             out.close();
147
148             ObjectInputStream JavaDoc in = new ObjectInputStream JavaDoc(new ByteArrayInputStream JavaDoc(buffer.toByteArray()));
149             Object JavaDoc dest = in.readObject();
150             in.close();
151             if (isEqualsCheckable()) {
152                 assertEquals("obj != deserialize(serialize(obj))", obj, dest);
153             }
154         }
155     }
156
157     /**
158      * Sanity check method, makes sure that any Serializable
159      * class can be serialized and de-serialized in memory,
160      * using the handy makeObject() method
161      *
162      * @throws IOException
163      * @throws ClassNotFoundException
164      */

165     public void testSimpleSerialization() throws Exception JavaDoc {
166         Object JavaDoc o = makeObject();
167         if (o instanceof Serializable JavaDoc && isTestSerialization()) {
168             byte[] objekt = writeExternalFormToBytes((Serializable JavaDoc) o);
169             Object JavaDoc p = readExternalFormFromBytes(objekt);
170         }
171     }
172
173     /**
174      * Tests serialization by comparing against a previously stored version in CVS.
175      * If the test object is serializable, confirm that a canonical form exists.
176      */

177     public void testCanonicalEmptyCollectionExists() {
178         if (supportsEmptyCollections() && isTestSerialization() && !skipSerializedCanonicalTests()) {
179             Object JavaDoc object = makeObject();
180             if (object instanceof Serializable JavaDoc) {
181                 String JavaDoc name = getCanonicalEmptyCollectionName(object);
182                 assertTrue(
183                     "Canonical empty collection (" + name + ") is not in CVS",
184                     new File JavaDoc(name).exists());
185             }
186         }
187     }
188
189     /**
190      * Tests serialization by comparing against a previously stored version in CVS.
191      * If the test object is serializable, confirm that a canonical form exists.
192      */

193     public void testCanonicalFullCollectionExists() {
194         if (supportsFullCollections() && isTestSerialization() && !skipSerializedCanonicalTests()) {
195             Object JavaDoc object = makeObject();
196             if (object instanceof Serializable JavaDoc) {
197                 String JavaDoc name = getCanonicalFullCollectionName(object);
198                 assertTrue(
199                     "Canonical full collection (" + name + ") is not in CVS",
200                     new File JavaDoc(name).exists());
201             }
202         }
203     }
204
205     // protected implementation
206
//-----------------------------------------------------------------------
207
/**
208      * Get the version of Collections that this object tries to
209      * maintain serialization compatibility with. Defaults to 1, the
210      * earliest Collections version. (Note: some collections did not
211      * even exist in this version).
212      *
213      * This constant makes it possible for TestMap (and other subclasses,
214      * if necessary) to automatically check CVS for a versionX copy of a
215      * Serialized object, so we can make sure that compatibility is maintained.
216      * See, for example, TestMap.getCanonicalFullMapName(Map map).
217      * Subclasses can override this variable, indicating compatibility
218      * with earlier Collections versions.
219      *
220      * @return The version, or <code>null</code> if this object shouldn't be
221      * tested for compatibility with previous versions.
222      */

223     public String JavaDoc getCompatibilityVersion() {
224         return "1";
225     }
226
227     protected String JavaDoc getCanonicalEmptyCollectionName(Object JavaDoc object) {
228         StringBuffer JavaDoc retval = new StringBuffer JavaDoc();
229         retval.append("data/test/");
230         String JavaDoc colName = object.getClass().getName();
231         colName = colName.substring(colName.lastIndexOf(".") + 1, colName.length());
232         retval.append(colName);
233         retval.append(".emptyCollection.version");
234         retval.append(getCompatibilityVersion());
235         retval.append(".obj");
236         return retval.toString();
237     }
238
239     protected String JavaDoc getCanonicalFullCollectionName(Object JavaDoc object) {
240         StringBuffer JavaDoc retval = new StringBuffer JavaDoc();
241         retval.append("data/test/");
242         String JavaDoc colName = object.getClass().getName();
243         colName = colName.substring(colName.lastIndexOf(".") + 1, colName.length());
244         retval.append(colName);
245         retval.append(".fullCollection.version");
246         retval.append(getCompatibilityVersion());
247         retval.append(".obj");
248         return retval.toString();
249     }
250
251     /**
252      * Write a Serializable or Externalizable object as
253      * a file at the given path. NOT USEFUL as part
254      * of a unit test; this is just a utility method
255      * for creating disk-based objects in CVS that can become
256      * the basis for compatibility tests using
257      * readExternalFormFromDisk(String path)
258      *
259      * @param o Object to serialize
260      * @param path path to write the serialized Object
261      * @exception IOException
262      */

263     protected void writeExternalFormToDisk(Serializable JavaDoc o, String JavaDoc path) throws IOException JavaDoc {
264         FileOutputStream JavaDoc fileStream = new FileOutputStream JavaDoc(path);
265         writeExternalFormToStream(o, fileStream);
266     }
267
268     /**
269      * Converts a Serializable or Externalizable object to
270      * bytes. Useful for in-memory tests of serialization
271      *
272      * @param o Object to convert to bytes
273      * @return serialized form of the Object
274      * @exception IOException
275      */

276     protected byte[] writeExternalFormToBytes(Serializable JavaDoc o) throws IOException JavaDoc {
277         ByteArrayOutputStream JavaDoc byteStream = new ByteArrayOutputStream JavaDoc();
278         writeExternalFormToStream(o, byteStream);
279         return byteStream.toByteArray();
280     }
281
282     /**
283      * Reads a Serialized or Externalized Object from disk.
284      * Useful for creating compatibility tests between
285      * different CVS versions of the same class
286      *
287      * @param path path to the serialized Object
288      * @return the Object at the given path
289      * @exception IOException
290      * @exception ClassNotFoundException
291      */

292     protected Object JavaDoc readExternalFormFromDisk(String JavaDoc path) throws IOException JavaDoc, ClassNotFoundException JavaDoc {
293         FileInputStream JavaDoc stream = new FileInputStream JavaDoc(path);
294         return readExternalFormFromStream(stream);
295     }
296
297     /**
298      * Read a Serialized or Externalized Object from bytes.
299      * Useful for verifying serialization in memory.
300      *
301      * @param b byte array containing a serialized Object
302      * @return Object contained in the bytes
303      * @exception IOException
304      * @exception ClassNotFoundException
305      */

306     protected Object JavaDoc readExternalFormFromBytes(byte[] b) throws IOException JavaDoc, ClassNotFoundException JavaDoc {
307         ByteArrayInputStream JavaDoc stream = new ByteArrayInputStream JavaDoc(b);
308         return readExternalFormFromStream(stream);
309     }
310
311     protected boolean skipSerializedCanonicalTests() {
312         return Boolean.getBoolean("org.apache.commons.collections:with-clover");
313     }
314
315     // private implementation
316
//-----------------------------------------------------------------------
317
private Object JavaDoc readExternalFormFromStream(InputStream JavaDoc stream) throws IOException JavaDoc, ClassNotFoundException JavaDoc {
318         ObjectInputStream JavaDoc oStream = new ObjectInputStream JavaDoc(stream);
319         return oStream.readObject();
320     }
321
322     private void writeExternalFormToStream(Serializable JavaDoc o, OutputStream JavaDoc stream) throws IOException JavaDoc {
323         ObjectOutputStream JavaDoc oStream = new ObjectOutputStream JavaDoc(stream);
324         oStream.writeObject(o);
325     }
326
327 }
328
Popular Tags