diff --git a/Drivers/chromedriver b/Drivers/chromedriver new file mode 100755 index 00000000..543ed9f5 Binary files /dev/null and b/Drivers/chromedriver differ diff --git a/chromedriver.exe b/Drivers/chromedriver.exe similarity index 100% rename from chromedriver.exe rename to Drivers/chromedriver.exe diff --git a/chromedriver_linux b/Drivers/chromedriver_linux similarity index 100% rename from chromedriver_linux rename to Drivers/chromedriver_linux diff --git a/Resources/DataProvider.xls b/Resources/DataProvider.xls new file mode 100755 index 00000000..381150bb Binary files /dev/null and b/Resources/DataProvider.xls differ diff --git a/chromedriver b/chromedriver deleted file mode 100755 index 93c906e2..00000000 Binary files a/chromedriver and /dev/null differ diff --git a/config.properties b/config.properties new file mode 100644 index 00000000..4c1a9f39 --- /dev/null +++ b/config.properties @@ -0,0 +1,16 @@ +environment=https://www.cleartrip.com/ +platformname=desktop +//browser=chrome or mozilla or notrequired +browser=chrome +//os=windows or mac +os=mac +resultsdir=Reports +shareddirectory=Drivers +reportfilename=Test_Status.html +tomail=dummy@gmail.com +replyto=noreply +reportemail=dummy@gmail.com +//reportemail=dummy@gmail.com +reportpassword=password +resources=Resources +dataproviderpath=DataProvider.xls \ No newline at end of file diff --git a/pom.xml b/pom.xml index 839ed21f..cacfc856 100644 --- a/pom.xml +++ b/pom.xml @@ -3,14 +3,14 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 4.0.0 com.testvagrant.codingRound - codoingRound + codingRound 1.0-SNAPSHOT junit junit 4.11 - compile + test org.seleniumhq.selenium @@ -24,5 +24,25 @@ 6.11 compile + + org.apache.poi + poi + 3.7 + + + com.relevantcodes + extentreports + 2.41.2 + + + javax.mail + mail + 1.4.7 + + + com.sun.mail + smtp + 1.6.2 + diff --git a/settings.gradle b/settings.gradle index 7b80fd47..330a12c6 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,2 +1,2 @@ -rootProject.name = 'codoingRound' +rootProject.name = 'codingRound' diff --git a/src/main/java/FlightBookingTest.java b/src/main/java/FlightBookingTest.java deleted file mode 100644 index 19d98ddf..00000000 --- a/src/main/java/FlightBookingTest.java +++ /dev/null @@ -1,89 +0,0 @@ -import com.sun.javafx.PlatformUtil; -import org.openqa.selenium.By; -import org.openqa.selenium.NoSuchElementException; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.WebElement; -import org.openqa.selenium.chrome.ChromeDriver; -import org.openqa.selenium.support.ui.Select; -import org.testng.Assert; -import org.testng.annotations.Test; - -import java.util.List; - -public class FlightBookingTest { - - WebDriver driver = new ChromeDriver(); - - - @Test - public void testThatResultsAppearForAOneWayJourney() { - - setDriverPath(); - driver.get("https://www.cleartrip.com/"); - waitFor(2000); - driver.findElement(By.id("OneWay")).click(); - - driver.findElement(By.id("FromTag")).clear(); - driver.findElement(By.id("FromTag")).sendKeys("Bangalore"); - - //wait for the auto complete options to appear for the origin - - waitFor(2000); - List originOptions = driver.findElement(By.id("ui-id-1")).findElements(By.tagName("li")); - originOptions.get(0).click(); - - driver.findElement(By.id("toTag")).clear(); - driver.findElement(By.id("toTag")).sendKeys("Delhi"); - - //wait for the auto complete options to appear for the destination - - waitFor(2000); - //select the first item from the destination auto complete list - List destinationOptions = driver.findElement(By.id("ui-id-2")).findElements(By.tagName("li")); - destinationOptions.get(0).click(); - - driver.findElement(By.xpath("//*[@id='ui-datepicker-div']/div[1]/table/tbody/tr[3]/td[7]/a")).click(); - - //all fields filled in. Now click on search - driver.findElement(By.id("SearchBtn")).click(); - - waitFor(5000); - //verify that result appears for the provided journey search - Assert.assertTrue(isElementPresent(By.className("searchSummary"))); - - //close the browser - driver.quit(); - - } - - - private void waitFor(int durationInMilliSeconds) { - try { - Thread.sleep(durationInMilliSeconds); - } catch (InterruptedException e) { - e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. - } - } - - - private boolean isElementPresent(By by) { - try { - driver.findElement(by); - return true; - } catch (NoSuchElementException e) { - return false; - } - } - - private void setDriverPath() { - if (PlatformUtil.isMac()) { - System.setProperty("webdriver.chrome.driver", "chromedriver"); - } - if (PlatformUtil.isWindows()) { - System.setProperty("webdriver.chrome.driver", "chromedriver.exe"); - } - if (PlatformUtil.isLinux()) { - System.setProperty("webdriver.chrome.driver", "chromedriver_linux"); - } - } -} diff --git a/src/main/java/HotelBookingTest.java b/src/main/java/HotelBookingTest.java deleted file mode 100644 index 2be026bb..00000000 --- a/src/main/java/HotelBookingTest.java +++ /dev/null @@ -1,53 +0,0 @@ -import com.sun.javafx.PlatformUtil; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.WebElement; -import org.openqa.selenium.chrome.ChromeDriver; -import org.openqa.selenium.support.FindBy; -import org.openqa.selenium.support.ui.Select; -import org.testng.annotations.Test; - -public class HotelBookingTest { - - WebDriver driver = new ChromeDriver(); - - @FindBy(linkText = "Hotels") - private WebElement hotelLink; - - @FindBy(id = "Tags") - private WebElement localityTextBox; - - @FindBy(id = "SearchHotelsButton") - private WebElement searchButton; - - @FindBy(id = "travellersOnhome") - private WebElement travellerSelection; - - @Test - public void shouldBeAbleToSearchForHotels() { - setDriverPath(); - - driver.get("https://www.cleartrip.com/"); - hotelLink.click(); - - localityTextBox.sendKeys("Indiranagar, Bangalore"); - - new Select(travellerSelection).selectByVisibleText("1 room, 2 adults"); - searchButton.click(); - - driver.quit(); - - } - - private void setDriverPath() { - if (PlatformUtil.isMac()) { - System.setProperty("webdriver.chrome.driver", "chromedriver"); - } - if (PlatformUtil.isWindows()) { - System.setProperty("webdriver.chrome.driver", "chromedriver.exe"); - } - if (PlatformUtil.isLinux()) { - System.setProperty("webdriver.chrome.driver", "chromedriver_linux"); - } - } - -} diff --git a/src/main/java/SignInTest.java b/src/main/java/SignInTest.java deleted file mode 100644 index 2c109950..00000000 --- a/src/main/java/SignInTest.java +++ /dev/null @@ -1,51 +0,0 @@ -import com.sun.javafx.PlatformUtil; -import org.openqa.selenium.By; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.chrome.ChromeDriver; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class SignInTest { - - WebDriver driver = new ChromeDriver(); - - @Test - public void shouldThrowAnErrorIfSignInDetailsAreMissing() { - - setDriverPath(); - - driver.get("https://www.cleartrip.com/"); - waitFor(2000); - - driver.findElement(By.linkText("Your trips")).click(); - driver.findElement(By.id("SignIn")).click(); - - driver.findElement(By.id("signInButton")).click(); - - String errors1 = driver.findElement(By.id("errors1")).getText(); - Assert.assertTrue(errors1.contains("There were errors in your submission")); - driver.quit(); - } - - private void waitFor(int durationInMilliSeconds) { - try { - Thread.sleep(durationInMilliSeconds); - } catch (InterruptedException e) { - e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. - } - } - - private void setDriverPath() { - if (PlatformUtil.isMac()) { - System.setProperty("webdriver.chrome.driver", "chromedriver"); - } - if (PlatformUtil.isWindows()) { - System.setProperty("webdriver.chrome.driver", "chromedriver.exe"); - } - if (PlatformUtil.isLinux()) { - System.setProperty("webdriver.chrome.driver", "chromedriver_linux"); - } - } - - -} diff --git a/src/main/java/codingRound/cleartrip/FlightBooking.java b/src/main/java/codingRound/cleartrip/FlightBooking.java new file mode 100644 index 00000000..7c42d970 --- /dev/null +++ b/src/main/java/codingRound/cleartrip/FlightBooking.java @@ -0,0 +1,79 @@ +package codingRound.cleartrip; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.FindBy; +import org.openqa.selenium.support.PageFactory; + +import com.relevantcodes.extentreports.ExtentTest; + +import codingRound.commonLib.CommonFunctionsLib; +import codingRound.utility.Configurations; + +public class FlightBooking { + + @FindBy(id="OneWay") + public static WebElement onewayRadiobtn; + + @FindBy(id="FromTag") + public static WebElement fromTag; + + @FindBy(id="ToTag") + public static WebElement toTag; + + @FindBy(xpath="//input[@class='keyValue span span24 required arabicChars ui-autocomplete-input']") + public static WebElement fromInput; + + @FindBy(xpath="//input[@id='ToTag' and @class='keyValue span span24 required arabicChars ui-autocomplete-input']") + public static WebElement toInput; + @FindBy(id="ui-id-1") + public static WebElement originOptions; + + @FindBy(id="ui-id-2") + public static WebElement destinationOptions; + + @FindBy(xpath="//*[@id='ui-datepicker-div']/div[1]/table/tbody/tr[3]/td[7]/a") + public static WebElement datePickerEle; + + @FindBy(id="SearchBtn") + public static WebElement searchBtn; + + @FindBy(className="searchSummary") + public static WebElement searchSummary; + + public WebDriver driver; + public ExtentTest logger; + + public FlightBooking(WebDriver driver, ExtentTest logger) { + this.driver = driver; + this.logger = logger; + PageFactory.initElements(driver, this); + + } + public void flightBooking(Object[][] bookingDetails,Configurations testConfig, CommonFunctionsLib common) { + String from=bookingDetails[0][0].toString(); + String to=bookingDetails[0][1].toString(); + onewayRadiobtn.click(); + common.sendingKeys(fromTag, from, driver); + common.waitForPageLoaded(driver, logger); + common.checkPresenceOfElement(fromInput, driver); + originOptions.click(); + //common.waitForPageLoaded(driver, logger); + common.sendingKeys(toTag, to, driver); + common.checkPresenceOfElement(destinationOptions, driver); + + //select the first item from the destination auto complete list + + destinationOptions.click(); + datePickerEle.click(); + searchBtn.click(); + + common.waitForPageLoaded(driver, logger); + //verify that result appears for the provided journey search + + } + + public void isResultAppeared(Configurations testConfig, CommonFunctionsLib common) { + if(common.checkPresenceOfElement(searchSummary, driver)) + common.softAssert("Verify the search result"," search summary should be present","Search summary is displayed", true, logger); + } +} diff --git a/src/main/java/codingRound/cleartrip/HotelBooking.java b/src/main/java/codingRound/cleartrip/HotelBooking.java new file mode 100644 index 00000000..df4e33be --- /dev/null +++ b/src/main/java/codingRound/cleartrip/HotelBooking.java @@ -0,0 +1,47 @@ +package codingRound.cleartrip; + +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.FindBy; +import org.openqa.selenium.support.PageFactory; +import org.openqa.selenium.support.ui.Select; + +import com.relevantcodes.extentreports.ExtentTest; + +import codingRound.commonLib.CommonFunctionsLib; +import codingRound.utility.Configurations; + +public class HotelBooking { + + @FindBy(linkText = "Hotels") + private WebElement hotelLink; + + @FindBy(id = "Tags") + private WebElement localityTextBox; + + @FindBy(id = "SearchHotelsButton") + private WebElement searchButton; + + @FindBy(id = "travellersOnhome") + private WebElement travellerSelection; + public WebDriver driver; + public ExtentTest logger; + + public HotelBooking(WebDriver driver, ExtentTest logger) { + this.driver = driver; + this.logger = logger; + PageFactory.initElements(driver, this); + + } + public void hotelBooking(Configurations testConfig, CommonFunctionsLib common) { + hotelLink.click(); + common.waitForPageLoaded(driver, logger); + localityTextBox.click(); + common.sendingKeys(localityTextBox, "Indiranagar, Bangalore", driver); + + new Select(travellerSelection).selectByVisibleText("1 room, 2 adults"); + searchButton.click(); + + } + +} diff --git a/src/main/java/codingRound/cleartrip/SignIn.java b/src/main/java/codingRound/cleartrip/SignIn.java new file mode 100644 index 00000000..19c4e186 --- /dev/null +++ b/src/main/java/codingRound/cleartrip/SignIn.java @@ -0,0 +1,52 @@ +package codingRound.cleartrip; + +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.FindBy; +import org.openqa.selenium.support.PageFactory; + +import com.relevantcodes.extentreports.ExtentTest; + +import codingRound.commonLib.CommonFunctionsLib; +import codingRound.utility.Configurations; + +public class SignIn { + @FindBy(linkText = "Your trips") + private WebElement tripsLink; + + @FindBy(id = "SignIn") + private WebElement signIn; + + @FindBy(id = "signInButton") + private WebElement signInButton; + + @FindBy(id="signinForm") + private WebElement signInForm; + + @FindBy(id = "errors1") + private WebElement errorText; + + public WebDriver driver; + public ExtentTest logger; + + public SignIn(WebDriver driver, ExtentTest logger) { + this.driver = driver; + this.logger = logger; + PageFactory.initElements(driver, this); + + } + + public void signIn(Configurations testConfig, CommonFunctionsLib common) { + tripsLink.click(); + signIn.click(); + String expectedErrorMsg="There were errors in your submission Your username is a required field Your account password is a required field"; + common.waitForPageLoaded(driver, logger); + driver.switchTo().frame("modal_window"); + common.waitToBeClickable(signInButton, driver); + signInButton.click(); + String signInError=errorText.getText(); + common.softAssert("Validating for invalid login", expectedErrorMsg, signInError, + common.compareString(expectedErrorMsg, signInError, true), logger); + + } +} diff --git a/src/main/java/codingRound/commonLib/CommonFunctionsLib.java b/src/main/java/codingRound/commonLib/CommonFunctionsLib.java new file mode 100644 index 00000000..b7a8c21b --- /dev/null +++ b/src/main/java/codingRound/commonLib/CommonFunctionsLib.java @@ -0,0 +1,284 @@ +package codingRound.commonLib; +import java.awt.Robot; +import java.awt.Toolkit; +import java.awt.datatransfer.StringSelection; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import org.apache.poi.hssf.usermodel.HSSFRow; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.openqa.selenium.JavascriptExecutor; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.interactions.Actions; +import org.openqa.selenium.logging.LogEntries; +import org.openqa.selenium.logging.LogEntry; +import org.openqa.selenium.logging.LogType; +import org.openqa.selenium.logging.Logs; +import org.openqa.selenium.support.ui.ExpectedCondition; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.Select; +import org.openqa.selenium.support.ui.WebDriverWait; +import org.testng.Assert; + +import com.relevantcodes.extentreports.ExtentTest; +import com.relevantcodes.extentreports.LogStatus; + +public class CommonFunctionsLib { + + public void waitForPageLoaded(WebDriver driver, ExtentTest logger) { + ExpectedCondition expectation = new ExpectedCondition() { + public Boolean apply(WebDriver driver) { + return ((JavascriptExecutor) driver).executeScript("return document.readyState").toString() + .equals("complete"); + } + }; + try { + Thread.sleep(1000); + WebDriverWait wait = new WebDriverWait(driver, 30); + wait.until(expectation); + } catch (Throwable error) { + logger.log(LogStatus.FAIL, "Timeout waiting for Page Load Request to complete."); + } + } + + public Object[][] readExcel(String filepath, String sheetname) { + FileInputStream fis = null; + try { + fis = new FileInputStream(filepath); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + HSSFWorkbook wb = null; + try { + wb = new HSSFWorkbook(fis); + } catch (IOException e) { + e.printStackTrace(); + } + HSSFSheet sheet = wb.getSheet(sheetname); + int rowcount = sheet.getLastRowNum(); + HSSFRow row = sheet.getRow(0); + int colcount = row.getLastCellNum(); + + Object data[][] = new Object[rowcount][colcount]; + for (int i = 1; i <= rowcount; i++) { + HSSFRow row_individual = sheet.getRow(i); + for (int j = 0; j <= colcount - 1; j++) { + data[i - 1][j] = row_individual.getCell(j); + } + } + return data; + } + + public void softAssert(String stepname, String expected, String actual, boolean result, ExtentTest logger) { + if (Boolean.TRUE.equals(result)) { + logger.log(LogStatus.PASS, stepname, + "Expected value : " + expected + "
is equal to
actual value : " + actual); + } else { + logger.log(LogStatus.ERROR, stepname, + "Expected value : " + expected + "
is not equal to
actual value : " + actual); + } + } + + public void hardAssert(String stepname, String expected, String actual, boolean result, ExtentTest logger) { + if (Boolean.TRUE.equals(result)) { + logger.log(LogStatus.PASS, stepname, + "Expected value : " + expected + "
is equal to
actual value : " + actual); + } else { + logger.log(LogStatus.FAIL, stepname, + "Expected value : " + expected + "
is not equal to
actual value : " + actual); + Assert.fail(); + } + } + + public boolean compareString(String expected, String actual, boolean ignorecase) { + if ((ignorecase && expected.trim().equalsIgnoreCase(actual.trim())) || expected.trim().equals(actual.trim())) { + return true; + } else { + return false; + } + } + + public void sendingKeys(WebElement we, String text, WebDriver driver) { + if (checkPresenceOfElement(we, driver)) { + we.click(); + we.clear(); + we.sendKeys(text); + } + } + + public void scrollToWebElement(WebElement we, WebDriver driver) { + ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", we); + } + + public void scrollDown(WebDriver driver) { + ((JavascriptExecutor) driver).executeScript("window.scrollTo(0,document.body.scrollHeight)"); + } + + public void scrollUp(WebDriver driver) { + ((JavascriptExecutor) driver).executeScript("window.scrollTo(0,-document.body.scrollHeight);"); + } + + public void MouseOver(WebElement we, WebDriver driver) { + Actions actObj = new Actions(driver); + actObj.moveToElement(we).build().perform(); + } + + public boolean checkPresenceOfElement(WebElement we, WebDriver driver) { + WebDriverWait wait = new WebDriverWait(driver, 30); + wait.until(ExpectedConditions.visibilityOf(we)); + if (we.isDisplayed() && we.isEnabled()) { + return true; + } + return false; + } + + public void waitToBeClickable(WebElement we, WebDriver driver) { + WebDriverWait wait = new WebDriverWait(driver, 35); + wait.until(ExpectedConditions.elementToBeClickable(we)); + } + + public List returnHandleList(WebDriver driver) { + Set handles = driver.getWindowHandles(); + List listHandle = new ArrayList(handles); + return listHandle; + } + + public void selectFromDropdown(WebElement we, String text) { + Select oSelect = new Select(we); + oSelect.selectByVisibleText(text); + } + + public long getCurrentDateAndTime() { + long epoch = System.currentTimeMillis() / 1000; + return epoch; + } + + public void uploadFile(WebElement we, String filename, WebDriver driver) throws Exception { + StringSelection s = new StringSelection(filename); + Toolkit.getDefaultToolkit().getSystemClipboard().setContents(s, null); + Robot robot = new Robot(); + + robot.keyPress(java.awt.event.KeyEvent.VK_ENTER); + robot.keyRelease(java.awt.event.KeyEvent.VK_ENTER); + robot.keyPress(java.awt.event.KeyEvent.VK_CONTROL); + robot.keyPress(java.awt.event.KeyEvent.VK_V); + robot.keyRelease(java.awt.event.KeyEvent.VK_CONTROL); + Thread.sleep(3000); + robot.keyPress(java.awt.event.KeyEvent.VK_ENTER); + } + + public Boolean isImageDisplayed(WebElement ImageFile, WebDriver driver) { + Boolean ImagePresent = (Boolean) ((JavascriptExecutor) driver).executeScript( + "return arguments[0].complete && typeof arguments[0].naturalWidth != \"undefined\" && arguments[0].naturalWidth > 0", + ImageFile); + return ImagePresent; + + } + + public void performDragAndDrop(WebElement source, WebElement destination, WebDriver driver) { + Actions act = new Actions(driver); + act.dragAndDrop(source, destination).build().perform(); + } + + public void getAllFiles(File dir, List fileList) { + File[] files = dir.listFiles(); + for (File file : files) { + fileList.add(file); + if (file.isDirectory()) { + getAllFiles(file, fileList); + } + } + } + + public String writeZipFile(File directoryToZip, List fileList) { + + String zipFile = directoryToZip + ".zip"; + try { + + FileOutputStream fos = new FileOutputStream(zipFile); + ZipOutputStream zos = new ZipOutputStream(fos); + + for (File file : fileList) { + if (!file.isDirectory()) { // we only zip files, not directories + addToZip(directoryToZip, file, zos); + } + } + zos.close(); + fos.close(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + return zipFile; + } + + public void addToZip(File directoryToZip, File file, ZipOutputStream zos) + throws FileNotFoundException, IOException { + + FileInputStream fis = new FileInputStream(file); + String zipFilePath = file.getCanonicalPath().substring(directoryToZip.getCanonicalPath().length() + 1, + file.getCanonicalPath().length()); + ZipEntry zipEntry = new ZipEntry(zipFilePath); + zos.putNextEntry(zipEntry); + + byte[] bytes = new byte[1024]; + int length; + while ((length = fis.read(bytes)) >= 0) { + zos.write(bytes, 0, length); + } + zos.closeEntry(); + fis.close(); + } + + public LogEntries getConsoleErrors(WebDriver driver) throws InterruptedException { + Logs logs = driver.manage().logs(); + Thread.sleep(5000); + return logs.get(LogType.BROWSER); + } + + public void categorizeConsoleErrors(LogEntries logEntries, ExtentTest logger) { + List severem = new ArrayList(); + List warningm = new ArrayList(); + for (LogEntry logEntry : logEntries) { + if (logEntry.getLevel().getName().equalsIgnoreCase("SEVERE")) { + severem.add(logEntry.getMessage()); + } else if (logEntry.getLevel().getName().equalsIgnoreCase("WARNING")) { + warningm.add(logEntry.getMessage()); + } + } + + if (severem.size() > 0) { + String lsts = new String(); + for (int i = 0; i < severem.size(); i++) { + lsts = lsts + (i + 1) + ". " + severem.get(i).toString() + "
"; + } + logger.log(LogStatus.ERROR, "Console Errors - Severe", lsts); + } else { + logger.log(LogStatus.PASS, "Console Errors - Severe", "No error found"); + } + if (warningm.size() > 0) { + String lsts = new String(); + for (int i = 0; i < warningm.size(); i++) { + lsts = lsts + (i + 1) + ". " + warningm.get(i).toString() + "
"; + } + logger.log(LogStatus.ERROR, "Console Errors - Warning", lsts); + } else { + logger.log(LogStatus.PASS, "Console Errors - Warning", "No error found"); + } + + } + + + +} diff --git a/src/main/java/codingRound/utility/Configurations.java b/src/main/java/codingRound/utility/Configurations.java new file mode 100644 index 00000000..6d94c5e5 --- /dev/null +++ b/src/main/java/codingRound/utility/Configurations.java @@ -0,0 +1,114 @@ +package codingRound.utility; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Enumeration; +import java.util.Properties; + +import com.relevantcodes.extentreports.ExtentTest; +import com.relevantcodes.extentreports.LogStatus; + +public class Configurations { + + private static String fileSeparator = File.separator; + + private static final String Environment = "environment"; + private static final String Browser = "browser"; + private static final String Platform_Name = "platformname"; + private static final String OS = "os"; + private static final String TO_MAIL = "tomail"; + private static final String Results_Dir= "ResultsDir"; + private static final String Shared_Directory = "sharedDirectory"; + private static final String Resources ="resources"; + private static final String Resource_Dir = "resourceDir"; + + Properties runtimeProperties; + + public Configurations() { + + } + + public Configurations(String browser, String environment, String platformName, String os, String sharedDirectory, + String resultsdir, String tomail, ExtentTest logger) { + try { + // Read the config file + this.runtimeProperties = new Properties(); + String path = System.getProperty("user.dir") + fileSeparator + "config.properties"; + FileInputStream fn = new FileInputStream(path); + runtimeProperties.load(fn); + fn.close(); + + putRunTimeProperty("fileSeparator", fileSeparator); + String resourceDir = System.getProperty("user.dir") + fileSeparator + getRunTimeProperty(Resources); + putRunTimeProperty(Resource_Dir, resourceDir); + + overrideDefaultConfig(browser, environment, platformName, os, sharedDirectory,resultsdir, tomail); + + } catch (IOException e) { + logger.log(LogStatus.FAIL, "Error while loading configurations", e); + } + + } + + private void overrideDefaultConfig(String browser, String environment, String platformName, String os, String sharedDirectory, + String resultsdir, String tomail) { + // override the environment value if passed through mvn command line + if (isNotBlank (environment)) + putRunTimeProperty(Environment, environment.toLowerCase()); + + if (isNotBlank(browser)) + putRunTimeProperty(Browser, browser); + + if (isNotBlank(platformName)) + putRunTimeProperty(Platform_Name, platformName); + + if (isNotBlank(os)) + putRunTimeProperty(OS, os); + + if (isNotBlank(tomail)) + putRunTimeProperty(TO_MAIL, tomail); + + if (isNotBlank(resultsdir)) { + putRunTimeProperty(Results_Dir, resultsdir); + } else { + String resultsDir = System.getProperty("user.dir") + fileSeparator + getRunTimeProperty(Results_Dir); + putRunTimeProperty(Results_Dir, resultsDir); + } + if (isNotBlank(sharedDirectory)) + putRunTimeProperty(Shared_Directory, sharedDirectory); + else { + String sharedDir = System.getProperty("user.dir") + fileSeparator + + getRunTimeProperty(Shared_Directory); + putRunTimeProperty(Shared_Directory, sharedDir); + } + } + + private boolean isNotBlank(String str) { + return str != null && !str.equals("") && !str.equals(" ") && str.length()!=0; + } + + public void putRunTimeProperty(String key, String value) { + String keyName = key.toLowerCase(); + runtimeProperties.put(keyName, value); + } + + public void removeRunTimeProperty(String key) { + String keyName = key.toLowerCase(); + runtimeProperties.remove(keyName); + } + + public String getRunTimeProperty(String key) { + String keyName = key.toLowerCase(); + String value = ""; + try { + value = runtimeProperties.get(keyName).toString(); + } catch (Exception e) { + return null; + } + return value; + } + + + +} diff --git a/src/main/java/codingRound/utility/Sendmail.java b/src/main/java/codingRound/utility/Sendmail.java new file mode 100644 index 00000000..a62b66bc --- /dev/null +++ b/src/main/java/codingRound/utility/Sendmail.java @@ -0,0 +1,90 @@ +package codingRound.utility; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import javax.activation.DataHandler; +import javax.activation.DataSource; +import javax.activation.FileDataSource; +import javax.mail.BodyPart; +import javax.mail.Message; +import javax.mail.MessagingException; +import javax.mail.Multipart; +import javax.mail.PasswordAuthentication; +import javax.mail.Session; +import javax.mail.Transport; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeBodyPart; +import javax.mail.internet.MimeMessage; +import javax.mail.internet.MimeMultipart; + +import codingRound.commonLib.CommonFunctionsLib; + +public class Sendmail { + + public void SendMail(String to, String replyTo, String subject, String path, String username, String password, + String bodyData) throws IOException { + + final String username_email = username; + final String password_email = password; + + Properties props = new Properties(); + props.put("mail.smtp.host", "true"); + props.put("mail.smtp.starttls.enable", "true"); + props.put("mail.smtp.host", "smtp.gmail.com"); + props.put("mail.smtp.port", "587"); + props.put("mail.smtp.auth", "true"); + props.put("mail.from", "automation-htdigital@htdigital.in"); + props.put("mail.from.alias", "Automation Report"); + File extPath = new File(path); + String rep_start_time = extPath.getName(); + String rep_date = rep_start_time.substring(0, 10); + String rep_time = rep_start_time.substring(11, 23).replace("_", ":"); + String final_subject = subject + " : " + rep_date + " " + rep_time; + + Session session = Session.getInstance(props, new javax.mail.Authenticator() { + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username_email, password_email); + } + }); + + try { + + Message message = new MimeMessage(session); + message.setFrom(new InternetAddress(session.getProperty("mail.from"), + session.getProperty("mail.from.alias"), "UTF8")); + message.setReplyTo(InternetAddress.parse(replyTo)); + message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); + message.setSubject(final_subject); + + BodyPart messageBodyPart1 = new MimeBodyPart(); + messageBodyPart1.setText(bodyData); + + Multipart multipart = new MimeMultipart(); + multipart.addBodyPart(messageBodyPart1); + + CommonFunctionsLib common = new CommonFunctionsLib(); + File directoryToSend = new File(path); + List fileList = new ArrayList(); + common.getAllFiles(directoryToSend, fileList); + + for (int i = 0; i < fileList.size(); i++) { + MimeBodyPart messageBodyPart2 = new MimeBodyPart(); + String filename = fileList.get(i).toString(); + DataSource source = new FileDataSource(filename); + messageBodyPart2.setDataHandler(new DataHandler(source)); + messageBodyPart2.setFileName(fileList.get(i).getName()); + multipart.addBodyPart(messageBodyPart2); + } + message.setContent(multipart); + Transport.send(message); + } catch (MessagingException e) { + throw new RuntimeException(e); + } + + } +} + diff --git a/src/main/java/codingRound/utility/SuiteListener.java b/src/main/java/codingRound/utility/SuiteListener.java new file mode 100644 index 00000000..1dd7cad2 --- /dev/null +++ b/src/main/java/codingRound/utility/SuiteListener.java @@ -0,0 +1,21 @@ +package codingRound.utility; + +import org.testng.ISuite; +import org.testng.ISuiteListener; + +public class SuiteListener implements ISuiteListener { + + private static ThreadLocal ACCESS = new ThreadLocal(); + + public static ISuite getAccess() { + return ACCESS.get(); + } + + public void onStart(ISuite suite) { + ACCESS.set(suite); + } + + public void onFinish(ISuite suite) { + ACCESS.set(null); + } +} diff --git a/src/main/java/codingRound/utility/Testbase.java b/src/main/java/codingRound/utility/Testbase.java new file mode 100644 index 00000000..c656be26 --- /dev/null +++ b/src/main/java/codingRound/utility/Testbase.java @@ -0,0 +1,206 @@ +package codingRound.utility; + + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.lang.reflect.Method; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.apache.commons.codec.binary.Base64; +import org.openqa.selenium.OutputType; +import org.openqa.selenium.Proxy.ProxyType; +import org.openqa.selenium.TakesScreenshot; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.chrome.ChromeDriver; +import org.openqa.selenium.chrome.ChromeOptions; +import org.openqa.selenium.firefox.FirefoxDriver; +import org.openqa.selenium.firefox.FirefoxProfile; +import org.testng.ISuite; +import org.testng.ITestResult; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.AfterSuite; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.BeforeSuite; +import org.testng.annotations.Listeners; +import org.testng.annotations.Optional; +import org.testng.annotations.Parameters; +import org.testng.annotations.Test; + +import com.relevantcodes.extentreports.ExtentReports; +import com.relevantcodes.extentreports.ExtentTest; +import com.relevantcodes.extentreports.LogStatus; + + + +@Listeners({ SuiteListener.class }) +public class Testbase { + + public static String path; + public static String extentReportFile; + public static ExtentReports extent; + public static Configurations testConfig; + public static String reqBrowser; + public static ExtentTest logger; + public WebDriver driver; + + + @BeforeSuite(alwaysRun = true) + @Parameters({ "browser", "environment", "platformName", "os", "sharedDirectory", + "resultsDir", "tomail" }) + public void InitializeParameters(@Optional String browser, @Optional String environment, + @Optional String platformName, @Optional String os, @Optional String sharedDirectory, + @Optional String resultsdir, + @Optional String tomail) throws IOException { + + testConfig = new Configurations(browser,environment,platformName,os,sharedDirectory,resultsdir,tomail,logger); + reqBrowser = testConfig.getRunTimeProperty("browser"); + + SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd-HH_mm_ss_SSS"); + Date now = new Date(); + String strDate = sdfDate.format(now); + + path = testConfig.getRunTimeProperty("ResultsDir") + testConfig.getRunTimeProperty("fileSeparator") + strDate; + + new File(path).mkdirs(); + extentReportFile = path + testConfig.getRunTimeProperty("fileSeparator") + + testConfig.getRunTimeProperty("reportfilename"); + File file = new File(extentReportFile); + file.createNewFile(); + extent = new ExtentReports(extentReportFile, true); + logger = extent.startTest("Configurations for : " + getSuiteName()); + logger.log(LogStatus.INFO, "Details for starting the suite", + "1. Browser name : " + testConfig.getRunTimeProperty("browser") + "
2. Environment : " + + testConfig.getRunTimeProperty("environment") + "
3. Platform Name : " + + testConfig.getRunTimeProperty("platformName") + "
4. OS : " + + testConfig.getRunTimeProperty("os") + "
5. To Mail : " + + testConfig.getRunTimeProperty("tomail")); + extent.endTest(logger); + } + + @SuppressWarnings("deprecation") + @BeforeMethod(alwaysRun = true) + public void startMethod(Method method) { + Test test = method.getAnnotation(Test.class); + if (test == null) { + return; + } + String class_name = this.getClass().getName(); + logger = extent.startTest("Class_Name : " + class_name + "
" + "Test_Name : " + method.getName() + "
" + + "Test_Desc : " + test.description()); + logger.assignCategory(class_name); + int flag = 1; + try { + + if (testConfig.getRunTimeProperty("platformname").equalsIgnoreCase("desktop")) { + if (reqBrowser.equalsIgnoreCase("notrequired")) { + logger.log(LogStatus.INFO, "Browser required", "No"); + flag = 0; + } else if (testConfig.getRunTimeProperty("os").equalsIgnoreCase("mac")) { + ChromeOptions options = new ChromeOptions(); + options.addArguments("--disable-notifications"); + System.setProperty("webdriver.chrome.driver", testConfig.getRunTimeProperty("SharedDirectory") + + testConfig.getRunTimeProperty("fileSeparator") + "chromedriver"); + + driver = new ChromeDriver(options); + } else if (testConfig.getRunTimeProperty("os").equalsIgnoreCase("windows")) { + if (reqBrowser.equalsIgnoreCase("chrome")) { + System.setProperty("webdriver.chrome.driver", testConfig.getRunTimeProperty("SharedDirectory") + + testConfig.getRunTimeProperty("fileSeparator") + "chromedriver_windows.exe"); + driver = new ChromeDriver(); + } else if (reqBrowser.equalsIgnoreCase("mozilla")) { + System.setProperty("webdriver.gecko.driver", testConfig.getRunTimeProperty("SharedDirectory") + + testConfig.getRunTimeProperty("fileSeparator") + "geckodriver.exe"); + FirefoxProfile profile = new FirefoxProfile(); + profile.setPreference("network.proxy.type", ProxyType.SYSTEM.ordinal()); + driver = new FirefoxDriver(); + } + } + } + + + } catch (Exception e) { + logger.log(LogStatus.FAIL, "Browser Open", e.getLocalizedMessage()); + extent.endTest(logger); + } + + if (flag == 1) { + logger.log(LogStatus.INFO, "Browser Open", "Browser opened successfully"); + driver.manage().window().maximize(); + logger.log(LogStatus.INFO, "Browser Maximize", "Browser maximized sucessfully"); + } + } + + @AfterMethod(alwaysRun = true) + public void endMethod(ITestResult result) throws IOException { + try { + if (result.getStatus() == ITestResult.FAILURE) { + logger.log(LogStatus.FAIL, result.getName() + " : Test case failed due to : ", result.getThrowable()); + + if (!reqBrowser.equalsIgnoreCase("notrequired")) { + File scrf_a = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); + + String encodedBase64 = null; + FileInputStream fileInputStreamReader = null; + try { + fileInputStreamReader = new FileInputStream(scrf_a); + byte[] bytes = new byte[(int) scrf_a.length()]; + fileInputStreamReader.read(bytes); + encodedBase64 = new String(Base64.encodeBase64(bytes)); + + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + String final_file_path = "data:image/png;base64," + encodedBase64; + String image_a = logger.addScreenCapture(final_file_path); + logger.log(LogStatus.FAIL, "Test case failed. Please check - visible image", image_a); + + + } + } else if (result.getStatus() == ITestResult.SUCCESS) { + logger.log(LogStatus.PASS, result.getName() + " : Test case passed"); + } else { + logger.log(LogStatus.SKIP, result.getName() + " : Test case skipped due to : ", result.getThrowable()); + } + + } catch (Exception e) { + logger.log(LogStatus.WARNING, "Final test step failed due to : ", e.toString()); + } finally { + if ((!reqBrowser.equalsIgnoreCase("notrequired")) + && (testConfig.getRunTimeProperty("platformname").equalsIgnoreCase("desktop"))) { + driver.quit(); + logger.log(LogStatus.INFO, "Browser Closed"); + } + extent.endTest(logger); + } + } + + @AfterSuite(alwaysRun = true) + public void dumpParameters() throws IOException { + extent.flush(); + extent.close(); + String bodyData = "1. Browser name : " + testConfig.getRunTimeProperty("browser") + "\n2. Environment : " + + testConfig.getRunTimeProperty("environment") + "\n3. Platform Name : " + + testConfig.getRunTimeProperty("platformName") + "\n4. OS : " + testConfig.getRunTimeProperty("os") + + "\n5. To Mail : " + testConfig.getRunTimeProperty("tomail") + "\n\n PFA report."; + + //code to send mail to given mail id(s) + /*sendmail sendmail = new sendmail(); + sendmail.SendMail(testConfig.getRunTimeProperty("tomail"), testConfig.getRunTimeProperty("replyto"), + "Automation Report : " + getSuiteName(), path, testConfig.getRunTimeProperty("reportemail"), + testConfig.getRunTimeProperty("reportpassword"), bodyData);*/ + } + + public String getSuiteName() { + ISuite suiteListner = SuiteListener.getAccess(); + String runningSuite = suiteListner.getName(); + return runningSuite; + } + + + +} diff --git a/src/test/java/codingRound/cleartrip/FlightBookingTest.java b/src/test/java/codingRound/cleartrip/FlightBookingTest.java new file mode 100644 index 00000000..1b8c95ae --- /dev/null +++ b/src/test/java/codingRound/cleartrip/FlightBookingTest.java @@ -0,0 +1,30 @@ +package codingRound.cleartrip; +import org.testng.annotations.Test; + +import com.relevantcodes.extentreports.LogStatus; + +import codingRound.commonLib.CommonFunctionsLib; +import codingRound.utility.Testbase; + +public class FlightBookingTest extends Testbase{ + + + @Test(description = "to create a new one way booking")//, timeOut = 180000) + + public void oneWayflightBooking() throws Exception { + + CommonFunctionsLib common = new CommonFunctionsLib(); + String filePath = testConfig.getRunTimeProperty("Resources") + testConfig.getRunTimeProperty("fileSeparator") + + testConfig.getRunTimeProperty("dataproviderpath"); + Object[][] bookingDetails = common.readExcel(filePath, "FlightBooking"); + driver.get(testConfig.getRunTimeProperty("environment")); + FlightBooking fb = new FlightBooking(driver, logger); + fb.flightBooking(bookingDetails,testConfig, common); + logger.log(LogStatus.INFO, "one way booking", "One way booking"); + + fb.isResultAppeared( testConfig,common); + logger.log(LogStatus.INFO, "Verify search results", "search result appeared "); + // cs.checkImageStdStory(); + + } +} diff --git a/src/test/java/codingRound/cleartrip/HotelBookingTest.java b/src/test/java/codingRound/cleartrip/HotelBookingTest.java new file mode 100644 index 00000000..7117e52a --- /dev/null +++ b/src/test/java/codingRound/cleartrip/HotelBookingTest.java @@ -0,0 +1,34 @@ +package codingRound.cleartrip; +import com.relevantcodes.extentreports.LogStatus; +import com.sun.javafx.PlatformUtil; + +import codingRound.commonLib.CommonFunctionsLib; +import codingRound.utility.Testbase; + +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.chrome.ChromeDriver; +import org.openqa.selenium.support.FindBy; +import org.openqa.selenium.support.ui.Select; +import org.testng.annotations.Test; + +public class HotelBookingTest extends Testbase{ + +@Test(description = "to create a new hotel booking")//, timeOut = 180000) + + public void hotelBooking() throws Exception { + + CommonFunctionsLib common = new CommonFunctionsLib(); + driver.get(testConfig.getRunTimeProperty("environment")); + HotelBooking hb = new HotelBooking(driver, logger); + hb.hotelBooking(testConfig, common); + logger.log(LogStatus.INFO, "Hotel booking", "Hotel booking successful"); + + //hb.isResultAppeared( testConfig,common); + //logger.log(LogStatus.INFO, "Verify search results", "search result appeared "); + // cs.checkImageStdStory(); + + } + + +} diff --git a/src/test/java/codingRound/cleartrip/SignInTest.java b/src/test/java/codingRound/cleartrip/SignInTest.java new file mode 100644 index 00000000..44bc405f --- /dev/null +++ b/src/test/java/codingRound/cleartrip/SignInTest.java @@ -0,0 +1,32 @@ +package codingRound.cleartrip; +import com.relevantcodes.extentreports.LogStatus; +import com.sun.javafx.PlatformUtil; + +import codingRound.commonLib.CommonFunctionsLib; +import codingRound.utility.Testbase; + +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.chrome.ChromeDriver; +import org.testng.Assert; +import org.testng.annotations.Test; + +public class SignInTest extends Testbase{ + +@Test(description = "To verify sign in error if sign in details are missing")//, timeOut = 180000) + + public void verifySignIn() throws Exception { + + CommonFunctionsLib common = new CommonFunctionsLib(); + driver.get(testConfig.getRunTimeProperty("environment")); + SignIn signin = new SignIn(driver, logger); + signin.signIn(testConfig, common); + logger.log(LogStatus.INFO, "Verify sign in with missing details", "Error message is thrown"); + + //hb.isResultAppeared( testConfig,common); + //logger.log(LogStatus.INFO, "Verify search results", "search result appeared "); + // cs.checkImageStdStory(); + + } + +} diff --git a/testng.xml b/testng.xml new file mode 100644 index 00000000..c744426d --- /dev/null +++ b/testng.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file