001/**
002 * Copyright 2004-2014 The Kuali Foundation
003 *
004 * Licensed under the Educational Community License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.opensource.org/licenses/ecl2.php
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.kuali.hr;
017
018import java.io.File;
019import java.util.ArrayList;
020import java.util.Arrays;
021import java.util.List;
022
023import org.apache.log4j.Logger;
024import org.kuali.kpme.core.rice.test.lifecycles.KPMEXmlDataLoaderLifecycle;
025import org.kuali.kpme.core.util.ClearDatabaseLifecycle;
026import org.kuali.kpme.core.util.DatabaseCleanupDataLifecycle;
027import org.kuali.kpme.core.util.HrContext;
028import org.kuali.kpme.core.util.LoadDatabaseDataLifeCycle;
029import org.kuali.rice.core.api.config.property.Config;
030import org.kuali.rice.core.api.config.property.ConfigContext;
031import org.kuali.rice.core.api.lifecycle.BaseLifecycle;
032import org.kuali.rice.core.api.lifecycle.Lifecycle;
033import org.kuali.rice.core.impl.services.CoreImplServiceLocator;
034import org.kuali.rice.krad.UserSession;
035import org.kuali.rice.krad.util.GlobalVariables;
036import org.kuali.rice.krad.util.MessageMap;
037import org.kuali.rice.test.RiceInternalSuiteDataTestCase;
038import org.kuali.rice.test.TransactionalLifecycle;
039import org.kuali.rice.test.lifecycles.JettyServerLifecycle;
040import org.kuali.rice.test.lifecycles.JettyServerLifecycle.ConfigMode;
041import org.springframework.cache.CacheManager;
042
043import com.gargoylesoftware.htmlunit.BrowserVersion;
044import com.gargoylesoftware.htmlunit.WebClient;
045
046/**
047 *  Default test base for a full KPME unit test.
048 */
049public abstract class KPMEWebTestCase extends RiceInternalSuiteDataTestCase {
050
051        private static final String FILE_PREFIX = System.getProperty("user.dir") + "/../db/src/main/config/workflow/";
052
053        private static final String RELATIVE_WEBAPP_ROOT = "/src/main/webapp";
054        
055        private TransactionalLifecycle transactionalLifecycle;
056    private WebClient webClient;
057        
058        @Override
059        protected String getModuleName() {
060                return "kpme";
061        }
062
063        @Override
064        public void setUp() throws Exception {
065            if (System.getProperty("basedir") == null) {
066                System.setProperty("basedir", System.getProperty("user.dir") + "/");
067            }
068            
069                super.setUp();
070
071                GlobalVariables.setMessageMap(new MessageMap());
072                
073                final boolean needsSpring = false;
074                if (needsSpring) {
075                        transactionalLifecycle = new TransactionalLifecycle();
076                        //transactionalLifecycle.setTransactionManager(KRADServiceLocatorInternal.getTransactionManager());
077                        transactionalLifecycle.start();
078                }
079
080            new ClearDatabaseLifecycle().start();
081        
082                new LoadDatabaseDataLifeCycle(this.getClass()).start();
083        
084            //lets try to create a user session
085            GlobalVariables.setUserSession(new UserSession("admin"));
086        setWebClient(new WebClient(BrowserVersion.FIREFOX_17));
087        getWebClient().getOptions().setJavaScriptEnabled(true);
088        getWebClient().getOptions().setTimeout(0);
089        }
090        
091        @Override
092        public void tearDown() throws Exception {
093            // runs custom SQL at the end of each test.
094            // useful for difficult to reset test additions, not handled by
095            // our ClearDatabaseLifecycle.
096        HrContext.clearTargetUser();
097        getWebClient().closeAllWindows();
098            new DatabaseCleanupDataLifecycle(this.getClass()).start();
099
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[] files = new File(FILE_PREFIX).listFiles();
187            if (files != null) {
188            Arrays.sort(files);
189                for (File file : files) {
190                    if (file.getName().endsWith(".xml")) {
191                        lifecycles.add(new KPMEXmlDataLoaderLifecycle(FILE_PREFIX + file.getName()));
192                    }
193                }
194            }
195                return lifecycles;
196        }
197
198/*      public void futureEffectiveDateValidation(String baseUrl) throws Exception {
199                HtmlPage page = HtmlUnitUtil.gotoPageAndLogin(getWebClient(), baseUrl);
200                Assert.assertNotNull(page);
201        
202                HtmlForm form = page.getFormByName("KualiForm");
203                Assert.assertNotNull("Search form was missing from page.", form);
204                // use past dates
205            setFieldValue(page, "document.newMaintainableObject.effectiveDate", "04/01/2011");
206            HtmlInput  input  = HtmlUnitUtil.getInputContainingText(form, "methodToCall.route");
207            Assert.assertNotNull("Could not locate submit button", input);
208                page = ((HtmlButtonInput)page.getElementByName("methodToCall.route")).click();
209                Assert.assertTrue("page text does not contain:\n" + HrTestConstants.EFFECTIVE_DATE_ERROR, page.asText().contains(HrTestConstants.EFFECTIVE_DATE_ERROR));
210                LocalDate futureDate = LocalDate.now().plusYears(2); // 2 years in the future
211                String futureDateString = "01/01/" + Integer.toString(futureDate.getYear());
212                
213                // use dates 2 years in the future
214            setFieldValue(page, "document.newMaintainableObject.effectiveDate", futureDateString);
215                page = ((HtmlButtonInput)page.getElementByName("methodToCall.route")).click();
216                Assert.assertTrue("page text does not contain:\n" + HrTestConstants.EFFECTIVE_DATE_ERROR, page.asText().contains(HrTestConstants.EFFECTIVE_DATE_ERROR));
217                LocalDate validDate = LocalDate.now().plusMonths(5); // 5 month in the future
218                String validDateString = Integer.toString(validDate.getMonthOfYear()) + '/' + Integer.toString(validDate.getDayOfMonth()) 
219                        + '/' + Integer.toString(validDate.getYear());
220                setFieldValue(page, "document.newMaintainableObject.effectiveDate", validDateString);
221                page = ((HtmlElement)page.getElementByName("methodToCall.route")).click();
222                Assert.assertFalse("page text contains:\n" + HrTestConstants.EFFECTIVE_DATE_ERROR, page.asText().contains(HrTestConstants.EFFECTIVE_DATE_ERROR));
223        }
224*/
225    public class ClearCacheLifecycle extends BaseLifecycle {
226        private final Logger LOG = Logger.getLogger(ClearCacheLifecycle.class);
227
228        @Override
229        public void start() throws Exception {
230            long startTime = System.currentTimeMillis();
231            LOG.info("Starting cache flushing");
232            List<CacheManager> cms = new ArrayList<CacheManager>(CoreImplServiceLocator.getCacheManagerRegistry().getCacheManagers());
233            for (CacheManager cm : cms) {
234                for (String cacheName : cm.getCacheNames()) {
235                    //LOG.info("Clearing cache: " + cacheName);
236                    cm.getCache(cacheName).clear();
237                }
238            }
239            long endTime = System.currentTimeMillis();
240            LOG.info("Caches cleared in " + (endTime - startTime) + "ms");
241        }
242
243        @Override
244        public void stop() throws Exception {
245            super.stop();
246        }
247
248    }
249
250    public WebClient getWebClient() {
251        return this.webClient;
252    }
253
254    public void setWebClient(WebClient webClient) {
255        this.webClient = webClient;
256    }
257    
258    public static String getBaseURL() {
259            return ConfigContext.getCurrentContextConfig().getProperty("application.url");
260    }
261    
262    public static String getContext() {
263        return "/" + ConfigContext.getCurrentContextConfig().getProperty("app.context.name");
264    }
265
266    public static String getTempDir() {
267        return ConfigContext.getCurrentContextConfig().getProperty("temp.dir");
268    }
269
270    public static Integer getPort() {
271            return new Integer(ConfigContext.getCurrentContextConfig().getProperty("kns.test.port"));
272    }
273
274    /*protected List<String> getConfigLocations() {
275        List<String> configLocations = new ArrayList<String>();
276        //configLocations.add(getRiceMasterDefaultConfigFile());
277        configLocations.add("classpath:META-INF/kpme-test-config.xml");
278
279        //module specific overrides:
280        configLocations.add(getModuleTestConfigLocation());
281        return configLocations;
282    }*/
283
284}