View Javadoc
1   package org.apache.fulcrum.upload;
2   
3   import static org.junit.jupiter.api.Assertions.assertEquals;
4   import static org.junit.jupiter.api.Assertions.assertNotNull;
5   import static org.junit.jupiter.api.Assertions.assertTrue;
6   import static org.junit.jupiter.api.Assertions.fail;
7   import static org.mockito.ArgumentMatchers.any;
8   import static org.mockito.ArgumentMatchers.anyInt;
9   import static org.mockito.ArgumentMatchers.anyString;
10  import static org.mockito.Mockito.doAnswer;
11  import static org.mockito.Mockito.mock;
12  import static org.mockito.Mockito.when;
13  
14  import java.io.ByteArrayInputStream;
15  
16  /*
17   * Licensed to the Apache Software Foundation (ASF) under one
18   * or more contributor license agreements.  See the NOTICE file
19   * distributed with this work for additional information
20   * regarding copyright ownership.  The ASF licenses this file
21   * to you under the Apache License, Version 2.0 (the
22   * "License"); you may not use this file except in compliance
23   * with the License.  You may obtain a copy of the License at
24   *
25   *   http://www.apache.org/licenses/LICENSE-2.0
26   *
27   * Unless required by applicable law or agreed to in writing,
28   * software distributed under the License is distributed on an
29   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
30   * KIND, either express or implied.  See the License for the
31   * specific language governing permissions and limitations
32   * under the License.
33   */
34  
35  
36  import java.io.File;
37  import java.io.IOException;
38  import java.util.HashMap;
39  import java.util.List;
40  import java.util.Locale;
41  import java.util.Map;
42  import java.util.Vector;
43  
44  import javax.servlet.ReadListener;
45  import javax.servlet.ServletInputStream;
46  import javax.servlet.http.HttpServletRequest;
47  import javax.servlet.http.HttpSession;
48  
49  import org.apache.avalon.framework.component.ComponentException;
50  import org.apache.commons.fileupload.FileItem;
51  import org.apache.commons.fileupload.FileItemIterator;
52  import org.apache.fulcrum.testcontainer.BaseUnit5Test;
53  import org.junit.jupiter.api.BeforeEach;
54  import org.junit.jupiter.api.Test;
55  import org.mockito.invocation.InvocationOnMock;
56  import org.mockito.stubbing.Answer;
57  /**
58   * UploadServiceTest
59   *
60   * @author <a href="epugh@upstate.com">Eric Pugh</a>
61   * @version $Id$
62   */
63  public class UploadServiceTest extends BaseUnit5Test
64  {
65      private UploadService uploadService = null;
66  
67  
68      @BeforeEach
69      public void setUp() throws Exception
70      {
71          try
72          {
73              uploadService = (UploadService) this.lookup(UploadService.ROLE);
74          }
75          catch (ComponentException e)
76          {
77              e.printStackTrace();
78              fail(e.getMessage());
79          }
80      }
81      /**
82       * Simple test that verify an object can be created and deleted.
83       * @throws Exception
84       */
85      @Test
86      public void testRepositoryExists() throws Exception
87      {
88          File f = new File(uploadService.getRepository());
89          assertTrue(f.exists());
90      }
91      
92      // This is Apache Commons, but we want to make be really sure it runs clean in Fulcrum
93      @Test
94      public void testUploadEncoding() throws Exception {
95          HttpServletRequest request = getMockRequest();
96          when(request.getContentType()).thenReturn("multipart/form-data; boundary=boundary");
97          when(request.getContentLength()).thenReturn(-1);// -1
98          when(request.getMethod()).thenReturn("post");
99          String testData= "Überfülle=\r\nf";
100         //override default settings
101         requestFormData( request, testData );
102         assertTrue(uploadService.isMultipart( request ));
103         List<FileItem> fil = uploadService.parseRequest( request );
104         assertNotNull(fil);
105         assertTrue( fil.size() >0);
106         FileItem fi = fil.get( 0 );
107         System.out.println( fi.getString() );
108         assertEquals(15,fi.getSize());
109         // default is ISO-8859-1
110         assertTrue( fi.getString("UTF-8").startsWith( "Überfülle" ), "data string:'" +fi.getString("UTF-8") +"' not as expected");
111         
112         //reset inputstream
113         requestFormData( request, testData);
114         FileItemIterator fii = uploadService.getItemIterator( request );
115         assertNotNull(fii);
116         assertTrue( fii.hasNext());
117         assertNotNull(fii.next());
118     }
119 
120     private void requestFormData( HttpServletRequest request, String data)
121         throws IOException
122     {
123         String example ="--boundary\r\n"
124             + "Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"12345678.txt\"\r\n"
125             + "Content-Type: text/plain\r\n"
126 //            + "Content-Transfer-Encoding: UTF-8\r\n"
127             + "\r\n"
128             + data 
129             + "\r\n--boundary--\r\n";
130         final ByteArrayInputStream is = new ByteArrayInputStream (example.getBytes());// "UTF-8"
131         when(request.getInputStream()).thenReturn(new ServletInputStream() {
132                 @Override
133                 public int read() throws IOException {
134                     return is.read();
135                 }
136 
137 				@Override
138 				public boolean isFinished() {
139 					// TODO Auto-generated method stub
140 					return false;
141 				}
142 
143 				@Override
144 				public boolean isReady() {
145 					// TODO Auto-generated method stub
146 					return false;
147 				}
148 
149 				@Override
150 				public void setReadListener(ReadListener readListener) {
151 					// TODO Auto-generated method stub
152 					
153 				}
154             });
155     }
156     
157     protected Map<String,Object> attributes = new HashMap<String,Object>();
158     protected int maxInactiveInterval = 0;
159     // from Turbine org.apache.turbine.test.BaseTestCase, should be later in Fulcrum Testcontainer BaseUnit4Test
160     protected HttpServletRequest getMockRequest()
161     {
162         HttpServletRequest request = mock(HttpServletRequest.class);
163         HttpSession session = mock(HttpSession.class);
164 
165         doAnswer(new Answer<Object>()
166         {
167             @Override
168             public Object answer(InvocationOnMock invocation) throws Throwable
169             {
170                 String key = (String) invocation.getArguments()[0];
171                 return attributes.get(key);
172             }
173         }).when(session).getAttribute(anyString());
174 
175         doAnswer(new Answer<Object>()
176         {
177             @Override
178             public Object answer(InvocationOnMock invocation) throws Throwable
179             {
180                 String key = (String) invocation.getArguments()[0];
181                 Object value = invocation.getArguments()[1];
182                 attributes.put(key, value);
183                 return null;
184             }
185         }).when(session).setAttribute(anyString(), any());
186 
187         when(session.getMaxInactiveInterval()).thenReturn(maxInactiveInterval);
188 
189         doAnswer(new Answer<Integer>()
190         {
191             @Override
192             public Integer answer(InvocationOnMock invocation) throws Throwable
193             {
194                 return Integer.valueOf(maxInactiveInterval);
195             }
196         }).when(session).getMaxInactiveInterval();
197 
198         doAnswer(new Answer<Object>()
199         {
200             @Override
201             public Object answer(InvocationOnMock invocation) throws Throwable
202             {
203                 Integer value = (Integer) invocation.getArguments()[0];
204                 maxInactiveInterval = value.intValue();
205                 return null;
206             }
207         }).when(session).setMaxInactiveInterval(anyInt());
208 
209         when(session.isNew()).thenReturn(true);
210         when(request.getSession()).thenReturn(session);
211 
212         when(request.getServerName()).thenReturn("bob");
213         when(request.getProtocol()).thenReturn("http");
214         when(request.getScheme()).thenReturn("scheme");
215         when(request.getPathInfo()).thenReturn("damn");
216         when(request.getServletPath()).thenReturn("damn2");
217         when(request.getContextPath()).thenReturn("wow");
218         when(request.getContentType()).thenReturn("html/text");
219 
220         when(request.getCharacterEncoding()).thenReturn("UTF-8");
221         when(request.getServerPort()).thenReturn(8080);
222         when(request.getLocale()).thenReturn(Locale.US);
223 
224         when(request.getHeader("Content-type")).thenReturn("html/text");
225         when(request.getHeader("Accept-Language")).thenReturn("en-US");
226 
227         Vector<String> v = new Vector<String>();
228         when(request.getParameterNames()).thenReturn(v.elements());
229         return request;
230     }
231 }