KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > sape > carbon > services > cache > test > CacheServiceTest


1 /*
2  * The contents of this file are subject to the Sapient Public License
3  * Version 1.0 (the "License"); you may not use this file except in compliance
4  * with the License. You may obtain a copy of the License at
5  * http://carbon.sf.net/License.html.
6  *
7  * Software distributed under the License is distributed on an "AS IS" basis,
8  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
9  * the specific language governing rights and limitations under the License.
10  *
11  * The Original Code is The Carbon Component Framework.
12  *
13  * The Initial Developer of the Original Code is Sapient Corporation
14  *
15  * Copyright (C) 2003 Sapient Corporation. All Rights Reserved.
16  */

17
18 package org.sape.carbon.services.cache.test;
19
20 import java.util.HashMap JavaDoc;
21
22 import org.sape.carbon.core.component.Lookup;
23 import org.sape.carbon.core.component.lifecycle.LifecycleException;
24 import org.sape.carbon.core.config.InvalidConfigurationException;
25 import org.sape.carbon.core.exception.ExceptionUtility;
26 import org.sape.carbon.services.cache.Cache;
27
28 import junit.extensions.ActiveTestSuite;
29 import junit.framework.Test;
30 import junit.framework.TestCase;
31 import junit.framework.TestSuite;
32
33 /**
34  * Template for junit test harness. Change this description to reflect what this class is testing.
35  * @since carbon 1.0
36  * @author Douglas Voet, March 2002
37  * @version $Revision: 1.11 $($Author: ghinkl $ / $Date: 2003/07/03 18:37:23 $)
38  * <br>Copyright 2002 Sapient
39  */

40 public class CacheServiceTest extends TestCase {
41     public CacheServiceTest(String JavaDoc name) {
42         super(name);
43     }
44
45     /**
46      * Test failure mode when the configuration service contains invalid
47      * configuration information for this cache, such as a dataLoader which is
48      * not of the right class.
49      */

50     public void testInvalidConfigInfo() {
51
52         try {
53             Lookup.getInstance().fetchComponent("/cache/test/invalidCache");
54             TestCase.fail("Able to create a cache with missing " +
55                 "configuration information");
56         } catch (InvalidConfigurationException e) {
57             // expected
58
}
59     }
60
61     /**
62      * Test the condition if a cache key is not found
63      */

64     public void testValueNotFound() {
65
66         Object JavaDoc cacheValue;
67         Integer JavaDoc invalidKey = new Integer JavaDoc(CacheServiceTest.CACHE_SIZE + 1);
68
69         Cache localCache =
70             (Cache) Lookup.getInstance().fetchComponent(TOTAL_CACHE_NAME);
71
72         // The cache service should return a null value
73
assertNull("Call to get() with an invalid key should return null",
74                    localCache.get(invalidKey) );
75
76         // The containsKey Method should return false
77
assertTrue("Call to containsKey should return false",
78                !localCache.containsKey(invalidKey));
79     }
80
81     /**
82      * Test Total Cache load exception
83      */

84     public void testTotalCacheLoadException() {
85
86         try {
87             Lookup.getInstance().fetchComponent(
88                 TOTAL_CACHE_WITH_EXCPETION_NAME);
89
90             fail("Did not catch expected LifecycleException");
91
92         } catch (LifecycleException le) {
93             // expected result - eat it
94
}
95     }
96
97
98     public void testTotalCacheAccess() {
99         testCacheAccess(TOTAL_CACHE_NAME);
100     }
101
102     public void testMruCacheAccess() {
103         testCacheAccess(MRU_CACHE_NAME);
104     }
105
106     /**
107      * Tests threaded access to the MRUCache to ensure that it performs
108      * properly under such conditions.
109      */

110     private void testCacheAccess(String JavaDoc cacheName) {
111         final int NUM_READS = 5000;
112
113         // Initialize the cache
114
Cache localCache =
115             (Cache) Lookup.getInstance().fetchComponent(cacheName);
116
117         // Start run
118
for (int i=0; i<NUM_READS; ++i) {
119             
120             //Integer key = new Integer(
121
// (int) (Math.random() * CACHE_SIZE));
122
Integer JavaDoc key = new Integer JavaDoc(i % CACHE_SIZE);
123             Object JavaDoc value = localCache.get(key);
124             if(!getCacheValue(key).equals(value)) {
125                 TestCase.fail("Value for given key was not as expected. " +
126                     "Actual: [" + value +
127                     "] Expected: [" + getCacheValue(key) + "]");
128             }
129         }
130     }
131
132
133     public void testMruCachePuts() {
134         testPuts(MRU_CACHE_NAME);
135     }
136
137     private void testPuts(String JavaDoc cacheName) {
138         final int puts = CACHE_SIZE * 5;
139
140         // Initialize the cache
141
Cache localCache =
142             (Cache) Lookup.getInstance().fetchComponent(cacheName);
143
144         // Start run
145
for (int i=0; i < puts; ++i) {
146             Integer JavaDoc key = new Integer JavaDoc(i % CACHE_SIZE);
147             localCache.put(key, key);
148             Object JavaDoc retrievedValue = localCache.get(key);
149             if(!retrievedValue.equals(key)) {
150                 TestCase.fail("Retrieved value was not the same as put in. " +
151                     "Actual: [" + retrievedValue +
152                     "] Expected: [" + key + "]");
153             }
154         }
155     }
156
157
158     /**
159      * Tests the expiration ablity of the MRUCache
160      *
161      * set expiration to 100 millis
162      * insert items in the MRUCache at a rate of 40 millis
163      * Number of elements 1 2 3 4 5 6 7 8 9 10
164      * Set of items [10,20,30,30,40,50,60,70,30,70]
165      * Hit of Miss M M M H M M M M M H
166      * therefore we should get a hit rate of 20%
167      */

168     public void testMruCacheExpiration() {
169         Cache localCache =
170             (Cache) Lookup.getInstance().fetchComponent(MRU_CACHE_NAME);
171
172         localCache.get(new Integer JavaDoc(1));
173         mruItemLoaded = false;
174
175         try {
176             Thread.sleep(600);
177         } catch(InterruptedException JavaDoc e) { }
178
179         localCache.get(new Integer JavaDoc(1));
180
181         TestCase.assertTrue("DataLoader was not called for expired cache object",
182             mruItemLoaded);
183     }
184
185     /**
186      * Tests the integrety of the MRU Cache that was created dynamically during
187      * the course of the above tests. Given the complexity of TreeSets and
188      * implementing the Comparable interface it is important to test that each
189      * collection in the cache is the size of the capacity after exercising it
190      * fully!
191      */

192     public void testMruCacheDrops() {
193         Cache localCache =
194             (Cache) Lookup.getInstance().fetchComponent(MRU_CACHE_NAME);
195
196         for(int i=0; i<1010; i++) {
197             localCache.get(new Integer JavaDoc(i));
198         }
199         mruItemLoaded = false;
200
201         localCache.get(new Integer JavaDoc(1));
202
203         TestCase.assertTrue("DataLoader was not called for droped cache object",
204             mruItemLoaded);
205     }
206
207     public void startScheduler() {
208         Lookup.getInstance().fetchComponent(SCHEDULER_NAME);
209     }
210
211     public void stopScheduler() {
212         Lookup.getInstance().getComponentKeeper().
213             destroyComponent(SCHEDULER_NAME);
214     }
215
216     /**
217      * This method is used to test writeable cache.
218      */

219     public void testWriteableCache() {
220         Cache localCache =
221             (Cache) Lookup.getInstance().fetchComponent(WRITEABLE_CACHE_NAME);
222
223         HashMap JavaDoc testMapForCache = new HashMap JavaDoc();
224         String JavaDoc KEY_FOR_CACHE_ITEM = "key_test_writeable";
225         String JavaDoc valueForCacheItem = "value_test_writeable";
226         try {
227             int initialCacheSize = localCache.size();
228             Object JavaDoc verifyResult = localCache.put(KEY_FOR_CACHE_ITEM,VALUE_FOR_CACHE_ITEM);
229             int newCacheSize = localCache.size();
230             boolean validResult = false;
231             if (newCacheSize == (initialCacheSize + 1)) {
232                 validResult = true;
233             }
234             TestCase.assertTrue("Cannot write to writeable cache",validResult);
235
236             // restoring the cache status to the pre-test case running status
237
verifyResult = localCache.remove(KEY_FOR_CACHE_ITEM);
238         } catch (UnsupportedOperationException JavaDoc uoe) {
239             TestCase.fail("Cannot write to cache " +
240                            ExceptionUtility.printStackTracesToString(uoe));
241         }
242     }
243
244     public static final int CACHE_SIZE = 1000;
245     public static final String JavaDoc TOTAL_CACHE_WITH_EXCPETION_NAME =
246         "/cache/test/TestTotalCacheWithException";
247     public static final String JavaDoc TOTAL_CACHE_NAME = "/cache/test/testTotalCache";
248     public static final String JavaDoc MRU_CACHE_NAME = "/cache/test/testMRUCache";
249     public static final String JavaDoc SCHEDULER_NAME = "/cache/test/testScheduler";
250     public static final String JavaDoc WRITEABLE_CACHE_NAME = "/cache/test/testWriteableCache";
251     public static final String JavaDoc KEY_FOR_CACHE_ITEM = "key_test_writeable";
252     public static final String JavaDoc VALUE_FOR_CACHE_ITEM = "value_test_writeable";
253     private static boolean mruItemLoaded;
254
255     public static String JavaDoc getCacheValue(Integer JavaDoc i) {
256         return "String " + i.toString();
257     }
258
259     /**
260      * Method called by jUnit to get all the tests in this test case.
261      * @return Test the suite of tests in this test case
262      */

263     public static Test suite() {
264         TestSuite masterSuite = new TestSuite();
265         masterSuite.addTest(new CacheServiceTest("startScheduler"));
266         // add single threaded tests
267
Test singleThreadedTests = getSingleThreadedTests();
268         if (singleThreadedTests != null) {
269             masterSuite.addTest(singleThreadedTests);
270         }
271         // add multi threaded tests
272
Test multiThreadedTests = getMultiThreadedTests();
273         if (multiThreadedTests != null) {
274             masterSuite.addTest(multiThreadedTests);
275         }
276         masterSuite.addTest(new CacheServiceTest("stopScheduler"));
277         return masterSuite;
278     }
279
280     public static void setMRUItemLoaded() {
281         mruItemLoaded = true;
282     }
283
284     /**
285      * This method is used within the suite method to get all of the single threaded tests.
286      * Add all your single threaded tests in this method with a line like:
287      * suite.addTest(new CacheServiceTest("testFunction1"));
288      * @return Test the suite of single threaded tests in this test case
289      */

290     private static Test getSingleThreadedTests() {
291         TestSuite mySuite = new TestSuite();
292
293         mySuite.addTest(new CacheServiceTest("testMruCacheAccess"));
294         mySuite.addTest(new CacheServiceTest("testTotalCacheAccess"));
295         mySuite.addTest(new CacheServiceTest("testInvalidConfigInfo"));
296         mySuite.addTest(new CacheServiceTest("testTotalCacheLoadException"));
297         mySuite.addTest(new CacheServiceTest("testValueNotFound"));
298         mySuite.addTest(new CacheServiceTest("testMruCacheExpiration"));
299         mySuite.addTest(new CacheServiceTest("testMruCacheDrops"));
300         mySuite.addTest(new CacheServiceTest("testWriteableCache"));
301
302         return mySuite;
303     }
304
305     /**
306      * This method is used within the suite method to get all of the multi threaded tests.
307      * Add all your multi threaded tests in this method with a line like: addTest(suite, "testFunction1", 5);
308      * @return Test the suite of multi-threaded tests in this test case
309      */

310     private static Test getMultiThreadedTests() {
311         TestSuite suite = new TestSuite("Multithreaded Cache tests");
312         final int THREAD_COUNT = 10;
313
314         TestSuite mruAccess = new ActiveTestSuite();
315         addTest(mruAccess, "testMruCacheAccess", THREAD_COUNT);
316         TestSuite totalAccess = new ActiveTestSuite();
317         addTest(totalAccess, "testTotalCacheAccess", THREAD_COUNT);
318
319         TestSuite mruPuts = new ActiveTestSuite();
320         addTest(mruPuts, "testMruCachePuts", THREAD_COUNT);
321
322         suite.addTest(mruAccess);
323         suite.addTest(totalAccess);
324         suite.addTest(mruPuts);
325
326         return suite;
327     }
328
329     /**
330      * This method will add the give test to the give suite the specified
331      * number of times. This is best used for multi-threaded tests where
332      * suite is an instance of ActiveTestSuite and you want to run the same test in multiple threads.
333      * @param suite the suite to add the test to.
334      * @param testName the name of the test to add.
335      * @param number the number of times to add the test to the suite
336      */

337     private static void addTest(TestSuite suite, String JavaDoc testName, int number) {
338         for (int count = 0; count < number; count++) {
339             suite.addTest(new CacheServiceTest(testName));
340         }
341     }
342
343 }
344
Popular Tags