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