adjust BrowseASDCTest with FLAG_2002_ANY_ALACARTE_BESIDES_EXCLUDED_NEW_INSTANTIATION_UI
[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("Deleting cookies...");
175                         deleteCookies();
176
177                         System.out.println("Navigating to URL : " + url);
178                         getDriver().navigate().to(url);
179                         GeneralUIUtils.waitForLoader();
180
181                         System.out.println("Zooming out...");
182                         GeneralUIUtils.windowZoomOutUltimate();
183
184                 } catch (Exception e) {
185                         String msg = "Browser is unreachable";
186                         System.out.println(msg);
187                         e.printStackTrace();
188                         getExtendTest().log(Status.ERROR, msg);
189                         Assert.fail(msg);
190                 }
191         }
192
193         private static void deleteCookies() throws Exception {
194                 getDriver().manage().deleteAllCookies();
195                 Thread.sleep(1000);
196
197                 int attempts = 0;
198                 final int max_attempts = 3;
199
200                 while (!getDriver().manage().getCookies().isEmpty() && attempts < max_attempts) {
201                         getExtendTest().log(Status.INFO,
202                                         "Trying to delete cookies one more time - " + (attempts + 1) + "/" + max_attempts + "attempts");
203                         String deleteCookiesJS = "document.cookie.split(';').forEach(function(c) { document.cookie = c.replace(/^ +/, '').replace(/=.*/, '=;expires=' + new Date().toUTCString() + ';path=/'); });";
204                         ((JavascriptExecutor) getDriver()).executeScript(deleteCookiesJS);
205                         attempts++;
206
207                         if (attempts == max_attempts) {
208                                 String msg = "Did not delete cookies, can't login with the userId "
209                                                 + WindowTestManager.getWindowMap().getUserCredentials().getUserId();
210                                 System.out.println(msg);
211                                 getExtendTest().log(Status.ERROR, msg);
212                                 Assert.fail(msg);
213                         }
214                 }
215         }
216
217         protected void loginToSystem(UserCredentials userCredentials) throws Exception {
218                 if (getConfiguration().isUseCustomLogin()) {
219                         loginToLocalSimulator(userCredentials);
220                 } 
221                 else {
222                         sendUserAndPasswordKeys(userCredentials);
223                         WebElement submitButton = GeneralUIUtils.getWebElementBy(By.name("btnSubmit"), 30);
224                         submitButton.click();
225                         WebElement buttonOK = GeneralUIUtils.getWebElementBy(By.name("successOK"), 30);
226                         Assert.assertTrue(buttonOK.isDisplayed(), "OK button is not displayed.");
227                         buttonOK.click();
228                 }
229                 GeneralUIUtils.ultimateWait();
230                 getWindowTest().setUserCredentials(userCredentials);
231         }
232
233         private void setRefreshAttempts(int refreshAttempts) {
234                 getWindowTest().setRefreshAttempts(refreshAttempts);
235         }
236
237         private void sendUserAndPasswordKeys(UserCredentials userCredentials) {
238                 System.out.println("Login with the userId : " + userCredentials.getUserId());
239                 WebElement userNameTextbox = GeneralUIUtils.getWebElementBy(By.name("userid"));
240                 userNameTextbox.sendKeys(userCredentials.getUserId());
241                 WebElement passwordTextbox = GeneralUIUtils.getWebElementBy(By.name("password"));
242                 passwordTextbox.sendKeys(userCredentials.getPassword());
243         }
244
245         public void loginWithUser(UserCredentials userCredentials) {
246                 try {
247                         getExtendTest().log(Status.INFO, String.format("Login with the userId %s", userCredentials.getUserId()));
248                         loginToSystem(userCredentials);
249                 } catch (Exception e) {
250                         throw new RuntimeException(e);
251                 } finally {
252                         getWindowTest().setPreviousUser(getWindowTest().getUserCredentials().getUserId());
253                 }
254         }
255
256         private void setUser(UserCredentials userCredentials) {
257                 User user = new User();
258                 user.setUserId(userCredentials.getUserId());
259                 user.setFirstName(userCredentials.getFirstName());
260                 user.setRole(userCredentials.getRole());
261                 user.setLastName(userCredentials.getLastName());
262                 getWindowTest().setUserCredentials(userCredentials);
263         }
264
265         public User getUser() {
266                 return getWindowTest().getUserCredentials();
267         }
268
269         private void setBrowserBeforeTest(UserCredentials userCredentials) {
270                 System.out.println(String.format("Setup before test with the userId %s.", userCredentials.getUserId()));
271                 try {
272                         System.out.println("Previous userId is : " + getWindowTest().getPreviousUser() + " ; Current userId is : " + userCredentials.getUserId());
273                         if (!getWindowTest().getPreviousUser().toLowerCase().equals(userCredentials.getUserId())) {
274                                 System.out.println("User IDs are different. navigating and login.");
275                                 navigateAndLogin(userCredentials);
276                         }
277                 } catch (Exception e) {
278                         e.printStackTrace();
279                 }
280         }
281
282         public void navigateAndLogin(UserCredentials userCredentials)  {
283                 int refreshAttempts = getWindowTest().getRefreshAttempts() != 0 ? getWindowTest().getRefreshAttempts() : 0;
284                 setRefreshAttempts(refreshAttempts);
285                 setUser(userCredentials);
286                 navigateToUrl(url);
287                 loginWithUser(userCredentials);
288                 GeneralUIUtils.ultimateWait();
289         }
290
291         public User getUser(UserRoleEnum role) {
292                 User user = new User();
293                 user.setUserId(role.getUserId());
294                 user.setFirstName(role.getFirstName());
295                 user.setLastName(role.getLastName());
296                 user.setRole(role.name());
297                 return user;
298         }
299
300         protected void reloginWithNewRole(UserCredentials userCredentials)  {
301                 System.out.println(String.format("Setup before relogin with the userId %s", userCredentials.getUserId()));
302                 navigateAndLogin(userCredentials);
303         }
304
305         public void addTrafficFileToReport(ITestResult result) {
306                 try {
307                         // Get the HAR data
308                         Har har = MobProxy.getPoxyServer().getHar();
309                         String shortUUID = UUID.randomUUID().toString().split("-")[0];
310                         File harFile = new File(getHarFilesFolder() + result.getName() + shortUUID + ".har");
311                         new File(getHarFilesFolder()).mkdirs();
312
313                         har.writeTo(harFile);
314
315                         String pathToFileFromReportDirectory = getReportFolder() + File.separator + harFile.getName();
316                         ExtentTestActions.addFileToReportAsLink(harFile, pathToFileFromReportDirectory,
317                                         "File with captured traffic");
318                 } catch (IOException ioe) {
319                         ioe.printStackTrace();
320                 }
321         }
322
323         /*
324          * * Start section of test in ExtentReport with DataProvider parameters,
325          * should be started from test method, see example in onboardVNFTest
326          */
327         public void setLog(String fromDataProvider) {
328
329                 String suiteName = ExtentManager.getSuiteName(myContext);
330                 if (suiteName.equals(suiteNameXml.TESTNG_FAILED_XML_NAME.getValue())) {
331                         ExtentTestManager.startTest(RE_RUN + Thread.currentThread().getStackTrace()[2].getMethodName()
332                                         + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + fromDataProvider);
333                 } else {
334                         ExtentTestManager.startTest(Thread.currentThread().getStackTrace()[2].getMethodName()
335                                         + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + fromDataProvider);
336                 }
337
338                 getWindowTest().setAddedValueFromDataProvider(fromDataProvider);
339                 ExtentTestManager.assignCategory(this.getClass());
340                 setBrowserBeforeTest(getUserCredentials());
341         }
342         
343         public static void main(String[] args) {
344                 System.out.println("---------------------");
345                 System.out.println("running test from CLI");
346                 System.out.println("---------------------");
347
348                 String testSuite = System.getProperty("testSuite");
349                 String[] testSuiteArr = {testSuite};
350                 StartTest.main(testSuiteArr);
351         }
352         
353 }