2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.sdc.ci.tests.execute.setup;
24 import java.io.IOException;
25 import java.util.UUID;
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;
47 import com.aventstack.extentreports.ExtentTest;
48 import com.aventstack.extentreports.Status;
50 import net.lightbody.bmp.core.har.Har;
52 public abstract class SetupCDTest extends DriverFactory {
54 private static final String RE_RUN = "<html><font color=\"red\">ReRun - </font></html>";
56 /**************** PRIVATES ****************/
57 private static String url;
59 protected static ITestContext myContext;
61 /**************** METHODS ****************/
62 public static ExtentTest getExtendTest() {
63 return ExtentTestManager.getTest();
66 public static WindowTest getWindowTest() {
67 return WindowTestManager.getWindowMap();
70 public static String getScreenshotFolder() {
71 return getConfiguration().getScreenshotFolder();
74 public static String getHarFilesFolder() {
75 return getConfiguration().getHarFilesFolder();
78 public static String getReportFolder(){
79 return getConfiguration().getReportFolder();
82 public static String getReportFilename(){
83 return getConfiguration().getReportFileName();
86 protected abstract UserCredentials getUserCredentials();
87 protected abstract Configuration getEnvConfiguration();
88 protected abstract void loginToLocalSimulator(UserCredentials userCredentials);
92 /**************** BEFORE ****************/
94 @BeforeSuite(alwaysRun = true)
95 public void setupBeforeSuite(ITestContext context) throws Exception {
100 private void initReport(ITestContext context) throws Exception {
102 ExtentManager.initReporter(getConfiguration(), context);
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());
114 ExtentTestManager.startTest(method.getName());
117 ExtentTestManager.assignCategory(this.getClass());
118 setBrowserBeforeTest(getUserCredentials());
120 System.out.println("ExtentReport instance started from Test...");
123 getConfiguration().setWindowsDownloadDirectory(getWindowTest().getDownloadDirectory());
125 if (getConfiguration().isCaptureTraffic()) {
127 MobProxy.getPoxyServer().newHar(method.getName() + ".har");
128 } catch (Throwable e) {
134 private boolean isDataProviderEmpty(java.lang.reflect.Method method) {
135 return method.getAnnotation(Test.class).dataProvider().isEmpty();
138 /**************** AFTER ****************/
139 @AfterMethod(alwaysRun = true)
140 public void quitAfterTest(ITestResult result, ITestContext context) throws Exception {
143 ReportAfterTestManager.report(result, context);
144 GeneralUIUtils.closeErrorMessage();
147 if (getConfiguration().isCaptureTraffic()) {
148 // addTrafficFileToReport(result);
151 ExtentTestManager.endTest();
152 ExtentManager.closeReporter();
153 FileHandling.cleanCurrentDownloadDir();
158 @AfterSuite(alwaysRun = true)
159 public void afterSuite() throws Exception {
160 if (getConfiguration().isUseBrowserMobProxy()) {
161 MobProxy.getPoxyServer().stop();
165 protected static String setUrl() {
166 url = getConfiguration().getUrl();
168 String message = "no URL found";
169 System.out.println(message);
170 Assert.fail(message);
175 public static void navigateToUrl(String url) throws Exception {
177 System.out.println("Deleting cookies...");
180 System.out.println("Navigating to URL : " + url);
181 getDriver().navigate().to(url);
182 GeneralUIUtils.waitForLoader();
184 System.out.println("Zooming out...");
185 GeneralUIUtils.windowZoomOutUltimate();
187 } catch (Exception e) {
188 String msg = "Browser is unreachable";
189 System.out.println(msg);
191 getExtendTest().log(Status.ERROR, msg);
196 private static void deleteCookies() throws Exception {
197 getDriver().manage().deleteAllCookies();
201 final int max_attempts = 3;
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);
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);
220 protected void loginToSystem(UserCredentials userCredentials) throws Exception {
221 if (getConfiguration().isUseCustomLogin()) {
222 loginToLocalSimulator(userCredentials);
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.");
232 GeneralUIUtils.ultimateWait();
233 getWindowTest().setUserCredentials(userCredentials);
236 private void setRefreshAttempts(int refreshAttempts) {
237 getWindowTest().setRefreshAttempts(refreshAttempts);
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());
248 public void loginWithUser(UserCredentials userCredentials) {
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);
255 getWindowTest().setPreviousUser(getWindowTest().getUserCredentials().getUserId());
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);
268 public User getUser() {
269 return getWindowTest().getUserCredentials();
272 private void setBrowserBeforeTest(UserCredentials userCredentials) {
273 System.out.println(String.format("Setup before test with the userId %s.", userCredentials.getUserId()));
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);
280 } catch (Exception e) {
285 public void navigateAndLogin(UserCredentials userCredentials) throws Exception {
286 int refreshAttempts = getWindowTest().getRefreshAttempts() != 0 ? getWindowTest().getRefreshAttempts() : 0;
287 setRefreshAttempts(refreshAttempts);
288 setUser(userCredentials);
290 loginWithUser(userCredentials);
291 GeneralUIUtils.ultimateWait();
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());
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);
308 public void addTrafficFileToReport(ITestResult result) {
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();
316 har.writeTo(harFile);
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();
327 * * Start section of test in ExtentReport with DataProvider parameters,
328 * should be started from test method, see example in onboardVNFTest
330 public void setLog(String fromDataProvider) {
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 + " " + fromDataProvider);
337 ExtentTestManager.startTest(Thread.currentThread().getStackTrace()[2].getMethodName()
338 + " " + fromDataProvider);
341 getWindowTest().setAddedValueFromDataProvider(fromDataProvider);
342 ExtentTestManager.assignCategory(this.getClass());
343 setBrowserBeforeTest(getUserCredentials());
346 public static void main(String[] args) {
347 System.out.println("---------------------");
348 System.out.println("running test from CLI");
349 System.out.println("---------------------");
351 String testSuite = System.getProperty("testSuite");
352 String[] testSuiteArr = {testSuite};
353 StartTest.main(testSuiteArr);