View Javadoc

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