Friday 14 August 2015

Different exceptions you got when working with WebDriver ?

1. ElementNotVisibleException,
2. ElementNotSelectableException, 
3. NoAlertPresentException, 
4. NoSuchAttributeException,
5. NoSuchWindowException, 
6. TimeoutException, 
7. WebDriverException etc.

Monday 10 August 2015

Right click on the mouse.

package test;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;

public class RightClick {

    @Test
    public void rightClicktest(){
        WebDriver driver = new FirefoxDriver();
        driver.navigate().to("http://www.google.com");
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
       
        WebDriverWait wait = new WebDriverWait(driver, 60);
        wait.until(ExpectedConditions.presenceOfElementLocated(By.id("lst-ib")));
       
        WebElement element = driver.findElement(By.id("lst-ib"));
        element.sendKeys("");
        element.click();
       
        Actions actObj = new Actions(driver);
        actObj.contextClick(element).sendKeys(Keys.ARROW_DOWN).
            sendKeys(Keys.ARROW_DOWN).
            sendKeys(Keys.ARROW_DOWN).
            sendKeys(Keys.ARROW_DOWN).
            sendKeys(Keys.RETURN).perform();

    }
}

SELENDROID automation code for execting the Android application (.Apk)


//ApkName ====spsbranch.apk
//Version   =====com.youtility.attendance.ui:16.0.1


package nativeui;

import java.sql.Timestamp;
import io.selendroid.SelendroidDriver;
import io.selendroid.common.SelendroidCapabilities;
import io.selendroid.standalone.SelendroidConfiguration;
import io.selendroid.standalone.SelendroidLauncher;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import xlsx.work.Excel_ReadAndWrite;

public class SIteAuditSyncChechk {
    SendingEmail emailObj = new SendingEmail();
    Excel_ReadAndWrite excelrwObj = new Excel_ReadAndWrite();
    SelendroidLauncher selendroidServer = null;
    WebDriver driver = null;
    WebDriverWait wait;
   
    String syncSuccessMsg = "Synchronization successful!", actualSyncMsg;
    String errorMsg = "";
    int excelRowCount;
    String syncStatus = "";
   
    public void excelConfig(){
        String path = "InputData/AppInfo.xlsx";
        excelrwObj.fis_setXlsFilePath(path);
        excelrwObj.fis_setFileConfig();
        excelrwObj.fis_setWorkBookConfig();
        excelrwObj.fis_setWorkSheetConfig("SiteAuditInfo");
        excelRowCount = excelrwObj.fis_getRowCount();
        System.out.println("Row count : "+excelRowCount);
    }
    SelendroidCapabilities caps;
    public void appConfigaration(int i) throws Exception{
        try {
            SelendroidConfiguration config = new SelendroidConfiguration();
            config.addSupportedApp("src/resources/"+excelrwObj.fis_getCellValueByColumnName(i, "ApkName"));
            selendroidServer = new SelendroidLauncher(config);
            selendroidServer.launchSelendroid();
            caps = new SelendroidCapabilities (excelrwObj.fis_getCellValueByColumnName(i, "Version"));
            try {
                driver = new SelendroidDriver(caps);
                wait = new WebDriverWait(driver, 60);
            } catch (Exception e) {
                e.printStackTrace();
                errorMsg = errorMsg + e;
            }
        } catch (Exception e) {
            System.out.println("Error :- Unable to configure and launch the Application.");
            errorMsg = errorMsg + e;
            e.printStackTrace();
        }
        if(!driver.findElement(By.xpath("//EditText[@id='server_url']")).isDisplayed()){
            driver = new SelendroidDriver(caps);
            System.out.println("Second attempt.");
        }
    }
   
    public void appServerDetailsEnter(int i){
        try {
            driver.findElement(By.xpath("//EditText[@id='server_url']")).clear();
            driver.findElement(By.xpath("//EditText[@id='server_url']")).sendKeys(excelrwObj.fis_getCellValueByColumnName(i, "serverURL"));
            driver.findElement(By.xpath("//*[@id='server_db']")).clear();
            driver.findElement(By.xpath("//*[@id='server_db']")).sendKeys(excelrwObj.fis_getCellValueByColumnName(i, "DatabaseName"));
            driver.navigate().back();
            driver.findElement(By.xpath("//Button[@value='Save']")).click();
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//EditText[@id='username']")));
        } catch (Exception e) {
            System.out.println("Error :- Unable to set the server configaration to Application.");
            errorMsg = errorMsg + e;
            e.printStackTrace();
        }
    }
    public void appLogin(int i){
        try {
            driver.findElement(By.xpath("//EditText[@id='username']")).clear();
            driver.findElement(By.xpath("//EditText[@id='username']")).sendKeys(excelrwObj.fis_getCellValueByColumnName(i, "userid"));
            driver.findElement(By.xpath("//EditText[@id='password']")).clear();
            driver.findElement(By.xpath("//EditText[@id='password']")).sendKeys(excelrwObj.fis_getCellValueByColumnName(i, "password"));
            driver.navigate().back();
            driver.findElement(By.xpath("//Button[@id='btnLogin']")).click();
        } catch (Exception e) {
            System.out.println("Error :- Unable to login into Application.");
            errorMsg = errorMsg + e;
            e.printStackTrace();
        }
    }
    long estimatedTime = 0;
    public void syncStatus(){
        long startTime = System.nanoTime();
        System.out.println("StartTime in nano seconds : "+startTime);
        try {
            wait = new WebDriverWait(driver, 10000);
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//Button[@id='button1']")));
            estimatedTime = System.nanoTime() - startTime;
            actualSyncMsg = driver.findElement(By.xpath("//TextView[@id='message']")).getText().trim();
            System.out.println("Message : "+actualSyncMsg);
            if(actualSyncMsg.equalsIgnoreCase(syncSuccessMsg)) syncStatus = "True";
            driver.findElement(By.xpath("//Button[@id='button1']")).click();
        } catch (Exception e) {
            System.out.println("Error :- Unable to validate the synchronization.");
            errorMsg = errorMsg + e;
            e.printStackTrace();
        }
        System.out.println("EstimatedTime in nano seconds : "+estimatedTime);
    }
    public void appDataClear(){
         try {
            driver.quit();
            selendroidServer.stopSelendroid();
        } catch (Exception e) {
            System.out.println("Error :-  Unable to clear the application data");
            errorMsg = errorMsg + e;
            e.printStackTrace();
        }
    }
    public void statusUpdateInExcel(int i){
        if(syncStatus.equalsIgnoreCase("True")) excelrwObj.fis_setCellValueAndColorByColumnName(i, "LastExeStatus", "Success", IndexedColors.GREEN, IndexedColors.WHITE);
        else excelrwObj.fis_setCellValueAndColorByColumnName(i, "LastExeStatus", "Fail", IndexedColors.RED, IndexedColors.WHITE);
        java.util.Date date= new java.util.Date();
        excelrwObj.fis_setCellValueByColumnName(i, "SyncConsumedTime", ""+estimatedTime);
        excelrwObj.fis_setCellValueByColumnName(i, "ActualMessage", actualSyncMsg);
        excelrwObj.fis_setCellValueByColumnName(i, "ErrorLog", errorMsg);
        excelrwObj.fis_fileSaveAndClose();
        emailObj.mailSending(excelrwObj, i);
    }
   
   
   
    @Test
    public void siteAuditAppSyncCheck(){
        excelConfig();
        for (int i = 2; i <= excelRowCount; i++) {
            actualSyncMsg = "Error"; syncStatus = "False";
            try {
                if(!excelrwObj.fis_getCellValueByColumnName(i, "ExeStatus").equalsIgnoreCase("Yes")) continue;
                appConfigaration(i);
                appServerDetailsEnter(i);
                appLogin(i);
                syncStatus();
                appDataClear();
                statusUpdateInExcel(i);
            } catch (Exception e) {
                appDataClear();
                errorMsg = errorMsg + e;
                statusUpdateInExcel(i);
                e.printStackTrace();
                System.out.println("Error :- Unable to validate the Application sync");
            }
            /*driver.quit();
            selendroidServer.stopSelendroid();*/
        }
    }//Test closed
}//Class closed








How to Handle Alerts, JavaScript Alerts and PopUp Boxes in Selenium WebDriver

Alerts are different from regular windows. The main difference is that alerts are blocking in nature. They will not allow any action on the underlying webpage if they are present. So if an alert is present on the webpage and you try to access any of the element in the underlying page you will get following exception:
UnhandledAlertException: Modal dialog present

To reproduce this exception you can use this code:

    public static void main(String[] args)
    {
        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.toolsqa.com/handling-alerts-using-selenium-webdriver/");
        //This step will result in an alert on screen
        driver.findElement(By.xpath("//*[@id='content']/p[4]/button")).click();

        //Once alert is present try to click on any button on the page
        driver.findElement(By.xpath("//*[@id='content']/p[16]/button")).click();

    }
 

Types of Alerts:
Java scrip provides mainly following three types of alerts:
1. Simple alert
document.alert("This is a simple alert");
//or
alert("This is a simple alert");

2. Confirmation alert
var popuResult = confirm("Confirm pop up with OK and Cancel button");

3. Prompt alert
var person = prompt("Do you like toolsqa?", "Yes/No");


Handling alerts using Selenium WebDriver:
Selenium provides us with an interface called Alert. It is present in the org.openqa.selenium.Alert package. Alert interface gives us following methods to deal with the alert:

accept() To accept the alert
dismiss() To dismiss the alert
getText() To get the text of the alert
sendKeys() To write some text to the alert
Lets use these to handle the above mentioned types of alerts one by one.

Simple alert:
Simple alerts just have a OK button on them. They are mainly used to display some information to the user. The first alert on our test page is a simple alert. Following code will read the text from the Alert and then accept the alert. Important point to note is that we can switch from main window to an alert using the driver.switchTo().alert(). Below is the usage of that also:

    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.toolsqa.com/handling-alerts-using-selenium-webdriver/");
        driver.manage().window().maximize();
        // This step will result in an alert on screen
        driver.findElement(By.xpath("//*[@id='content']/p[4]/button")).click();

        Alert simpleAlert = driver.switchTo().alert();
        String alertText = simpleAlert.getText();
        System.out.println("Alert text is " + alertText);
        simpleAlert.accept();
    }


Confirmation Alert:
This alert comes with an option to accept or dismiss the alert. To accept the alert you can use Alert.accept() and to dismiss you can use the Alert.dismiss(). Here is the code to dismiss a prompt alert.

    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.toolsqa.com/handling-alerts-using-selenium-webdriver/");
        driver.manage().window().maximize();
        // This step will result in an alert on screen
        WebElement element = driver.findElement(By.xpath("//*[@id='content']/p[11]/button"));
        ((JavascriptExecutor) driver).executeScript("arguments[0].click()", element);

        Alert confirmationAlert = driver.switchTo().alert();
        String alertText = confirmationAlert.getText();
        System.out.println("Alert text is " + alertText);
        confirmationAlert.dismiss();
    }


Prompt Alerts:
In prompt alerts you get an option to add text to the alert box. This is specifically used when some input is required from the user. We will use the sendKeys() method to type something in the Prompt alert box. Here is the code


    public static void main(String[] args) throws InterruptedException {
        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.toolsqa.com/handling-alerts-using-selenium-webdriver/");
        driver.manage().window().maximize();
        // This step will result in an alert on screen
        WebElement element = driver.findElement(By.xpath("//*[@id='content']/p[16]/button"));
        ((JavascriptExecutor) driver).executeScript("arguments[0].click()", element);

        Alert promptAlert  = driver.switchTo().alert();
        String alertText = promptAlert .getText();
        System.out.println("Alert text is " + alertText);
        //Send some text to the alert
        promptAlert .sendKeys("Accepting the alert");
        Thread.sleep(4000); //This sleep is not necessary, just for demonstration
        promptAlert .accept();
    }