KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > core > container > ContainerTestCase


1 /*
2  * Copyright 1999-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.cocoon.core.container;
17
18 import java.io.InputStream JavaDoc;
19 import java.net.URL JavaDoc;
20
21 import junit.framework.TestCase;
22
23 import org.apache.avalon.excalibur.component.DefaultRoleManager;
24 import org.apache.avalon.excalibur.component.ExcaliburComponentManager;
25 import org.apache.avalon.excalibur.logger.LoggerManager;
26 import org.apache.avalon.framework.configuration.Configuration;
27 import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
28 import org.apache.avalon.framework.container.ContainerUtil;
29 import org.apache.avalon.framework.context.Context;
30 import org.apache.avalon.framework.context.DefaultContext;
31 import org.apache.avalon.framework.logger.ConsoleLogger;
32 import org.apache.avalon.framework.logger.Logger;
33 import org.apache.avalon.framework.service.ServiceException;
34 import org.apache.avalon.framework.service.ServiceManager;
35 import org.apache.avalon.framework.service.WrapperServiceManager;
36 import org.apache.cocoon.util.Deprecation;
37
38 /**
39  * JUnit TestCase for Cocoon Components.
40  * <p>
41  * This class extends the JUnit TestCase class to setup an environment which
42  * makes it possible to easily test Cocoon Components. The following methods
43  * and instance variables are exposed for convenience testing:
44  * </p>
45  * <dl>
46  * <dt>getManager()</dt>
47  * <dd>
48  * This instance variable contains an initialized service manager which
49  * can be used to lookup components configured in the test configuration
50  * file. (see below)
51  * </dd>
52  * <dt>getLogger()</dt>
53  * <dd>
54  * This method returns a logger for this test case. By default this
55  * logger logs with log level DEBUG.
56  * </dd>
57  * </dl>
58  * <p>
59  * The following test case configuration can be used as a basis for new tests.
60  * Detailed explanations of the configuration elements can be found after
61  * the example.
62  * </p>
63  * <pre>
64  * &lt;testcase&gt;
65  * &lt;context&gt;
66  * &lt;entry name="foo" value="bar"/&gt;
67  * &lt;entry name="baz" class="my.context.Class"/&gt;
68  * &lt;/context&gt;
69  *
70  * &lt;roles&gt;
71  * &lt;role name="org.apache.avalon.excalibur.datasource.DataSourceComponentSelector"
72  * shorthand="datasources"
73  * default-class="org.apache.avalon.excalibur.component.ExcaliburComponentSelector"&gt;
74  * &lt;hint shorthand="jdbc" class="org.apache.avalon.excalibur.datasource.JdbcDataSource"/&gt;
75  * &lt;/role&gt;
76  * &lt;/roles&gt;
77  *
78  * &lt;components&gt;
79  * &lt;datasources&gt;
80  * &lt;jdbc name="personell"&gt;
81  * &lt;pool-controller min="5" max="10"/&gt;
82  * &lt;jdbc name="personnel"/&gt;
83  * &lt;dburl&gt;jdbc:odbc:test&lt;/dburl&gt;
84  * &lt;user&gt;test&lt;/user&gt;
85  * &lt;password&gt;test&lt;/password&gt;
86  * &lt;driver&gt;sun.jdbc.odbc.JdbcOdbcDriver&lt;/driver&gt;
87  * &lt;/jdbc&gt;
88  * &lt;/datasources&gt;
89  * &lt;/components&gt;
90  * &lt;/testcase&gt;
91  * </pre>
92  * <p>
93  * Element Explanation:
94  * <dl>
95  * <dt>testcase</dt>
96  * <dd>Defines a test case configuration. Must contain one each of the
97  * following elements: <code>annotation</code>,
98  * <code>context</code>, <code>roles</code>, and <code>components</code>
99  * </dd>.
100  *
101  * <dt>context</dt>
102  * <dd>Allows context properties to be set in the context passed to any
103  * Contextualizable components.</dd>
104  *
105  * <dt>roles</dt>
106  * <dd>Roles configuration for the components configured in the
107  * <code>components</code> element.
108  * </dd>
109  *
110  * <dt>components</dt>
111  * <dd>Used to configure any Components used by the test cases.
112  * </dd>
113  *
114  * </dl>
115  *
116  * @version $Id: $
117  */

118 public class ContainerTestCase extends TestCase {
119
120     /** The default logger */
121     private Logger logger;
122
123     /** The service manager to use */
124     private ServiceManager manager;
125
126     /** Return the logger */
127     protected Logger getLogger() {
128         return logger;
129     }
130
131     /** Return the service manager */
132     protected ServiceManager getManager() {
133         return this.manager;
134     }
135
136     /* (non-Javadoc)
137      * @see junit.framework.TestCase#setUp()
138      */

139     protected void setUp() throws Exception JavaDoc {
140         super.setUp();
141
142         String JavaDoc level = System.getProperty("junit.test.loglevel", "" + ConsoleLogger.LEVEL_WARN);
143         this.logger = new ConsoleLogger(Integer.parseInt(level));
144         Deprecation.setLogger(this.logger);
145         prepare();
146     }
147
148     /**
149      * Initializes the ComponentLocator
150      *
151      * The configuration file is determined by the class name plus .xtest appended,
152      * all '.' replaced by '/' and loaded as a resource via classpath
153      */

154     protected void prepare()
155     throws Exception JavaDoc {
156         final String JavaDoc resourceName = getClass().getName().replace( '.', '/' ) + ".xtest";
157         URL JavaDoc resource = getClass().getClassLoader().getResource( resourceName );
158
159         if (resource != null) {
160             getLogger().debug("Loading resource " + resourceName);
161             prepare(resource.openStream());
162         } else {
163             getLogger().debug("Resource not found " + resourceName);
164         }
165     }
166
167     /**
168      * Initializes the ComponentLocator
169      *
170      * @param testconf The configuration file is passed as a <code>InputStream</code>
171      *
172      * A common way to supply a InputStream is to overwrite the initialize() method
173      * in the sub class, do there whatever is needed to get the right InputStream object
174      * supplying a conformant xtest configuartion and pass it to this initialize method.
175      * the mentioned initialize method is also the place to set a different logging priority
176      * to the member variable m_logPriority.
177      */

178     protected final void prepare(final InputStream JavaDoc testconf)
179     throws Exception JavaDoc {
180         if (getLogger().isDebugEnabled()) {
181             getLogger().debug("ContainerTestCase.initialize");
182         }
183
184         final DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
185         final Configuration conf = builder.build(testconf);
186
187         Context context = this.setupContext(conf.getChild("context"));
188
189         setupManagers(conf.getChild("components"),
190                       conf.getChild("roles"),
191                       context);
192     }
193
194     /* (non-Javadoc)
195      * @see junit.framework.TestCase#tearDown()
196      */

197     protected void tearDown() throws Exception JavaDoc {
198         done();
199         super.tearDown();
200     }
201
202     /**
203      * Disposes the <code>ComponentLocator</code>
204      */

205     final private void done() {
206         if (manager != null) {
207             ContainerUtil.dispose(manager);
208             manager = null;
209         }
210     }
211
212     /**
213      * set up a context according to the xtest configuration specifications context
214      * element.
215      *
216      * A method addContext(DefaultContext context) is called here to enable subclasses
217      * to put additional objects into the context programmatically.
218      */

219     final private Context setupContext( final Configuration conf )
220     throws Exception JavaDoc {
221         final DefaultContext context = new DefaultContext();
222         final Configuration[] confs = conf.getChildren( "entry" );
223         for (int i = 0; i < confs.length; i++) {
224             final String JavaDoc key = confs[i].getAttribute("name");
225             final String JavaDoc value = confs[i].getAttribute("value", null);
226             if (value == null) {
227                 String JavaDoc clazz = confs[i].getAttribute("class");
228                 Object JavaDoc obj = getClass().getClassLoader().loadClass(clazz).newInstance();
229                 context.put(key, obj);
230                 if (getLogger().isInfoEnabled()) {
231                     getLogger().info("ContainerTestCase: added an instance of class " + clazz + " to context entry " + key);
232                 }
233             } else {
234                 context.put(key, value);
235                 if (getLogger().isInfoEnabled()) {
236                     getLogger().info("ContainerTestCase: added value \"" + value + "\" to context entry " + key);
237                 }
238             }
239         }
240         addContext(context);
241         return context ;
242     }
243
244     /**
245      * This method may be overwritten by subclasses to put additional objects
246      * into the context programmatically.
247      */

248     protected void addContext(DefaultContext context) {
249     }
250
251     final private void setupManagers(final Configuration confCM,
252                                      final Configuration confRM,
253                                      final Context context)
254     throws Exception JavaDoc {
255         // Setup the RoleManager
256
DefaultRoleManager roleManager = new DefaultRoleManager();
257         roleManager.enableLogging(getLogger());
258         roleManager.configure(confRM);
259
260         // Set up the ComponentLocator
261
ExcaliburComponentManager ecManager = new ExcaliburComponentManager();
262         ecManager.enableLogging(getLogger());
263         ecManager.contextualize(context);
264         ecManager.setRoleManager(roleManager);
265         ecManager.setLoggerManager(new DefaultLoggerManager(getLogger()));
266         ecManager.configure(confCM);
267         ecManager.initialize();
268         this.manager = new WrapperServiceManager(ecManager);
269     }
270
271     protected final Object JavaDoc lookup(final String JavaDoc key)
272     throws ServiceException {
273         return manager.lookup(key);
274     }
275
276     protected final void release(final Object JavaDoc object) {
277         manager.release(object);
278     }
279
280     protected static class DefaultLoggerManager implements LoggerManager {
281         private Logger logger;
282
283         public DefaultLoggerManager(Logger logger) {
284             this.logger = logger;
285         }
286         /* (non-Javadoc)
287          * @see org.apache.avalon.excalibur.logger.LoggerManager#getDefaultLogger()
288          */

289         public Logger getDefaultLogger() {
290             return this.logger;
291         }
292         /* (non-Javadoc)
293          * @see org.apache.avalon.excalibur.logger.LoggerManager#getLoggerForCategory(java.lang.String)
294          */

295         public Logger getLoggerForCategory(String JavaDoc arg0) {
296             return this.logger;
297         }
298     }
299 }
300
Popular Tags