bb6a19a36fa5977b6ecb3b16e36a541886779fdd
[vid.git] / vid-automation / src / main / java / org / onap / sdc / ci / tests / execute / setup / SetupCDTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.sdc.ci.tests.execute.setup;
22
23 import java.io.File;
24 import java.io.IOException;
25 import java.util.UUID;
26
27 import org.onap.sdc.ci.tests.datatypes.Configuration;
28 import org.onap.sdc.ci.tests.datatypes.User;
29 import org.onap.sdc.ci.tests.datatypes.UserCredentials;
30 import org.onap.sdc.ci.tests.datatypes.UserRoleEnum;
31 import org.onap.sdc.ci.tests.execute.setup.ExtentManager.suiteNameXml;
32 import org.onap.sdc.ci.tests.run.StartTest;
33 import org.onap.sdc.ci.tests.utilities.FileHandling;
34 import org.onap.sdc.ci.tests.utilities.GeneralUIUtils;
35 import org.openqa.selenium.By;
36 import org.openqa.selenium.JavascriptExecutor;
37 import org.openqa.selenium.WebElement;
38 import org.testng.Assert;
39 import org.testng.ITestContext;
40 import org.testng.ITestResult;
41 import org.testng.annotations.AfterMethod;
42 import org.testng.annotations.AfterSuite;
43 import org.testng.annotations.BeforeMethod;
44 import org.testng.annotations.BeforeSuite;
45 import org.testng.annotations.Test;
46
47 import com.aventstack.extentreports.ExtentTest;
48 import com.aventstack.extentreports.Status;
49
50 import net.lightbody.bmp.core.har.Har;
51
52 public abstract class SetupCDTest extends DriverFactory {
53
54         private static final String RE_RUN = "<html><font color=\"red\">ReRun - </font></html>";
55
56         /**************** PRIVATES ****************/
57         private static String url;
58
59         protected static ITestContext myContext;
60
61         /**************** METHODS ****************/
62         public static ExtentTest getExtendTest() {
63                 return ExtentTestManager.getTest();
64         }
65
66         public static WindowTest getWindowTest() {
67                 return WindowTestManager.getWindowMap();
68         }
69
70         public static String getScreenshotFolder() {
71                 return getConfiguration().getScreenshotFolder();
72         }
73
74         public static String getHarFilesFolder() {
75                 return getConfiguration().getHarFilesFolder();
76         }
77         
78         public static String getReportFolder(){
79                 return getConfiguration().getReportFolder();
80         }
81         
82         public static String getReportFilename(){
83                 return getConfiguration().getReportFileName();
84         }
85         
86         protected abstract UserCredentials getUserCredentials();
87         protected abstract Configuration getEnvConfiguration();
88         protected abstract void loginToLocalSimulator(UserCredentials userCredentials);
89         
90         
91
92         /**************** BEFORE ****************/
93
94         @BeforeSuite(alwaysRun = true)
95         public void setupBeforeSuite(ITestContext context) throws Exception {
96                 setUrl();
97                 initReport(context);
98         }
99
100         private void initReport(ITestContext context) throws Exception {
101                 myContext = context;
102                 ExtentManager.initReporter(getConfiguration(), context);
103         }
104
105         @BeforeMethod(alwaysRun = true)
106         public void setBrowserBeforeTest(java.lang.reflect.Method method, ITestContext context) throws Exception {
107                 boolean emptyDataProvider = isDataProviderEmpty(method);
108                 if (emptyDataProvider) {
109                         System.out.println("ExtentReport instance started from BeforeMethod...");
110                         String suiteName = ExtentManager.getSuiteName(context);
111                         if (suiteName.equals(suiteNameXml.TESTNG_FAILED_XML_NAME.getValue())) {
112                                 ExtentTestManager.startTest(RE_RUN + method.getName());
113                         } else {
114                                 ExtentTestManager.startTest(method.getName());
115                         }
116
117                         ExtentTestManager.assignCategory(this.getClass());
118                         setBrowserBeforeTest(getUserCredentials());
119                 } else {
120                         System.out.println("ExtentReport instance started from Test...");
121                 }
122
123                 getConfiguration().setWindowsDownloadDirectory(getWindowTest().getDownloadDirectory());
124
125                 if (getConfiguration().isCaptureTraffic()) {
126                         try {
127                                 MobProxy.getPoxyServer().newHar(method.getName() + ".har");
128                         } catch (Throwable e) {
129                                 e.printStackTrace();
130                         }
131                 }
132         }
133
134         private boolean isDataProviderEmpty(java.lang.reflect.Method method) {
135                 return method.getAnnotation(Test.class).dataProvider().isEmpty();
136         }
137
138         /**************** AFTER ****************/
139         @AfterMethod(alwaysRun = true)
140         public void quitAfterTest(ITestResult result, ITestContext context) throws Exception {
141
142                 try {
143                         ReportAfterTestManager.report(result, context);
144                         GeneralUIUtils.closeErrorMessage();
145                 } finally {
146
147                         if (getConfiguration().isCaptureTraffic()) {
148 //                              addTrafficFileToReport(result);
149                         }
150
151                         ExtentTestManager.endTest();
152                         ExtentManager.closeReporter();
153                         FileHandling.cleanCurrentDownloadDir();
154                 }
155
156         }
157
158         @AfterSuite(alwaysRun = true)
159         public void afterSuite() throws Exception {
160                 if (getConfiguration().isUseBrowserMobProxy()) {
161                         MobProxy.getPoxyServer().stop();
162                 }
163         }
164
165         protected static String setUrl() {
166                 url = getConfiguration().getUrl();
167                 if (url == null) {
168                         String message = "no URL found";
169                         System.out.println(message);
170                         Assert.fail(message);
171                 } 
172                 return url;
173         }
174
175         public static void navigateToUrl(String url) throws Exception {
176                 try {
177                         System.out.println("Deleting cookies...");
178                         deleteCookies();
179
180                         System.out.println("Navigating to URL : " + url);
181                         getDriver().navigate().to(url);
182                         GeneralUIUtils.waitForLoader();
183
184                         System.out.println("Zooming out...");
185                         GeneralUIUtils.windowZoomOutUltimate();
186
187                 } catch (Exception e) {
188                         String msg = "Browser is unreachable";
189                         System.out.println(msg);
190                         e.printStackTrace();
191                         getExtendTest().log(Status.ERROR, msg);
192                         Assert.fail(msg);
193                 }
194         }
195
196         private static void deleteCookies() throws Exception {
197                 getDriver().manage().deleteAllCookies();
198                 Thread.sleep(1000);
199
200                 int attempts = 0;
201                 final int max_attempts = 3;
202
203                 while (!getDriver().manage().getCookies().isEmpty() && attempts < max_attempts) {
204                         getExtendTest().log(Status.INFO,
205                                         "Trying to delete cookies one more time - " + (attempts + 1) + "/" + max_attempts + "attempts");
206                         String deleteCookiesJS = "document.cookie.split(';').forEach(function(c) { document.cookie = c.replace(/^ +/, '').replace(/=.*/, '=;expires=' + new Date().toUTCString() + ';path=/'); });";
207                         ((JavascriptExecutor) getDriver()).executeScript(deleteCookiesJS);
208                         attempts++;
209
210                         if (attempts == max_attempts) {
211                                 String msg = "Did not delete cookies, can't login with the userId "
212                                                 + WindowTestManager.getWindowMap().getUserCredentials().getUserId();
213                                 System.out.println(msg);
214                                 getExtendTest().log(Status.ERROR, msg);
215                                 Assert.fail(msg);
216                         }
217                 }
218         }
219
220         protected void loginToSystem(UserCredentials userCredentials) throws Exception {
221                 if (getConfiguration().isUseCustomLogin()) {
222                         loginToLocalSimulator(userCredentials);
223                 } 
224                 else {
225                         sendUserAndPasswordKeys(userCredentials);
226                         WebElement submitButton = GeneralUIUtils.getWebElementBy(By.name("btnSubmit"), 30);
227                         submitButton.click();
228                         WebElement buttonOK = GeneralUIUtils.getWebElementBy(By.name("successOK"), 30);
229                         Assert.assertTrue(buttonOK.isDisplayed(), "OK button is not displayed.");
230                         buttonOK.click();
231                 }
232                 GeneralUIUtils.ultimateWait();
233                 getWindowTest().setUserCredentials(userCredentials);
234         }
235
236         private void setRefreshAttempts(int refreshAttempts) {
237                 getWindowTest().setRefreshAttempts(refreshAttempts);
238         }
239
240         private void sendUserAndPasswordKeys(UserCredentials userCredentials) {
241                 System.out.println("Login with the userId : " + userCredentials.getUserId());
242                 WebElement userNameTextbox = GeneralUIUtils.getWebElementBy(By.name("userid"));
243                 userNameTextbox.sendKeys(userCredentials.getUserId());
244                 WebElement passwordTextbox = GeneralUIUtils.getWebElementBy(By.name("password"));
245                 passwordTextbox.sendKeys(userCredentials.getPassword());
246         }
247
248         public void loginWithUser(UserCredentials userCredentials) {
249                 try {
250                         getExtendTest().log(Status.INFO, String.format("Login with the userId %s", userCredentials.getUserId()));
251                         loginToSystem(userCredentials);
252                 } catch (Exception e) {
253                         throw new RuntimeException(e);
254                 } finally {
255                         getWindowTest().setPreviousUser(getWindowTest().getUserCredentials().getUserId());
256                 }
257         }
258
259         private void setUser(UserCredentials userCredentials) {
260                 User user = new User();
261                 user.setUserId(userCredentials.getUserId());
262                 user.setFirstName(userCredentials.getFirstName());
263                 user.setRole(userCredentials.getRole());
264                 user.setLastName(userCredentials.getLastName());
265                 getWindowTest().setUserCredentials(userCredentials);
266         }
267
268         public User getUser() {
269                 return getWindowTest().getUserCredentials();
270         }
271
272         private void setBrowserBeforeTest(UserCredentials userCredentials) {
273                 System.out.println(String.format("Setup before test with the userId %s.", userCredentials.getUserId()));
274                 try {
275                         System.out.println("Previous userId is : " + getWindowTest().getPreviousUser() + " ; Current userId is : " + userCredentials.getUserId());
276                         if (!getWindowTest().getPreviousUser().toLowerCase().equals(userCredentials.getUserId())) {
277                                 System.out.println("User IDs are different. navigating and login.");
278                                 navigateAndLogin(userCredentials);
279                         }
280                 } catch (Exception e) {
281                         e.printStackTrace();
282                 }
283         }
284
285         public void navigateAndLogin(UserCredentials userCredentials) throws Exception {
286                 int refreshAttempts = getWindowTest().getRefreshAttempts() != 0 ? getWindowTest().getRefreshAttempts() : 0;
287                 setRefreshAttempts(refreshAttempts);
288                 setUser(userCredentials);
289                 navigateToUrl(url);
290                 loginWithUser(userCredentials);
291                 GeneralUIUtils.ultimateWait();
292         }
293
294         public User getUser(UserRoleEnum role) {
295                 User user = new User();
296                 user.setUserId(role.getUserId());
297                 user.setFirstName(role.getFirstName());
298                 user.setLastName(role.getLastName());
299                 user.setRole(role.name());
300                 return user;
301         }
302
303         protected void reloginWithNewRole(UserCredentials userCredentials) throws Exception {
304                 System.out.println(String.format("Setup before relogin with the userId %s", userCredentials.getUserId()));
305                 navigateAndLogin(userCredentials);
306         }
307
308         public void addTrafficFileToReport(ITestResult result) {
309                 try {
310                         // Get the HAR data
311                         Har har = MobProxy.getPoxyServer().getHar();
312                         String shortUUID = UUID.randomUUID().toString().split("-")[0];
313                         File harFile = new File(getHarFilesFolder() + result.getName() + shortUUID + ".har");
314                         new File(getHarFilesFolder()).mkdirs();
315
316                         har.writeTo(harFile);
317
318                         String pathToFileFromReportDirectory = getReportFolder() + File.separator + harFile.getName();
319                         ExtentTestActions.addFileToReportAsLink(harFile, pathToFileFromReportDirectory,
320                                         "File with captured traffic");
321                 } catch (IOException ioe) {
322                         ioe.printStackTrace();
323                 }
324         }
325
326         /*
327          * * Start section of test in ExtentReport with DataProvider parameters,
328          * should be started from test method, see example in onboardVNFTest
329          */
330         public void setLog(String fromDataProvider) {
331
332                 String suiteName = ExtentManager.getSuiteName(myContext);
333                 if (suiteName.equals(suiteNameXml.TESTNG_FAILED_XML_NAME.getValue())) {
334                         ExtentTestManager.startTest(RE_RUN + Thread.currentThread().getStackTrace()[2].getMethodName()
335                                         + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + fromDataProvider);
336                 } else {
337                         ExtentTestManager.startTest(Thread.currentThread().getStackTrace()[2].getMethodName()
338                                         + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + fromDataProvider);
339                 }
340
341                 getWindowTest().setAddedValueFromDataProvider(fromDataProvider);
342                 ExtentTestManager.assignCategory(this.getClass());
343                 setBrowserBeforeTest(getUserCredentials());
344         }
345         
346         public static void main(String[] args) {
347                 System.out.println("---------------------");
348                 System.out.println("running test from CLI");
349                 System.out.println("---------------------");
350
351                 String testSuite = System.getProperty("testSuite");
352                 String[] testSuiteArr = {testSuite};
353                 StartTest.main(testSuiteArr);
354         }
355         
356 }