View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  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,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.myfaces.renderkit.html.util;
20  
21  import junit.framework.TestCase;
22  import org.apache.myfaces.application.ApplicationFactoryImpl;
23  import org.apache.myfaces.context.servlet.ServletFacesContextImpl;
24  import org.apache.myfaces.renderkit.RenderKitFactoryImpl;
25  import org.apache.myfaces.shared_tomahawk.renderkit.html.HtmlResponseWriterImpl;
26  import org.easymock.MockControl;
27  
28  import javax.faces.FactoryFinder;
29  import javax.faces.context.FacesContext;
30  import javax.faces.context.ResponseWriter;
31  import javax.servlet.http.HttpServletRequest;
32  import javax.servlet.http.HttpServletResponse;
33  import java.io.IOException;
34  import java.io.PrintWriter;
35  import java.io.StringWriter;
36  import java.io.Writer;
37  import java.util.Map;
38  import java.util.LinkedHashMap;
39  
40  /**
41   * Unit test for the AddResource class which can output script, style and inline
42   * javascript into the header or body of an HTML response page.
43   */
44  public class AddResourceTest extends TestCase
45  {
46      public void testGetInstance()
47      {
48  
49         Map cacheMap = new LinkedHashMap();
50  
51          AddResource instance1 = AddResourceFactory.getInstance(null,cacheMap, "/test1", null);
52          assertNotNull(instance1);
53  
54          /* no longer true
55          AddResource instance2 = AddResourceFactory.getInstance(null, "/test2", null);
56          assertNotSame(instance1, instance2);
57          */
58  
59          AddResourceFactory.getInstance(null,cacheMap, "/test1", null);
60      }
61  
62      public void setUp()
63      {
64          // Make sure a FacesContext configured from some previous test case
65          // doesn't interfere with the test case we are about to run...
66          FacesContextHelper.setCurrentInstance(null);
67      }
68  
69      public void tearDown()
70      {
71          // Make sure a FacesContext we may have configured in the test case
72          // just completed doesn't interfere with test cases run later.
73          FacesContextHelper.setCurrentInstance(null);
74      }
75  
76      /**
77       * Simple test helper class to allow unit tests to configure
78       * mock FacesContext objects as the "current instance".
79       * <p>
80       * The method FacesContext.setCurrentInstance is protected, and
81       * hence cannot be accessed by unit tests wanting to configure
82       * a mock object as the value seen by code calling method
83       * FacesContext.getCurrentInstance().
84       */
85      private static abstract class FacesContextHelper extends FacesContext
86      {
87          public static void setCurrentInstance(FacesContext other)
88          {
89              FacesContext.setCurrentInstance(other);
90          }
91      }
92  
93      /**
94       * Configure a fake JSF environment for a test, consisting of a
95       * FacesContext and dependent objects.
96       * <p>
97       * EasyMock control objects are used to emulate the necessary bits.
98       */
99      private static class MockState
100     {
101         Writer _writer;
102         ResponseWriter _htmlResponseWriter;
103         MockControl _servletRequestControl;
104         HttpServletRequest _servletRequest;
105         MockControl _servletResponseControl;
106         HttpServletResponse _servletResponse;
107         FacesContext _facesContext;
108 
109         public void setup() throws IOException
110         {
111             // set up a writer object to be the "response" output stream.
112             _writer = new StringWriter();
113             String contentType = "text/html";
114             String charEncoding = "UTF-8";
115             _htmlResponseWriter = new HtmlResponseWriterImpl(_writer, contentType, charEncoding);
116 
117             // Mock ServletRequest object that:
118             // * returns "/test" for context path
119             // * returns "/test/foo.jsp" for servlet path
120             // * returns "null" for getPathInfo
121             // * returns "null" for getHeader
122             // * returns "null" for getAttribute
123             // * returns null for getSession
124             _servletRequestControl = MockControl.createControl(HttpServletRequest.class);
125             _servletRequest = (HttpServletRequest) _servletRequestControl.getMock();
126             _servletRequest.getContextPath();
127             _servletRequestControl.setReturnValue("/test", MockControl.ZERO_OR_MORE);
128             _servletRequest.getServletPath();
129             _servletRequestControl.setReturnValue("/test/foo.jsp", MockControl.ZERO_OR_MORE);
130             _servletRequest.getPathInfo();
131             _servletRequestControl.setReturnValue("", MockControl.ZERO_OR_MORE);
132             _servletRequest.getHeader("");
133             _servletRequestControl.setMatcher(MockControl.ALWAYS_MATCHER);
134             _servletRequestControl.setReturnValue(null, MockControl.ZERO_OR_MORE);
135             _servletRequest.getAttribute("");
136             _servletRequestControl.setMatcher(MockControl.ALWAYS_MATCHER);
137             _servletRequestControl.setReturnValue(null, MockControl.ZERO_OR_MORE);
138             _servletRequest.setAttribute("", "");
139             _servletRequestControl.setMatcher(MockControl.ALWAYS_MATCHER);
140             _servletRequestControl.setVoidCallable(MockControl.ZERO_OR_MORE);
141             _servletRequest.getSession(false);
142             _servletRequestControl.setReturnValue(null, MockControl.ZERO_OR_MORE);
143             _servletRequestControl.replay();
144 
145             // Mock ServletResponse object that:
146             // * returns appropriate encoded URLs
147             // * returns a PrintWriter wrapping this object's writer member for
148             //   calls to getWriter
149             _servletResponseControl = MockControl.createControl(HttpServletResponse.class);
150             _servletResponse = (HttpServletResponse) _servletResponseControl.getMock();
151             _servletResponse.encodeURL("/test/scripts/script1");
152             _servletResponseControl.setReturnValue("encoded(/test/scripts/script1)", MockControl.ZERO_OR_MORE);
153             _servletResponse.getWriter();
154             _servletResponseControl.setReturnValue(new PrintWriter(_writer), MockControl.ZERO_OR_MORE);
155             _servletResponse.getCharacterEncoding();
156             _servletResponseControl.setReturnValue("UTF-8", MockControl.ZERO_OR_MORE);
157             _servletResponseControl.replay();
158 
159             // The FacesContext needs FactoryFinder configured.
160             FactoryFinder.setFactory(FactoryFinder.APPLICATION_FACTORY, ApplicationFactoryImpl.class.getName());
161             FactoryFinder.setFactory(FactoryFinder.RENDER_KIT_FACTORY, RenderKitFactoryImpl.class.getName());
162 
163             // Now create a FacesContext....
164             _facesContext = new ServletFacesContextImpl(null,
165                     _servletRequest, _servletResponse);
166             _facesContext.setResponseWriter(_htmlResponseWriter);
167         }
168 
169         public void verifyControls()
170         {
171             _servletRequestControl.verify();
172             _servletResponseControl.verify();
173         }
174     }
175 
176     public void testAddJavaScriptHere() throws IOException
177     {
178         MockState mockState = new MockState();
179         mockState.setup();
180 
181         // now start the test
182         AddResource instance1 = AddResourceFactory.getInstance(null,null,"/test", null);
183         instance1.addJavaScriptHere(mockState._facesContext, "/scripts/script1");
184 
185         // verify that our mock objects got the expected callbacks
186         mockState.verifyControls();
187 
188         // verify that:
189         // *script tag is output
190         // * type attribute is right,
191         // * URL has context path prepended to it
192         // * URL has been encoded
193         // * HTML comments have been used to hide script from non-script-aware
194         //   browsers.
195         //
196         // NOTE: are comments required to hide this script from browsers when
197         // there isn't any script body content (just a src attr)?
198         assertEquals(
199             "<script type=\"text/javascript\""
200             + " src=\"encoded(/test/scripts/script1)\">"
201             + "<!--\n\n//--></script>",
202             mockState._writer.toString());
203     }
204 
205     public void testWriteWithFullHeader() throws IOException
206     {
207         MockState mockState = new MockState();
208         mockState.setup();
209 
210         String originalResponse =
211             "<html><head></head><body></body></html>";
212 
213         AddResource ar = AddResourceFactory.getInstance(null,null,"/test", null);
214         ar.parseResponse(mockState._servletRequest,originalResponse,mockState._servletResponse);
215         ar.writeWithFullHeader(mockState._servletRequest,mockState._servletResponse);
216         ar.writeResponse(mockState._servletRequest,mockState._servletResponse);
217 
218         mockState.verifyControls();
219 
220         System.out.println(mockState._writer.toString());
221         assertEquals(originalResponse, mockState._writer.toString());
222     }
223 }