View Javadoc

1   /*
2    * $Id: Jsr168DispatcherTest.java 451544 2006-09-30 05:38:02Z mrdon $
3    *
4    * Copyright 2006 The Apache Software Foundation.
5    *
6    * Licensed under the Apache License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    *
10   *      http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.struts2.portlet.dispatcher;
19  
20  import java.util.Collections;
21  import java.util.HashMap;
22  import java.util.Iterator;
23  import java.util.ListResourceBundle;
24  import java.util.Locale;
25  import java.util.Map;
26  
27  import javax.portlet.ActionRequest;
28  import javax.portlet.ActionResponse;
29  import javax.portlet.PortletConfig;
30  import javax.portlet.PortletContext;
31  import javax.portlet.PortletMode;
32  import javax.portlet.PortletSession;
33  import javax.portlet.RenderRequest;
34  import javax.portlet.RenderResponse;
35  import javax.portlet.WindowState;
36  import javax.servlet.ServletContext;
37  import javax.servlet.ServletContextEvent;
38  
39  import junit.textui.TestRunner;
40  
41  import org.apache.struts2.portlet.PortletActionConstants;
42  import org.apache.struts2.portlet.context.ServletContextHolderListener;
43  import org.jmock.Mock;
44  import org.jmock.cglib.MockObjectTestCase;
45  import org.jmock.core.Constraint;
46  
47  import com.opensymphony.xwork2.Action;
48  import com.opensymphony.xwork2.ActionInvocation;
49  import com.opensymphony.xwork2.ActionProxy;
50  import com.opensymphony.xwork2.ActionProxyFactory;
51  import com.opensymphony.xwork2.config.Configuration;
52  import com.opensymphony.xwork2.util.ValueStack;
53  import com.opensymphony.xwork2.util.ValueStackFactory;
54  
55  /***
56   * Jsr168DispatcherTest. Insert description.
57   * 
58   */
59  public class Jsr168DispatcherTest extends MockObjectTestCase implements PortletActionConstants {
60   
61      Jsr168Dispatcher dispatcher = null;
62      Mock mockConfig = null;
63      Mock mockCtx = null;
64      Mock mockRequest = null;
65      Mock mockSession = null;
66      Mock mockActionFactory = null;
67      Mock mockActionProxy = null;
68      Mock mockAction = null;
69      Mock mockInvocation = null;
70      
71      public void setUp() {
72          dispatcher = new Jsr168Dispatcher();
73      }
74      
75      private void initPortletConfig(final Map initParams, final Map attributes) {
76          mockConfig = mock(PortletConfig.class);
77          mockCtx = mock(PortletContext.class);
78          mockConfig.stubs().method(ANYTHING);
79          setupStub(initParams, mockConfig, "getInitParameter");
80          mockCtx.stubs().method("getAttributeNames").will(returnValue(Collections.enumeration(attributes.keySet())));
81          setupStub(attributes, mockCtx, "getAttribute");
82          mockConfig.stubs().method("getPortletContext").will(returnValue(mockCtx.proxy()));
83          mockCtx.stubs().method("getInitParameterNames").will(returnValue(Collections.enumeration(initParams.keySet())));
84          setupStub(initParams, mockCtx, "getInitParameter");
85          
86          mockConfig.stubs().method("getResourceBundle").will(returnValue(new ListResourceBundle() {
87              protected Object[][] getContents() {
88                  return new String[][]{{"javax.portlet.title", "MyTitle"}};
89              }
90          }));
91      }
92  
93      private void setupActionFactory(String namespace, String actionName, String result, ValueStack stack) {
94          if(mockActionFactory == null) {
95              mockActionFactory = mock(ActionProxyFactory.class);
96          }
97          mockAction = mock(Action.class);
98          mockActionProxy = mock(ActionProxy.class);
99          mockInvocation = mock(ActionInvocation.class);
100         
101         mockActionFactory.expects(once()).method("createActionProxy").with(new Constraint[]{isA(Configuration.class), eq(namespace), eq(actionName), isA(Map.class)}).will(returnValue(mockActionProxy.proxy()));
102         mockActionProxy.stubs().method("getAction").will(returnValue(mockAction.proxy()));
103         mockActionProxy.expects(once()).method("execute").will(returnValue(result));
104         mockActionProxy.expects(once()).method("getInvocation").will(returnValue(mockInvocation.proxy()));
105         mockInvocation.stubs().method("getStack").will(returnValue(stack));
106     	
107     }
108 
109     public void testRender_ok() {
110         final Mock mockResponse = mock(RenderResponse.class);
111         mockResponse.stubs().method(ANYTHING);
112         final Mock servletContext = mock(ServletContext.class);
113         servletContext.stubs().method(ANYTHING);
114         ServletContextEvent event = new ServletContextEvent((ServletContext)servletContext.proxy());
115         new ServletContextHolderListener().contextInitialized(event);
116         PortletMode mode = PortletMode.VIEW;
117 
118         Map requestParams = new HashMap();
119         requestParams.put(PortletActionConstants.ACTION_PARAM, new String[]{"/view/testAction"});
120         requestParams.put(EVENT_ACTION, new String[]{"true"});
121         requestParams.put(PortletActionConstants.MODE_PARAM, new String[]{mode.toString()});
122         
123         Map sessionMap = new HashMap();
124         
125         
126         
127         Map initParams = new HashMap();
128         initParams.put("viewNamespace", "/view");
129 
130         initPortletConfig(initParams, new HashMap());
131         initRequest(requestParams, new HashMap(), sessionMap, new HashMap(), PortletMode.VIEW, WindowState.NORMAL, false, null);
132         setupActionFactory("/view", "testAction", "success", ValueStackFactory.getFactory().createValueStack());
133 
134         mockInvocation.expects(once()).method("getStack").will(
135                 returnValue(null));
136         //mockSession.expects(once()).method("setAttribute").with(new Constraint[]{eq(PortletActionConstants.LAST_MODE), eq(PortletMode.VIEW)});
137         try {
138             dispatcher
139                     .setActionProxyFactory((ActionProxyFactory) mockActionFactory
140                             .proxy());
141             dispatcher.init((PortletConfig) mockConfig.proxy());
142             dispatcher.render((RenderRequest) mockRequest.proxy(),
143                     (RenderResponse) mockResponse.proxy());
144         } catch (Exception e) {
145             e.printStackTrace();
146             fail("Error occured");
147         }
148     }
149 
150     public void testProcessAction_ok() {
151         final Mock mockResponse = mock(ActionResponse.class);
152 
153         PortletMode mode = PortletMode.VIEW;
154         Map initParams = new HashMap();
155         initParams.put("viewNamespace", "/view");
156         
157         Map requestParams = new HashMap();
158         requestParams.put(PortletActionConstants.ACTION_PARAM, new String[]{"/view/testAction"});
159         requestParams.put(PortletActionConstants.MODE_PARAM, new String[]{mode.toString()});
160         
161         initPortletConfig(initParams, new HashMap());
162         initRequest(requestParams, new HashMap(), new HashMap(), new HashMap(), PortletMode.VIEW, WindowState.NORMAL, true, null);
163         setupActionFactory("/view", "testAction", "success", ValueStackFactory.getFactory().createValueStack());
164         Constraint[] paramConstraints = new Constraint[] {
165                 eq(PortletActionConstants.EVENT_ACTION), same(mockActionProxy.proxy()) };
166 
167         mockSession.expects(once()).method("setAttribute").with(
168                 paramConstraints);
169 
170         mockResponse.expects(once()).method("setRenderParameter").with(
171                 new Constraint[] { eq(PortletActionConstants.EVENT_ACTION),
172                         eq("true") });
173 
174         //mockSession.expects(once()).method("setAttribute").with(new Constraint[]{eq(PortletActionConstants.LAST_MODE), eq(PortletMode.VIEW)});
175         try {
176             dispatcher
177                     .setActionProxyFactory((ActionProxyFactory) mockActionFactory
178                             .proxy());
179             dispatcher.init((PortletConfig) mockConfig.proxy());
180             dispatcher.processAction((ActionRequest) mockRequest.proxy(),
181                     (ActionResponse) mockResponse.proxy());
182         } catch (Exception e) {
183             e.printStackTrace();
184             fail("Error occured");
185         }
186     }
187     
188     /***
189      * Initialize the mock request (and as a result, the mock session)
190      * @param requestParams The request parameters
191      * @param requestAttributes The request attributes
192      * @param sessionParams The session attributes
193      * @param renderParams The render parameters. Will only be set if <code>isEvent</code> is <code>true</code>
194      * @param mode The portlet mode
195      * @param state The portlet window state
196      * @param isEvent <code>true</code> when the request is an ActionRequest.
197      * @param locale The locale. If <code>null</code>, the request will return <code>Locale.getDefault()</code>
198      */
199     private void initRequest(Map requestParams, Map requestAttributes, Map sessionParams, Map renderParams, PortletMode mode, WindowState state, boolean isEvent, Locale locale) {
200     	mockRequest = isEvent ? mock(ActionRequest.class) : mock(RenderRequest.class);
201     	mockSession = mock(PortletSession.class);
202     	mockSession.stubs().method(ANYTHING);
203     	mockRequest.stubs().method(ANYTHING);
204     	setupStub(sessionParams, mockSession, "getAttribute");
205     	mockSession.stubs().method("getAttributeNames").will(returnValue(Collections.enumeration(sessionParams.keySet())));
206     	setupParamStub(requestParams, mockRequest, "getParameter");
207     	setupStub(requestAttributes, mockRequest, "getAttribute");
208     	mockRequest.stubs().method("getAttributeNames").will(returnValue(Collections.enumeration(requestAttributes.keySet())));
209     	mockRequest.stubs().method("getParameterMap").will(returnValue(requestParams));
210     	mockRequest.stubs().method("getParameterNames").will(returnValue(Collections.enumeration(requestParams.keySet())));
211     	mockRequest.stubs().method("getPortletSession").will(returnValue(mockSession.proxy()));
212     	if(locale != null) {
213     		mockRequest.stubs().method("getLocale").will(returnValue(locale));
214     	}
215     	else {
216     		mockRequest.stubs().method("getLocale").will(returnValue(Locale.getDefault()));
217     	}
218     	mockRequest.stubs().method("getPortletMode").will(returnValue(mode));
219     	mockRequest.stubs().method("getWindowState").will(returnValue(state));
220     }
221     
222     /***
223      * @param requestParams
224      * @param mockRequest2
225      * @param string
226      */
227     private void setupParamStub(Map requestParams, Mock mockRequest, String method) {
228         Map newMap = new HashMap();
229         Iterator it = requestParams.keySet().iterator();
230         while(it.hasNext()) {
231             Object key = it.next();
232             String[] val = (String[])requestParams.get(key);
233             newMap.put(key, val[0]);
234         }
235         setupStub(newMap, mockRequest, method);
236         
237     }
238 
239     /***
240      * Set up stubs for the mock.
241      * @param map The map containing the <code>key</code> and <code>values</code>. The key is the 
242      * expected parameter to <code>method</code>, and value is the value that should be returned from
243      * the stub.
244      * @param mock The mock to initialize.
245      * @param method The name of the method to stub.
246      */
247     private void setupStub(Map map, Mock mock, String method) {
248     	Iterator it = map.keySet().iterator();
249     	while(it.hasNext()) {
250     		Object key = it.next();
251     		Object val = map.get(key);
252     		mock.stubs().method(method).with(eq(key)).will(returnValue(val));
253     	}
254     }
255     
256     public void testModeChangeUsingPortletWidgets() {
257         final Mock mockResponse = mock(RenderResponse.class);
258         mockResponse.stubs().method(ANYTHING);
259         PortletMode mode = PortletMode.EDIT;
260 
261         Map requestParams = new HashMap();
262         requestParams.put(PortletActionConstants.ACTION_PARAM, new String[]{"/view/testAction"});
263         requestParams.put(EVENT_ACTION, new String[]{"false"});
264         requestParams.put(PortletActionConstants.MODE_PARAM, new String[]{PortletMode.VIEW.toString()});
265         
266         Map sessionMap = new HashMap();
267         
268         Map initParams = new HashMap();
269         initParams.put("viewNamespace", "/view");
270         initParams.put("editNamespace", "/edit");
271 
272         initPortletConfig(initParams, new HashMap());
273         initRequest(requestParams, new HashMap(), sessionMap, new HashMap(), mode, WindowState.NORMAL, false, null);
274         setupActionFactory("/edit", "default", "success", ValueStackFactory.getFactory().createValueStack());
275 
276         mockInvocation.expects(once()).method("getStack").will(
277                 returnValue(null));
278         //mockSession.expects(once()).method("setAttribute").with(new Constraint[]{eq(PortletActionConstants.LAST_MODE), eq(PortletMode.VIEW)});
279         try {
280             dispatcher
281                     .setActionProxyFactory((ActionProxyFactory) mockActionFactory
282                             .proxy());
283             dispatcher.init((PortletConfig) mockConfig.proxy());
284             dispatcher.render((RenderRequest) mockRequest.proxy(),
285                     (RenderResponse) mockResponse.proxy());
286         } catch (Exception e) {
287             e.printStackTrace();
288             fail("Error occured");
289         }
290     }
291     
292     public static void main(String[] args) {
293     	TestRunner.run(Jsr168DispatcherTest.class);
294     }
295 
296 }