View Javadoc
1   /**
2    * Copyright 2004-2014 The Kuali Foundation
3    *
4    * Licensed under the Educational Community License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.opensource.org/licenses/ecl2.php
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.kuali.hr;
17  
18  import java.io.File;
19  import java.util.ArrayList;
20  import java.util.Arrays;
21  import java.util.List;
22  
23  import org.apache.log4j.Logger;
24  import org.kuali.kpme.core.rice.test.lifecycles.KPMEXmlDataLoaderLifecycle;
25  import org.kuali.kpme.core.util.ClearDatabaseLifecycle;
26  import org.kuali.kpme.core.util.DatabaseCleanupDataLifecycle;
27  import org.kuali.kpme.core.util.HrContext;
28  import org.kuali.kpme.core.util.LoadDatabaseDataLifeCycle;
29  import org.kuali.rice.core.api.config.property.Config;
30  import org.kuali.rice.core.api.config.property.ConfigContext;
31  import org.kuali.rice.core.api.lifecycle.BaseLifecycle;
32  import org.kuali.rice.core.api.lifecycle.Lifecycle;
33  import org.kuali.rice.core.impl.services.CoreImplServiceLocator;
34  import org.kuali.rice.krad.UserSession;
35  import org.kuali.rice.krad.util.GlobalVariables;
36  import org.kuali.rice.krad.util.MessageMap;
37  import org.kuali.rice.test.RiceInternalSuiteDataTestCase;
38  import org.kuali.rice.test.TransactionalLifecycle;
39  import org.kuali.rice.test.lifecycles.JettyServerLifecycle;
40  import org.kuali.rice.test.lifecycles.JettyServerLifecycle.ConfigMode;
41  import org.springframework.cache.CacheManager;
42  
43  import com.gargoylesoftware.htmlunit.BrowserVersion;
44  import com.gargoylesoftware.htmlunit.WebClient;
45  
46  /**
47   *  Default test base for a full KPME unit test.
48   */
49  public abstract class KPMEWebTestCase extends RiceInternalSuiteDataTestCase {
50  
51  	private static final String FILE_PREFIX = System.getProperty("user.dir") + "/../db/src/main/resources/org/kuali/kpme/kpme-db/workflow/";
52  
53  	private static final String RELATIVE_WEBAPP_ROOT = "/src/main/webapp";
54  	
55  	private TransactionalLifecycle transactionalLifecycle;
56      private WebClient webClient;
57  	
58  	@Override
59  	protected String getModuleName() {
60  		return "kpme";
61  	}
62  
63  	@Override
64  	public void setUp() throws Exception {
65  	    if (System.getProperty("basedir") == null) {
66  	        System.setProperty("basedir", System.getProperty("user.dir") + "/");
67  	    }
68  	    
69  		super.setUp();
70  
71  		GlobalVariables.setMessageMap(new MessageMap());
72  		
73  		final boolean needsSpring = false;
74  		if (needsSpring) {
75  			transactionalLifecycle = new TransactionalLifecycle();
76  			//transactionalLifecycle.setTransactionManager(KRADServiceLocatorInternal.getTransactionManager());
77  			transactionalLifecycle.start();
78  		}
79  
80  	    new ClearDatabaseLifecycle().start();
81  	
82  		new LoadDatabaseDataLifeCycle(this.getClass()).start();
83  	
84  	    //lets try to create a user session
85  	    GlobalVariables.setUserSession(new UserSession("admin"));
86          setWebClient(new WebClient(BrowserVersion.FIREFOX_17));
87          getWebClient().getOptions().setJavaScriptEnabled(true);
88          getWebClient().getOptions().setTimeout(0);
89  	}
90  	
91  	@Override
92  	public void tearDown() throws Exception {
93  	    // runs custom SQL at the end of each test.
94  	    // useful for difficult to reset test additions, not handled by
95  	    // our ClearDatabaseLifecycle.
96          HrContext.clearTargetUser();
97          getWebClient().closeAllWindows();
98  	    new DatabaseCleanupDataLifecycle(this.getClass()).start();
99  
100 		final boolean needsSpring = true;
101 		if (needsSpring) {
102 		    if ( (transactionalLifecycle != null) && (transactionalLifecycle.isStarted()) ) {
103 		        transactionalLifecycle.stop();
104 		    }
105 		}
106 		
107 		GlobalVariables.setMessageMap(new MessageMap());
108 		
109 		super.tearDown();
110 	}
111 
112     @Override
113     protected List<Lifecycle> getPerTestLifecycles() {
114         List<Lifecycle> lifecycles = super.getPerTestLifecycles();
115         lifecycles.add(new ClearCacheLifecycle());
116         return lifecycles;
117     }
118 
119 	@Override
120 	protected List<Lifecycle> getSuiteLifecycles() {
121 		List<Lifecycle> lifecycles = super.getPerTestLifecycles();
122 	    lifecycles.add(new Lifecycle() {
123 			boolean started = false;
124 	
125 			public boolean isStarted() {
126 				return this.started;
127 			}
128 	
129 			public void start() throws Exception {
130 				setModuleName(getModuleName());
131 				setBaseDirSystemProperty(getModuleName());
132 				Config config = getTestHarnessConfig();
133 				ConfigContext.init(config);
134 				this.started = true;
135 			}
136 	
137 			public void stop() throws Exception {
138 				this.started = false;
139 			}
140 		});
141 	    /**
142 	     * Loads the TestHarnessSpringBeans.xml file which obtains connections to the DB for us
143 	     */
144 /*	    lifecycles.add(getTestHarnessSpringResourceLoader());*/
145 	
146 	    /**
147 	     * Establishes the TestHarnessServiceLocator so that it has a reference to the Spring context
148 	     * created from TestHarnessSpringBeans.xml
149 	     */
150 /*	    lifecycles.add(new BaseLifecycle() {
151 	        @Override
152 	        public void start() throws Exception {
153 	            TestHarnessServiceLocator.setContext(getTestHarnessSpringResourceLoader().getContext());
154 	            super.start();
155 	        }
156 	    });*/
157 	
158 	    lifecycles.add(new Lifecycle() {
159 			private JettyServerLifecycle jettyServerLifecycle;
160 	
161 			public boolean isStarted() {
162 				return jettyServerLifecycle.isStarted();
163 			}
164 	
165 			public void start() throws Exception {
166 	            System.setProperty("web.bootstrap.spring.file", "classpath:TestHarnessSpringBeans.xml");
167 	            jettyServerLifecycle = new JettyServerLifecycle(getPort(), getContext(), RELATIVE_WEBAPP_ROOT);
168 	            jettyServerLifecycle.setConfigMode(ConfigMode.OVERRIDE);
169 				jettyServerLifecycle.start();
170 			}
171 	
172 			public void stop() throws Exception {
173 				this.jettyServerLifecycle.stop();
174 			}
175 		});
176 	
177 	    ClearDatabaseLifecycle clearDatabaseLifecycle = new ClearDatabaseLifecycle();
178 	    clearDatabaseLifecycle.getAlternativeTablesToClear().add("KREW_RULE_T");
179 	    clearDatabaseLifecycle.getAlternativeTablesToClear().add("KREW_RULE_RSP_T");
180 	    clearDatabaseLifecycle.getAlternativeTablesToClear().add("KREW_DLGN_RSP_T");
181 	    clearDatabaseLifecycle.getAlternativeTablesToClear().add("KREW_RULE_ATTR_T");
182 	    clearDatabaseLifecycle.getAlternativeTablesToClear().add("KREW_RULE_TMPL_T");
183 	    clearDatabaseLifecycle.getAlternativeTablesToClear().add("KREW_DOC_TYP_T");
184 	    lifecycles.add(clearDatabaseLifecycle);
185 	
186 	    File[] folders = new File(FILE_PREFIX).listFiles();
187 
188 	    if (folders != null) {
189             Arrays.sort(folders);
190             for (File folder : folders) {
191             	if (folder.getName().startsWith("00")) {
192             		File[] files = new File(FILE_PREFIX + folder.getName()).listFiles();
193             		if (files != null) {
194                         // Arrays.sort(files);
195                         for (File file : files) {
196                         	if (file.getName().endsWith(".xml")) {
197                         		lifecycles.add(new KPMEXmlDataLoaderLifecycle(FILE_PREFIX + folder.getName() + "/" + file.getName()));
198                         	}
199                         }
200     		        }
201 	            }		        
202             }
203 	    }
204 		return lifecycles;
205 	}
206 
207 /*	public void futureEffectiveDateValidation(String baseUrl) throws Exception {
208 	  	HtmlPage page = HtmlUnitUtil.gotoPageAndLogin(getWebClient(), baseUrl);
209 	  	Assert.assertNotNull(page);
210 	
211 	  	HtmlForm form = page.getFormByName("KualiForm");
212 	  	Assert.assertNotNull("Search form was missing from page.", form);
213 	  	// use past dates
214 	    setFieldValue(page, "document.newMaintainableObject.effectiveDate", "04/01/2011");
215 	    HtmlInput  input  = HtmlUnitUtil.getInputContainingText(form, "methodToCall.route");
216 	    Assert.assertNotNull("Could not locate submit button", input);
217 	  	page = ((HtmlButtonInput)page.getElementByName("methodToCall.route")).click();
218 	  	Assert.assertTrue("page text does not contain:\n" + HrTestConstants.EFFECTIVE_DATE_ERROR, page.asText().contains(HrTestConstants.EFFECTIVE_DATE_ERROR));
219 	  	LocalDate futureDate = LocalDate.now().plusYears(2); // 2 years in the future
220 	  	String futureDateString = "01/01/" + Integer.toString(futureDate.getYear());
221 	  	
222 	  	// use dates 2 years in the future
223 	    setFieldValue(page, "document.newMaintainableObject.effectiveDate", futureDateString);
224 	  	page = ((HtmlButtonInput)page.getElementByName("methodToCall.route")).click();
225 	  	Assert.assertTrue("page text does not contain:\n" + HrTestConstants.EFFECTIVE_DATE_ERROR, page.asText().contains(HrTestConstants.EFFECTIVE_DATE_ERROR));
226 	  	LocalDate validDate = LocalDate.now().plusMonths(5); // 5 month in the future
227 	  	String validDateString = Integer.toString(validDate.getMonthOfYear()) + '/' + Integer.toString(validDate.getDayOfMonth()) 
228 	  		+ '/' + Integer.toString(validDate.getYear());
229 	  	setFieldValue(page, "document.newMaintainableObject.effectiveDate", validDateString);
230 	  	page = ((HtmlElement)page.getElementByName("methodToCall.route")).click();
231 	  	Assert.assertFalse("page text contains:\n" + HrTestConstants.EFFECTIVE_DATE_ERROR, page.asText().contains(HrTestConstants.EFFECTIVE_DATE_ERROR));
232 	}
233 */
234     public class ClearCacheLifecycle extends BaseLifecycle {
235         private final Logger LOG = Logger.getLogger(ClearCacheLifecycle.class);
236 
237         @Override
238         public void start() throws Exception {
239             long startTime = System.currentTimeMillis();
240             LOG.info("Starting cache flushing");
241             List<CacheManager> cms = new ArrayList<CacheManager>(CoreImplServiceLocator.getCacheManagerRegistry().getCacheManagers());
242             for (CacheManager cm : cms) {
243                 for (String cacheName : cm.getCacheNames()) {
244                     //LOG.info("Clearing cache: " + cacheName);
245                     cm.getCache(cacheName).clear();
246                 }
247             }
248             long endTime = System.currentTimeMillis();
249             LOG.info("Caches cleared in " + (endTime - startTime) + "ms");
250         }
251 
252         @Override
253         public void stop() throws Exception {
254             super.stop();
255         }
256 
257     }
258 
259     public WebClient getWebClient() {
260         return this.webClient;
261     }
262 
263     public void setWebClient(WebClient webClient) {
264         this.webClient = webClient;
265     }
266     
267     public static String getBaseURL() {
268 	    return ConfigContext.getCurrentContextConfig().getProperty("application.url");
269     }
270     
271     public static String getContext() {
272     	return "/" + ConfigContext.getCurrentContextConfig().getProperty("app.context.name");
273     }
274 
275     public static String getTempDir() {
276 	return ConfigContext.getCurrentContextConfig().getProperty("temp.dir");
277     }
278 
279     public static Integer getPort() {
280 	    return new Integer(ConfigContext.getCurrentContextConfig().getProperty("kns.test.port"));
281     }
282 
283     /*protected List<String> getConfigLocations() {
284         List<String> configLocations = new ArrayList<String>();
285         //configLocations.add(getRiceMasterDefaultConfigFile());
286         configLocations.add("classpath:META-INF/kpme-test-config.xml");
287 
288         //module specific overrides:
289         configLocations.add(getModuleTestConfigLocation());
290         return configLocations;
291     }*/
292 
293 }