KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opencms > flex > TestCmsFlexResponse


1 /*
2  * File : $Source: /usr/local/cvs/opencms/test/org/opencms/flex/TestCmsFlexResponse.java,v $
3  * Date : $Date: 2005/09/11 13:27:06 $
4  * Version: $Revision: 1.1 $
5  *
6  * This library is part of OpenCms -
7  * the Open Source Content Mananagement System
8  *
9  * Copyright (c) 2005 Alkacon Software GmbH (http://www.alkacon.com)
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19  * Lesser General Public License for more details.
20  *
21  * For further information about Alkacon Software GmbH, please see the
22  * company website: http://www.alkacon.com
23  *
24  * For further information about OpenCms, please see the
25  * project website: http://www.opencms.org
26  *
27  * You should have received a copy of the GNU Lesser General Public
28  * License along with this library; if not, write to the Free Software
29  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
30  */

31
32 package org.opencms.flex;
33
34 import org.opencms.file.CmsObject;
35 import org.opencms.main.OpenCms;
36 import org.opencms.test.OpenCmsTestCase;
37 import org.opencms.test.OpenCmsTestProperties;
38 import org.opencms.util.CmsRequestUtil;
39
40 import java.lang.reflect.InvocationHandler JavaDoc;
41 import java.lang.reflect.Method JavaDoc;
42 import java.lang.reflect.Proxy JavaDoc;
43 import java.util.ArrayList JavaDoc;
44 import java.util.HashMap JavaDoc;
45 import java.util.List JavaDoc;
46
47 import javax.servlet.http.HttpServletRequest JavaDoc;
48 import javax.servlet.http.HttpServletResponse JavaDoc;
49
50 import junit.extensions.TestSetup;
51 import junit.framework.TestSuite;
52
53 /**
54  * Unit tests for the {@link CmsFlexResponse}.<p>
55  *
56  * This test suite performs way more set-up than is required for the amount of testing that is done.
57  * However, there is probably value in demonstrating how to set up a test case to access flex cache resources
58  * so that more robust unit tests can be developed here.<p>
59  *
60  * @author Jason Trump
61  *
62  * @version $Revision: 1.1 $
63  *
64  * @since 6.0.1
65  */

66 public class TestCmsFlexResponse extends OpenCmsTestCase {
67
68     /**
69      * An InvocationHandler which simply records the arguments for each method that was called.<p>
70      *
71      * If a 'stub' object was passed in the contructor, and the stub object has a method of the
72      * same signature as the one that is being called, that method will be invoked.<p>
73      */

74     public static class RecordingMock implements InvocationHandler JavaDoc {
75
76         /** Maps {@link Method} to a {@link List} of arguments passed to each invocation of that method handled by this object. */
77         HashMap JavaDoc m_invocations = new HashMap JavaDoc();
78         
79         /** If non-null, delegate method invocations to this object when possible. */
80         Object JavaDoc m_stub;
81
82         /**
83          * Default empty construtor.<p>
84          */

85         public RecordingMock() {
86             // noop
87
}
88
89         /**
90          * Construtor with a 'stub' Object.<p>
91          *
92          * @param stub the stub Object to use
93          */

94         public RecordingMock(Object JavaDoc stub) {
95
96             m_stub = stub;
97         }
98
99         /**
100          * Returns a list of all recorded calls to the given method.<p>
101          *
102          * @param method the method to get the recorded calls for
103          *
104          * @return a list of all recorded calls to the given method
105          */

106         public List JavaDoc getCalls(Method JavaDoc method) {
107
108             ArrayList JavaDoc calls = (ArrayList JavaDoc)m_invocations.get(method);
109             if (calls == null) {
110                 calls = new ArrayList JavaDoc();
111                 m_invocations.put(method, calls);
112             }
113             return calls;
114         }
115
116
117         /**
118          * Notice that the given method has been invoked.<p>
119          *
120          * Two actions are taken:
121          * <ol>
122          * <li>The invocation is recorded in <code>{@link #getCalls getCalls(method)}</code>.</li>
123          * <li>If {@link #m_stub} is not null, the requested method is invoked on it</li>
124          * </ol>
125          *
126          * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
127          */

128         public Object JavaDoc invoke(Object JavaDoc proxy, Method JavaDoc method, Object JavaDoc[] args) throws Throwable JavaDoc {
129
130             // record the invocation
131
getCalls(method).add(args);
132             
133             // check to see if our stub object supports this method.
134
if (m_stub != null) {
135                 Method JavaDoc stubMethod = null;
136                 try {
137                     stubMethod = m_stub.getClass().getMethod(method.getName(), method.getParameterTypes());
138                     if (stubMethod != null) {
139                         if (stubMethod.getReturnType() == null) {
140                             if (method.getReturnType() != null) {
141                                 stubMethod = null;
142                             }
143                         } else if (!stubMethod.getReturnType().equals(method.getReturnType())) {
144                             stubMethod = null;
145                         }
146                     }
147                 } catch (NoSuchMethodException JavaDoc e) {
148                     // ignore
149
} catch (SecurityException JavaDoc e) {
150                     // ignore
151
}
152
153                 // if stubMethod is not null, then stub object has a public method with the requested signature
154
if (stubMethod != null) {
155                     return stubMethod.invoke(m_stub, args);
156                 }
157             }
158
159             return null;
160         }
161     }
162     
163     /**
164      * A partial implementation of {@link HttpServletRequest} which allows for the setting and getting of request attributes.<p>
165      */

166     public static class RequestStub {
167
168         /** Attribute map. */
169         HashMap JavaDoc m_attributes = new HashMap JavaDoc();
170
171         /**
172          * Returns the named attribute value.<p>
173          *
174          * @param name the name of the attribute to return
175          * @return the value of the attribute
176          */

177         public Object JavaDoc getAttribute(String JavaDoc name) {
178
179             return m_attributes.get(name);
180         }
181
182         /**
183          * Removes the named attribute.<p>
184          *
185          * @param name the name of the attribute to remove
186          */

187         public void removeAttribute(String JavaDoc name) {
188
189             m_attributes.remove(name);
190         }
191
192         /**
193          * Sets the named attribute to the given value.<p>
194          *
195          * @param name the name of the attribute to set
196          * @param value the value to set
197          */

198         public void setAttribute(String JavaDoc name, Object JavaDoc value) {
199
200             m_attributes.put(name, value);
201         }
202     }
203
204     /** Method for setContentType(String) from the HttpServletResponse class. */
205     public static Method JavaDoc SET_CONTENT_TYPE = null;
206     
207     /** Flex controller to be used by the tests. */
208     private CmsFlexController m_controller;
209     
210     /** Request mockup object. */
211     private RecordingMock m_reqMock;
212     
213     /** Response mockup object. */
214     private RecordingMock m_resMock;
215     
216     /** Servlet request to use with the tests. */
217     private HttpServletRequest JavaDoc m_request;
218
219     /** Servlet response to use with the tests. */
220     private HttpServletResponse JavaDoc m_response;
221
222     /**
223      * Default JUnit constructor.<p>
224      *
225      * @param arg0 JUnit parameters
226      */

227     public TestCmsFlexResponse(String JavaDoc arg0) {
228
229         super(arg0);
230     }
231
232     /**
233      * Static initializer for this test case.<p>
234      */

235     static {
236         try {
237             SET_CONTENT_TYPE = HttpServletResponse JavaDoc.class.getMethod("setContentType", new Class JavaDoc[] {String JavaDoc.class});
238         } catch (NoSuchMethodException JavaDoc e) {
239             throw new RuntimeException JavaDoc("HttpServletResponse linkage error", e);
240         }
241     }
242
243     /**
244      * Test suite for this test class.<p>
245      *
246      * @return the test suite
247      */

248     public static TestSetup suite() {
249
250         OpenCmsTestProperties.initialize(org.opencms.test.AllTests.TEST_PROPERTIES_PATH);
251
252         TestSuite suite = new TestSuite();
253         suite.setName(TestCmsFlexResponse.class.getName());
254
255         suite.addTest(new TestCmsFlexResponse("testContentTypeRules"));
256
257         TestSetup wrapper = new TestSetup(suite) {
258
259             protected void setUp() {
260
261                 setupOpenCms("simpletest", "/sites/default/");
262             }
263
264             protected void tearDown() {
265
266                 removeOpenCms();
267             }
268         };
269
270         return wrapper;
271     }
272
273     /**
274      * Convenience method to create a mock HttpServletRequest backed by the given invocation handler.<p>
275      */

276     private static HttpServletRequest JavaDoc createMockRequest(RecordingMock recorder) {
277
278         return (HttpServletRequest JavaDoc)createProxy(HttpServletRequest JavaDoc.class, recorder);
279     }
280
281     /**
282      * Convenience method to create a mock HttpServletResponse backed by the given invocation handler.<p>
283      */

284     private static HttpServletResponse JavaDoc createMockResponse(RecordingMock recorder) {
285
286         return (HttpServletResponse JavaDoc)createProxy(HttpServletResponse JavaDoc.class, recorder);
287     }
288
289     private static Object JavaDoc createProxy(Class JavaDoc interfaceClass, InvocationHandler JavaDoc handler) {
290
291         return Proxy.newProxyInstance(
292             Thread.currentThread().getContextClassLoader(),
293             new Class JavaDoc[] {interfaceClass},
294             handler);
295     }
296
297     /**
298      * Test semantics for Content-Type header on
299      * {@link CmsFlexResponse#setContentType(String)} and {@link CmsFlexResponse#setHeader(String, String)}.<p>
300      *
301      * @throws Exception if the test fails
302      */

303     public void testContentTypeRules() throws Exception JavaDoc {
304
305         // test that non-top elements won't try to set the content type.
306
CmsFlexResponse f_res = new CmsFlexResponse(m_response, m_controller, false, false);
307         f_res.setHeader(CmsRequestUtil.HEADER_CONTENT_TYPE, "application/borked");
308         assertTrue("non-top request does not set content type header", m_resMock.m_invocations.isEmpty());
309
310         f_res.setContentType("application/stillborked");
311         assertTrue("non-top request does not set content type header", m_resMock.m_invocations.isEmpty());
312
313         // test that top elements only set content type once
314
// first, try with a call to setContentType()
315
f_res = new CmsFlexResponse(m_response, m_controller, false, true);
316         f_res.setContentType("text/foo");
317
318         assertEquals("one method has been invoked on the actual response", 1, m_resMock.m_invocations.size());
319         List JavaDoc setCalls = m_resMock.getCalls(SET_CONTENT_TYPE);
320         assertEquals("top element has called setContentType() on the actual servlet response", 1, setCalls.size());
321         assertEquals("correct content type value passed", "text/foo", ((Object JavaDoc[])setCalls.get(0))[0]);
322
323         // subsequent attempts to set the content type on the same response should have no affect
324
f_res.setContentType("text/bar");
325         assertEquals("top element did NOT call content type method again", 1, setCalls.size());
326
327         f_res.setHeader(CmsRequestUtil.HEADER_CONTENT_TYPE, "text/baz");
328         assertEquals("still no more calls to setContentType() method", 1, setCalls.size());
329         assertEquals("no other methods called on request", 1, m_resMock.m_invocations.size());
330
331         // now, try with a call to setHeader on a new top response
332
f_res = new CmsFlexResponse(m_response, m_controller, false, true);
333         f_res.setHeader(CmsRequestUtil.HEADER_CONTENT_TYPE, "text/qux");
334         assertEquals("setContentType() was called from setHeader", 2, setCalls.size());
335         assertEquals("correct content type value passed", "text/qux", ((Object JavaDoc[])setCalls.get(1))[0]);
336
337         // subsequent attempts to set the content type on the same response should have no affect
338
f_res.setContentType("text/quux");
339         assertEquals("no further calls to setContentType", 2, setCalls.size());
340         assertEquals("no other methods called", 1, m_resMock.m_invocations.size());
341
342         f_res.setHeader(CmsRequestUtil.HEADER_CONTENT_TYPE, "text/arg");
343         assertEquals("no further calls to setContentType", 2, setCalls.size());
344         assertEquals("no other methods called", 1, m_resMock.m_invocations.size());
345     }
346
347     /**
348      * Initializes a flex cache controller and mock servlet request and response objects to be
349      * used by this unit tests.<p>
350      *
351      * @throws Exception if the setup fails
352      *
353      * @see junit.framework.TestCase#setUp()
354      */

355     protected void setUp() throws Exception JavaDoc {
356
357         super.setUp();
358         CmsObject cms = OpenCms.initCmsObject(OpenCms.getDefaultUsers().getUserGuest());
359         if (!cms.getRequestContext().currentUser().getName().equals(OpenCms.getDefaultUsers().getUserGuest())) {
360             fail("'Guest' user could not be properly initialized!");
361         }
362
363         m_reqMock = new RecordingMock(new RequestStub());
364         m_request = createMockRequest(m_reqMock);
365         m_resMock = new RecordingMock();
366         m_response = createMockResponse(m_resMock);
367
368         m_controller = new CmsFlexController(cms, null, CmsFlexDummyLoader.m_flexCache, m_request, m_response, false, true);
369         CmsFlexController.setController(m_request, m_controller);
370     }
371
372     /**
373      * @see junit.framework.TestCase#tearDown()
374      */

375     protected void tearDown() throws Exception JavaDoc {
376
377         super.tearDown();
378         m_reqMock = null;
379         m_resMock = null;
380         m_request = null;
381         m_response = null;
382         m_controller = null;
383     }
384 }
Popular Tags