Tuesday, 13 October 2015

How to refresh or reload a page in selenium webdriver

Sometimes we need to refresh the web page to ensure that all the elements are loaded. In some of the cases we see that for the first attempt all elements are not loaded but if we load the page for the second time we see that all the components are loaded. Some of the cases we need to load pages more than one times. In that case we use some conditional loops until the components are loaded.
We can refresh the page in many ways. Here we will discuss some of the ways.

Using refresh() method:
Selenium webdriver has a method called refresh(). This is widely used command. It refreshes the current page after executing. 
In Java,
driver.navigate().refresh();
Using sendkeys() method:
sendkeys() method is used like we do page refresh pressing F5 key through our keyboard. This manual task is executed by code using the sendkeys() command over an element.
The command will be like
driver.findElement(By.id(locator)).sendKeys(F5 key);
In Java,
driver.findElement(By.id("gbqfq")).sendKeys(Keys.F5);
Using navigate().to() method:
Actually browsing the same URL using navigate().to() function. We call getCurrentUrl() function to get the current URL of the page.
In Java,
driver.navigate().to(driver.getCurrentUrl());  
Using get() method:
If we know the URL then we can load the same URL again to reload the page. In Java,
driver.get("https://www.google.com.bd/");
We can also use getCurrentUrl() function to know the current URL of the page. The command would be, 
driver.get(driver.getCurrentUrl());
Using sendkeys() method with ASCII code:
We can use ASCII code as argument on sendkeys() method that is equivalent to F5 key command of the keyboard.
driver.findElement(By.id("gbqfq")).sendKeys("\uE035");
Here \uE035 is the ASCII code of F5 key.
 
Using executeScript() method:
Using this command we can execute any JavaScript for our need. If we execute location.reload() JavaScript function then current page will be reloaded which meets our purpose. 
The command is,
driver.executeScript("location.reload()"); 
There are many other ways but these are the generally used ways. I think this will help us.

Tuesday, 6 October 2015

WHAT IS LISTENERS AND EVENTFIRINGWEBDRIVER IN SELENIUM WEBDRIVER

What is Webdriver Listeners-
Hello Welcome to Selenium tutorial in this post we will talk about WebDriver Listener,EventFiringWebDriver and WebDriverEventListener  in detail.
I know all of you might have heard of Listeners but what exactly Listeners is let us discuss today.
In general, terms, Listeners are whom that listen to you and my favorite quotes is “Be a better listener”.

what is listeners in selenium webdriver
If you talk about Webdriver Listener so you should make a note of some classes and interfaces that we will use so will talk about it.
 

1- WebDriverEventListener – This is an interface, which have some predefined methods so we will implement all of these methods.
2-EventFiringWebDriver- This is an class that actually fire Webdriver event.

Why we are using Webdriver Listeners
If you talk about Webdriver we are doing some activity like type, click, navigate etc this is all your events which you are performing on your script so we should have activity which actually will keep track of it.

Take an example if you perform click then what should happen before click and after click.
To capture these events we will add listener that will perform this task for us.
How to implement Listener in our Script
Program for what is listeners in selenium webdriver

Step 1- Create a new Class that will implement WebDriverEventListener methods

package listerDemo;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.events.WebDriverEventListener;

public class ActivityCapture implements WebDriverEventListener {

@Override
public void afterChangeValueOf(WebElement arg0, WebDriver arg1) {

}
@Override
public void afterClickOn(WebElement arg0, WebDriver arg1) {
    System.out.println("After click "+arg0.toString());
}
@Override
public void afterFindBy(By arg0, WebElement arg1, WebDriver arg2) {
    System.out.println("After FindBy "+arg0.toString());
}
@Override
public void afterNavigateBack(WebDriver arg0) {
    System.out.println("After navigating back "+arg0.toString());
}
@Override
public void afterNavigateForward(WebDriver arg0) {
    System.out.println("After navigating forword "+arg0.toString());
}
@Override
public void afterNavigateTo(String arg0, WebDriver arg1) {
    System.out.println("After navigating "+arg0.toString());
    System.out.println("After navigating "+arg1.toString());
}
@Override
public void afterScript(String arg0, WebDriver arg1) {
}
@Override
public void beforeChangeValueOf(WebElement arg0, WebDriver arg1) {
}
@Override
public void beforeClickOn(WebElement arg0, WebDriver arg1) {
    System.out.println("before click "+arg0.toString());
}
@Override
public void beforeFindBy(By arg0, WebElement arg1, WebDriver arg2) {
    System.out.println("before FindBY "+arg0.toString());
}
@Override
public void beforeNavigateBack(WebDriver arg0) {
    System.out.println("Before navigating back "+arg0.toString());
}
@Override
public void beforeNavigateForward(WebDriver arg0) {
    System.out.println("Before navigating Forword "+arg0.toString());
}
@Override
public void beforeNavigateTo(String arg0, WebDriver arg1) {
     System.out.println("Before navigating "+arg0.toString());
     System.out.println("Before navigating "+arg1.toString());
}
@Override
public void beforeScript(String arg0, WebDriver arg1) {
}
@Override
public void onException(Throwable arg0, WebDriver arg1) {
    System.out.println("Testcase done"+arg0.toString());
    System.out.println("Testcase done"+arg1.toString());
}

Let’s Discuss one of these methods

@Override
public void afterClickOn(WebElement arg0, WebDriver arg1) {
    System.out.println(“After click “+arg0.toString());
}

In above method we are simply printing on console and this method will automatically called once click events done. In same way you have to implement on methods.

Note- We generally use Listener to generate log events

Step 2- Now create your simple script, create EventFiringWebDriver object, and pass your driver object.

EventFiringWebDriver event1=new EventFiringWebDriver(driver);

Step 3- Create an object of the class who has implemented all the method of WebDriverEventListener so in our case ActivityCapture is a class who has implemented the same.

ActivityCapture handle=new ActivityCapture();

Step 4- Now register that event using register method and pass the object of ActivityCapture class

event1.register(handle);

We are done now using event1 object write your script so now let us implement the same

Implementation of Webdriver listener

package testcases;
import listerDemo.ActivityCapture;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.events.EventFiringWebDriver;

public class ListnerDemo {
    public static void main(String []args){
    System.out.println("Started");
    WebDriver driver=new FirefoxDriver();
    EventFiringWebDriver event1=new EventFiringWebDriver(driver);
    ActivityCapture handle=new ActivityCapture();
    event1.register(handle);
    event1.navigate().to("http://www.facebook.com");
    event1.findElement(By.id("email")).sendKeys("asdsadsa");
    event1.findElement(By.id("loginbutton")).click();
    event1.quit();
    event1.unregister(handle);
    System.out.println("End");
}

Wednesday, 30 September 2015

Commenly used Assert comparisons

package Flowell_testing;
import org.junit.Ignore;
import org.junit.Test;
import org.testng.Assert;

public class AssertTest {
 
    @Ignore
    @Test
    public void assertBooleanCompare() throws Exception {
        boolean actual = true;
        boolean expected = false;
        Assert.assertEquals(actual, expected);
    }
  
    @Ignore
    @Test
    public void assertStringCompare(){
        String actual = "yes";
        String expected = "no";
        Assert.assertEquals(actual, expected);
    }
   
    @Ignore
    @Test
    public void assertIntCompare(){
        int actual = 10;
        int expected = 10;
        Assert.assertEquals(actual, expected);
    }
   
    @Ignore
    @Test
    public void AssertTrue(){
        boolean status = true;
        Assert.assertTrue(status);
    }
   
    @Test
    public void AssertFalse(){
        boolean status = false;
        Assert.assertFalse(status);
    }
   
}

Monday, 28 September 2015

MOUSE HOVER ACTIONS IN SELENIUM WEBDRIVER

In order to perform a ‘mouse hover’ action, we need to chain all of the actions that we want to achieve in one go. So move to the element that which has sub elements and click on the child item. It should the same way what we do normally to click on a sub menu item.

With the actions object you should first move the menu title, and then move to the sub menu item and click it.

Below is the sample code to perform Mouse hover action

Example 1:

Actions actions = new Actions(driver);
WebElement mainMenu = driver.findElement(By.linkText(“menulink”));
actions.moveToElement(mainMenu);

WebElement subMenu = driver.findElement(By.cssSelector(“subLinklocator”));
actions.moveToElement(subMenu);
actions.click().build().perform();

Example 2:


Actions action = new Actions(webdriver);
WebElement mainMenu = webdriver.findElement(By.linkText(“MainMenu”));
action.moveToElement(mainMenu).moveToElement(webdriver.findElement(By.xpath(“submenuxpath”))).click().build().perform();
There are cases where you may just want to mouse hover on particular element and check if the button state/color is changing after mouse hover.

Below is the example to perform mouse hover

WebElement searchBtn = driver.findElement(By.id(“searchbtn”));

Actions action = new Actions(driver);
action.moveToElement(searchBtn).perform();

BROWSER COMPATIBILITY TESTING USING SELENIUM AND TESTNG

Cross Browser Testing : Is  to check that your web application works as expected in different browsers.If we are using Selenium WebDriver, we can automate test cases using Internet Explorer, FireFox, Chrome, Safari browsers.To execute test cases with different browsers in the same machine at same time we can integrate TestNG with Selenium WebDriver.


Lets create a class Testng_BC.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.Reporter;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class Testng_BC
{
public WebDriver fd;
@Test
@Parameters({“browser”})
public void browserTest(String str) throws Exception
{
if(str.matches(“firefox”))
{

fd=new FirefoxDriver();
fd.get("http://qtpseleniumsolutions.blogspot.in/");
fd.close();

}
if(str.matches(“ie”))
{

//Following code is to set the ie driver with webdriver property.You need IE Driver //server. download from here.
System.setProperty(“webdriver.ie.driver”,”F:\\Selenium_project\\IEDriverServer.exe”);
fd=new InternetExplorerDriver();
fd.get(
"http://qtpseleniumsolutions.blogspot.in/");
fd.close();

}
else {
Reporter.log(“test failed”);
}

}
}

Now create testng.xml file and paste the below code

<suite name=”Suite“>

<test name=”FirefoxTest“>
  <parameter name=”browser“ value=”firefox“ />
<classes>
  <class name=”Testng_BC“ />
  </classes>
  </test>
<test name=”IETest“>
  <parameter name=”browser“ value=”ie“ />
<classes>
  <class name=”Testng_BC“ />
  </classes>
  </test>
  </suite>
To execute a testcase in IE browser we have to use IE Driver server.And you have change few settings.
1.Open IE
2.Go to Tools -> Internet Options -> Security
3.Set all zones to the same protected mode, enabled or disabled should not matter.
Finally, set Zoom level to 100% by right clicking on the gear located at the top right corner and enabling the status-bar. Default zoom level is now displayed at the lower right.
Why are we passing parameters ??
To run the Testng_BC class in multiple browsers, we have to pass the parameters from xml.From parameters in testing.xml we can pass browser name and in test case we can create WebDriver reference accordingly.
Now run the testng.xml file, it should execute ‘browserTest’ in Firefox and  IE Browsers.If you refresh the project and look into test-output folder, a html report (index.html) has been generated.

MOST COMMON EXCEPTIONS WHICH WE NOTICE IN SELENIUM WEBDRIVER.

NoSuchElement : An element could not be located on the page using the given search parameters.


NoSuchFrame : A request to switch to a frame could not be satisfied because the frame could not be found.

StaleElementReference : An element command failed because the referenced element is no longer attached to the DOM.

Firefox Not Connected : Firefox browser upgraded toop new version.

ElementIsNotSelectable : An attempt was made to select an element that cannot be selected.

UnknownCommand : The requested resource could not be found, or a request was received using an HTTP method that is not supported by the mapped resource.

ElementNotVisible : An element command could not be completed because the element is not visible on the page.

InvalidElementState : An element command could not be completed because the element is in an invalid state (e.g. attempting to click a disabled element).

UnknownError : An unknown server-side error occurred while processing the command.

JavaScriptError : An error occurred while executing JavaScript code.

XPathLookupError : An error occurred while searching for an element by XPath.

Timeout : An operation did not complete before its timeout expired.

NoSuchWindow : A request to switch to a different window could not be satisfied because the window could not be found.

InvalidCookieDomain : An illegal attempt was made to set a cookie under a different domain than the current page.

UnableToSetCookie : A request to set a cookie’s value could not be satisfied.

UnexpectedAlertOpen : A modal dialog was open, blocking this operation

NoAlertOpenError : An attempt was made to operate on a modal dialog when one was not open.

ScriptTimeout : A script did not complete before its timeout expired.

InvalidElementCoordinates : The coordinates provided to an interactions operation are invalid.

IMENotAvailable : IME was not available.
IMEEngineActivationFailed : An IME engine could not be started.

InvalidSelector : Argument was an invalid selector (e.g. XPath/CSS).

DATABASE TESTING USING SELENIUM

Generally We don’t have to Test entire database of our application.To my knowledge, We use Selenium to test the Database whether data given in the front end(UI) is as same as the data present in the Database(Back End).

Note: We don’t do negative testing in database.

Here i am using MySql to test the database.
You need to Download Java.sql jar and configure database in your system. I’ll explain database configuration in Upcoming posts.


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;

public class testng_8
{
public WebDriver fd;
@Test
public void method_sql() throws Exception
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection cn=DriverManager.getConnection(“jdbc:mysql:wombat”, “myLogin”, “myPassword”);
Statement st=cn.createStatement();
ResultSet rs= st.executeQuery(“select * from emp”);
try {
while (rs.next())
{
System.out.println(rs.getString(0));

}
cn.close();

}
catch (Exception e)
{
System.out.println(“invalid”);
}

}
}

GENERATE CUSTOMIZED EXCELREPORTS USING TESTNG IN SELENIUM

Download the Jar from here ExcelReportGenerator. Add this Jar into your project BuildPath.

Step1 : Create a Package ‘ExcelResults’ under your Project.

step2 :Create  the testcases which you’d like to automate using TestNg. (by using @Test,BeforeTest,…….) as Shown.

import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;

public class Test_98 {
@Test(priority = 1)
public void VerfyingTestCaseID_001() {
System.out.println(“test”);
System.out.println(“this”);
}

@Test(priority = 2)
public void VerfyingTestCaseID_002() {
System.out.println(“test”);
System.out.println(“this”);
}

@Test(priority = 3)
public void VerfyingTestCaseID_003() {
System.out.println(“test”);
System.out.println(“this”);
}

@Test(priority = 4)
public void VerfyingTestCaseID_004() {
System.out.println(“test”);
System.out.println(“this”);
}

@Test(priority = 5)
public void VerfyingTestCaseID_005() {
System.out.println(“test”);
System.out.println(“this”);
Assert.assertEquals(“validText”, “InvalidText”);
}

@Test(priority = 6)
public void VerfyingTestCaseID_006() {
System.out.println(“test”);
System.out.println(“this”);
}

@Test(priority = 7)
public void VerfyingTestCaseID_007() {
System.out.println(“test”);
System.out.println(“this”);
Assert.assertEquals(“validText”, “InvalidText”);

}

@Test(priority = 8)
public void VerfyingTestCaseID_008() {
System.out.println(“test”);
System.out.println(“this”);
}

@Test(priority = 9)
public void VerfyingTestCaseID_009() {
System.out.println(“test”);
System.out.println(“this”);
}

@Test(priority = 10)
public void VerfyingTestCaseID_010() {
System.out.println(“test”);
System.out.println(“this”);
}

@Test(priority = 11)
public void VerfyingTestCaseID_011() {
System.out.println(“test”);
System.out.println(“this”);
Assert.assertTrue(false);
}

@Test(priority = 12)
public void VerfyingTestCaseID_012() {
System.out.println(“test”);
System.out.println(“this”);
Assert.assertTrue(false);

}

@Test(priority = 13)
public void VerfyingTestCaseID_013() {
System.out.println(“test”);
System.out.println(“this”);
}

@Test(priority = 14)
public void VerfyingTestCaseID_014() {
System.out.println(“test”);
System.out.println(“this”);
}
}

Step3 : Create a testng.xml file under your Project as Shown.

<suite name=”Build 2.0.1?>

<test name=”TestReport”>
<classes>
<class name=”Test_98? />
</classes>
</test>
</suite>

Now Run the testng.xml file.

Step 4 : Now Create a Class ‘ExcelGenerate’  and paste the following code.

import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;
public class ExcelGenerate {

public static void main(String[]args) throws ParserConfigurationException, IOException, SAXException
{
ExcelReportGenerator exe= new ExcelReportGenerator();
exe.GenerateExcelReport(“YourTestName.xlsx”);

System.out.println(“Reports Generated in ExcelResults Package.Please refresh the packages”);

}
}

Step5 :Refresh the Package ‘ExcelResults’

MOST COMMONLY USED METHODS IN YOUR SELENIUM FRAMEWORK.

package utility;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import javax.imageio.ImageIO;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.interactions.internal.Coordinates;
import org.openqa.selenium.internal.Locatable;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Utils {
public static WebDriver driver = null;
public static String browserName = null;

public static WebDriver openFirefoxBrowser() throws Exception {
try {
driver = new FirefoxDriver();
Log.info(“New driver instantiated”);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
Log.info(“Implicit wait applied on the driver for 10 seconds”);
driver.get(Constant.URL);
Log.info(“Web application launched successfully”);

} catch (Exception e) {
Log.error(“Class Utils | Method OpenBrowser | Exception desc : ”
+ e.getMessage());
}
return driver;
}

public static String getBrowserName() {
browserName = System.getProperty(“browser”);

if (browserName == null)
browserName = “ie”;
return browserName;
}

public static WebDriver createWebDriver(String browser) {
System.out.println(“Browser: ” + browser);

switch (browser.toLowerCase()) {
case “ff”:
case “firefox”:
driver = new FirefoxDriver();
break;

case “ch”:
case “chrome”:
System.setProperty(“webdriver.chrome.driver”,
“E://chromedriver.exe”);
driver = new ChromeDriver();
break;

case “ie”:
case “internetexplorer”:
driver = new InternetExplorerDriver();
break;

default:
System.out.println(“Invalid browser name ” + browser);
System.exit(0);
break;
}// switch

driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
driver.manage().timeouts().setScriptTimeout(45, TimeUnit.SECONDS);

return driver;
}

public static void switchToNewWindow() {
Set s = driver.getWindowHandles();
Iterator itr = s.iterator();
String w1 = (String) itr.next();
String w2 = (String) itr.next();
driver.switchTo().window(w2);
}

public static void switchToOldWindow() {
Set s = driver.getWindowHandles();
Iterator itr = s.iterator();
String w1 = (String) itr.next();
String w2 = (String) itr.next();
driver.switchTo().window(w1);
}

public static void switchToParentWindow() {
driver.switchTo().defaultContent();
}

public static WebDriver openIEBrowser() throws Exception {
try {
System.setProperty(“webdriver.ie.driver”, “D:\\IEDriverServer.exe”);
driver = new InternetExplorerDriver();
Log.info(“New driver instantiated”);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
Log.info(“Implicit wait applied on the driver for 10 seconds”);
driver.get(Constant.URL);
driver.navigate()
.to(“javascript:document.getElementById(‘overridelink’).click()”);
Log.info(“Web application launched successfully”);

} catch (Exception e) {
Log.error(“Class Utils | Method OpenBrowser | Exception desc : ”
+ e.getMessage());
}
return driver;
}

/*
* public static String getMethodName() {
*
* String methodName = Thread.currentThread().getStackTrace()[1]
* .getMethodName(); System.out.println(methodName);
*
* return methodName; }
*/

public static void waitForElement(WebElement element) {

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(element));
}

public static void waitTillElementFound(WebElement ElementTobeFound,
int seconds) {
WebDriverWait wait = new WebDriverWait(driver, seconds);
wait.until(ExpectedConditions.visibilityOf(ElementTobeFound));
}

public static void takeScreenshotOfWebelement(WebDriver driver,
WebElement element, String Destination) throws Exception {
File v = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
BufferedImage bi = ImageIO.read(v);
org.openqa.selenium.Point p = element.getLocation();
int n = element.getSize().getWidth();
int m = element.getSize().getHeight();
BufferedImage d = bi.getSubimage(p.getX(), p.getY(), n, m);
ImageIO.write(d, “png”, v);

FileUtils.copyFile(v, new File(Destination));
}

public static void setWindowSize(int Dimension1, int dimension2) {
driver.manage().window().setSize(new Dimension(Dimension1, dimension2));

}

public static void takeScreenshotMethod(String Destination)
throws Exception {
File f = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(f, new File(Destination));
}

public static void pressKeyDown(WebElement element) {
element.sendKeys(Keys.DOWN);
}

public void pressKeyEnter(WebElement element) {
element.sendKeys(Keys.ENTER);
}

public static void pressKeyUp(WebElement element) {
element.sendKeys(Keys.UP);
}

public static void moveToTab(WebElement element) {
element.sendKeys(Keys.chord(Keys.ALT, Keys.TAB));
}

public static void handleHTTPS_IEbrowser() {
driver.navigate().to(
“javascript:document.getElementById(‘overridelink’).click()”);
}

public static void handleHTTPS_Firefox() {
FirefoxProfile profile = new FirefoxProfile();
profile.setAcceptUntrustedCertificates(false);
driver = new FirefoxDriver(profile);
}

public static void waitTillPageLoad(int i) {

driver.manage().timeouts().pageLoadTimeout(i, TimeUnit.SECONDS);

}

public static void clickAllLinksInPage(String destinationOfScreenshot)
throws Exception {

List<WebElement> Links = driver.findElements(By.tagName(“a”));
System.out.println(“Total number of links :” + Links.size());

for (int p = 0; p < Links.size(); p++) {
System.out.println(“Elements present the body :”
+ Links.get(p).getText());
Links.get(p).click();
Thread.sleep(3000);
System.out.println(“Url of the page ” + p + “)”
+ driver.getCurrentUrl());
takeScreenshotMethod(destinationOfScreenshot + p);
navigate_back();
Thread.sleep(2000);
}

}

public static void keyboardEvents(WebElement webelement, Keys key,
String alphabet) {
webelement.sendKeys(Keys.chord(key, alphabet));

}

public static void navigate_forward() {
driver.navigate().forward();
}

public static void navigate_back() {
driver.navigate().back();
}

public static void refresh() {
driver.navigate().refresh();
}

public static void waitMyTime(int i) {
driver.manage().timeouts().implicitlyWait(i, TimeUnit.SECONDS);

}

public static void clearTextField(WebElement element) {
element.clear();

}

public static void clickWebelement(WebElement element) {
try {
boolean elementIsClickable = element.isEnabled();
while (elementIsClickable) {
element.click();
}

} catch (Exception e) {
System.out.println(“Element is not enabled”);
e.printStackTrace();
}
}

public static void clickMultipleElements(WebElement someElement,
WebElement someOtherElement) {
Actions builder = new Actions(driver);
builder.keyDown(Keys.CONTROL).click(someElement)
.click(someOtherElement).keyUp(Keys.CONTROL).build().perform();
}

public static void highlightelement(WebElement element) {
for (int i = 0; i < 4; i++) {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(
“arguments[0].setAttribute(‘style’, arguments[1]);”,
element, “color: solid red; border: 6px solid yellow;”);
js.executeScript(
“arguments[0].setAttribute(‘style’, arguments[1]);”,
element, “”);

}

}

public static boolean checkAlert_Accept() {
try {
Alert a = driver.switchTo().alert();
String str = a.getText();
System.out.println(str);

a.accept();
return true;

} catch (Exception e) {

System.out.println(“no alert “);
return false;

}
}

public static boolean checkAlert_Dismiss() {
try {
Alert a = driver.switchTo().alert();
String str = a.getText();
System.out.println(str);

a.dismiss();
return true;

} catch (Exception e) {

System.out.println(“no alert “);
return false;

}
}

public static void scrolltoElement(WebElement ScrolltoThisElement) {
Coordinates coordinate = ((Locatable) ScrolltoThisElement)
.getCoordinates();
coordinate.onPage();
coordinate.inViewPort();
}

public static void checkbox_Checking(WebElement checkbox) {
boolean checkstatus;
checkstatus = checkbox.isSelected();
if (checkstatus == true) {
System.out.println(“Checkbox is already checked”);
} else {
checkbox.click();
System.out.println(“Checked the checkbox”);
}
}

public static void radiobutton_Select(WebElement Radio) {
boolean checkstatus;
checkstatus = Radio.isSelected();
if (checkstatus == true) {
System.out.println(“RadioButton is already checked”);
} else {
Radio.click();
System.out.println(“Selected the Radiobutton”);
}
}

// Unchecking
public static void checkbox_Unchecking(WebElement checkbox) {
boolean checkstatus;
checkstatus = checkbox.isSelected();
if (checkstatus == true) {
checkbox.click();
System.out.println(“Checkbox is unchecked”);
} else {
System.out.println(“Checkbox is already unchecked”);
}
}

public static void radioButton_Deselect(WebElement Radio) {
boolean checkstatus;
checkstatus = Radio.isSelected();
if (checkstatus == true) {
Radio.click();
System.out.println(“Radio Button is deselected”);
} else {
System.out.println(“Radio Button was already Deselected”);
}
}

public static void dragAndDrop(WebElement fromWebElement,
WebElement toWebElement) {
Actions builder = new Actions(driver);
builder.dragAndDrop(fromWebElement, toWebElement);
}

public static void dragAndDrop_Method2(WebElement fromWebElement,
WebElement toWebElement) {
Actions builder = new Actions(driver);
Action dragAndDrop = builder.clickAndHold(fromWebElement)
.moveToElement(toWebElement).release(toWebElement).build();
dragAndDrop.perform();
}

public static void dragAndDrop_Method3(WebElement fromWebElement,
WebElement toWebElement) throws InterruptedException {
Actions builder = new Actions(driver);
builder.clickAndHold(fromWebElement).moveToElement(toWebElement)
.perform();
Thread.sleep(2000);
builder.release(toWebElement).build().perform();
}

public static void hoverWebelement(WebElement HovertoWebElement)
throws InterruptedException {
Actions builder = new Actions(driver);
builder.moveToElement(HovertoWebElement).perform();
Thread.sleep(2000);

}

public static void doubleClickWebelement(WebElement doubleclickonWebElement)
throws InterruptedException {
Actions builder = new Actions(driver);
builder.doubleClick(doubleclickonWebElement).perform();
Thread.sleep(2000);

}

public static String getToolTip(WebElement toolTipofWebElement)
throws InterruptedException {
String tooltip = toolTipofWebElement.getAttribute(“title”);
System.out.println(“Tool text : ” + tooltip);
return tooltip;
}

public static void selectElementByNameMethod(WebElement element, String Name) {
Select selectitem = new Select(element);
selectitem.selectByVisibleText(Name);
}

public static void selectElementByValueMethod(WebElement element,
String value) {
Select selectitem = new Select(element);
selectitem.selectByValue(value);
}

public static void selectElementByIndexMethod(WebElement element, int index) {
Select selectitem = new Select(element);
selectitem.selectByIndex(index);
}

public static void clickCheckboxFromList(String xpathOfElement,
String valueToSelect) {

List<WebElement> lst = driver.findElements(By.xpath(xpathOfElement));
for (int i = 0; i < lst.size(); i++) {
List<WebElement> dr = lst.get(i).findElements(By.tagName(“label”));
for (WebElement f : dr) {
System.out.println(“value in the list : ” + f.getText());
if (valueToSelect.equals(f.getText())) {
f.click();
break;
}
}
}
}

public static void downloadFile(String href, String fileName)
throws Exception {
URL url = null;
URLConnection con = null;
int i;
url = new URL(href);
con = url.openConnection();
File file = new File(“.//OutputData//” + fileName);
BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(file));
while ((i = bis.read()) != -1) {
bos.write(i);
}
bos.flush();
bis.close();
}

public static void navigateToEveryLinkInPage() throws InterruptedException {

List<WebElement> linksize = driver.findElements(By.tagName(“a”));
int linksCount = linksize.size();
System.out.println(“Total no of links Available: ” + linksCount);
String[] links = new String[linksCount];
System.out.println(“List of links Available: “);
// print all the links from webpage
for (int i = 0; i < linksCount; i++) {
links[i] = linksize.get(i).getAttribute(“href”);
System.out.println(linksize.get(i).getAttribute(“href”));
}
// navigate to each Link on the webpage
for (int i = 0; i < linksCount; i++) {
driver.navigate().to(links[i]);
Thread.sleep(3000);
System.out.println(driver.getTitle());
}
}
}

Sunday, 13 September 2015

Selenium - Capture videos

Configuration

Step 1 : Navigate to the URL - http://www.randelshofer.ch/monte/index.html and download the screen recorder JAR.

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.awt.*;

import org.apache.commons.io.FileUtils;

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.By;

import org.monte.media.math.Rational;
import org.monte.media.Format;
import org.monte.screenrecorder.ScreenRecorder;

import static org.monte.media.AudioFormatKeys.*;
import static org.monte.media.VideoFormatKeys.*;


public class webdriverdemo
{
   private static ScreenRecorder screenRecorder;
   public static void main(String[] args) throws IOException, AWTException
   {
      GraphicsConfiguration gconfig = GraphicsEnvironment
         .getLocalGraphicsEnvironment()
         .getDefaultScreenDevice()
         .getDefaultConfiguration();
      
      screenRecorder = new ScreenRecorder(gconfig,
         new Format(MediaTypeKey, MediaType.FILE, MimeTypeKey,
         MIME_AVI),
         new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey,
         ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
         CompressorNameKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
         DepthKey, (int)24, FrameRateKey, Rational.valueOf(15),
         QualityKey, 1.0f,
         KeyFrameIntervalKey, (int) (15 * 60)),
         new Format(MediaTypeKey, MediaType.VIDEO,
         EncodingKey,"black",
         FrameRateKey, Rational.valueOf(30)), null);
      
      WebDriver driver = new FirefoxDriver();
      
      // Start Capturing the Video
      screenRecorder.start();
      
      // Puts an Implicit wait, Will wait for 10 seconds before throwing exception
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      
      // Launch website
      driver.navigate().to("http://www.calculator.net/");
      
      // Maximize the browser
      driver.manage().window().maximize();
      
      // Click on Math Calculators
      driver.findElement(By.xpath(".//*[@id='menu']/div[3]/a")).click();
      
      // Click on Percent Calculators
      driver.findElement(By.xpath(".//*[@id='menu']/div[4]/div[3]/a")).click();
      
      // Enter value 10 in the first number of the percent Calculator
      driver.findElement(By.id("cpar1")).sendKeys("10");
      
      // Enter value 50 in the second number of the percent Calculator
      driver.findElement(By.id("cpar2")).sendKeys("50");
      
      // Click Calculate Button
      driver.findElement(By.xpath(".//*[@id='content']/table/tbody/tr/td[2]/input")).click();
      
      // Get the Result Text based on its xpath
      String result = driver.findElement(By.xpath(".//*[@id='content']/p[2]/span/font/b")).getText();

      File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
      FileUtils.copyFile(screenshot, new File("D:\\screenshots\\screenshots1.jpg"));

      // Print a Log In message to the screen
      System.out.println(" The Result is " + result);
      
      // Close the Browser.
      driver.close();
      
      // Stop the ScreenRecorder
      screenRecorder.stop();
   }
}

Log4j file work.

Jar : log4j-1.2.17.jar to be add.
log4j.xml  :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">

   <appender name="fileAppender" class="org.apache.log4j.FileAppender">
      <param name="Threshold" value="INFO" />
      <param name="File" value="NewGenerated
LogFile.log"/>
      <param name="Append" value="flase" />
      <layout class="org.apache.log4j.PatternLayout">
         <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss}  [%c] (%t:%x) %m%n" />
      </layout>
   </appender>

   <root>
   <level value="INFO"/>
      <appender-ref ref="fileAppender"/>
   </root>
  
</log4j:configuration>


Log4j.java
package testing;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
import org.junit.Test;

public class Log4j {
    static final Logger logger = LogManager.getLogger(Log4j.class.getName());
   
    @Test
    public void logTest(){
        DOMConfigurator.configure("log4j.xml");
       
        logger.info("# # # # # # # # # # # #  # # # # # # # # # # # # # ");
        logger.info("TEST Has Started");
    }
}

Selenium - Find all Links

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;

public class getalllinks {

   public static void main(String[] args){
  
      WebDriver driver = new FirefoxDriver();
      driver.navigate().to("http://www.calculator.net");
      java.util.List<WebElement> links = driver.findElements(By.tagName("a"));
      System.out.println("Number of Links in the Page is " + links.size());
     
      for (int i = 1; i<=links.size(); i=i+1) {
         System.out.println("Name of Link# " + i - + links.get(i).getText());
         }
      }
   }

Selenium - Multi Select Action

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.interactions.Action;

public class webdriverdemo {

   public static void main(String[] args) throws InterruptedException {
  
      WebDriver driver = new FirefoxDriver();
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

      driver.navigate().to("http://demos.devexpress.com/aspxeditorsdemos/ListEditors/MultiSelect.aspx");

      //driver.manage().window().maximize();
      driver.findElement(By.id("ContentHolder_lbSelectionMode_I")).click();
      driver.findElement(By.id("ContentHolder_lbSelectionMode_DDD_L_LBI1T0")).click();
      Thread.sleep(5000);
     
      // Perform Multiple Select
      Actions builder = new Actions(driver);
      WebElement select = driver.findElement(By.id("ContentHolder_lbFeatures_LBT"));
      List<WebElement> options = select.findElements(By.tagName("td"));
     
      System.out.println(options.size());
      Action multipleSelect = builder.keyDown(Keys.CONTROL).click(options.get(2)).click(options.get(4)).click(options.get(6)).build();
     
      multipleSelect.perform();
      driver.close();
   }
}

Selenium - Drag & Drop

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.interactions.Action;

public class webdriverdemo {

   public static void main(String[] args) throws InterruptedException{
  
      WebDriver driver = new FirefoxDriver();
      //Puts a Implicit wait, Will wait for 10 seconds before throwing exception
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
     
      // Launch website
      driver.navigate().to("http://www.keenthemes.com/preview/metronic/templates/admin/ui_tree.html");
      driver.manage().window().maximize();
     
      WebElement From = driver.findElement(By.xpath(".//*[@id='j3_7']/a"));
      WebElement To = driver.findElement(By.xpath(".//*[@id='j3_1']/a"));
     
      Actions builder = new Actions(driver);
      Action dragAndDrop = builder.clickAndHold(From).moveToElement(To).release(To).build();
     
      dragAndDrop.perform();
      driver.close();
      }
   }

Thursday, 3 September 2015

Multi Touch Using Selendroid

Single Finger Example:
TouchAction ta = new TouchActionBuilder().pointerDown().
pointerMove(x, y).pointerUp().build();
ta.perform(driver);

Multi Finger Example (these will be executed in parallel):
TouchAction finger1 = new TouchActionBuilder().pointerDown().pause(100).
  pointerMove(x, y).pointerUp().build();
TouchAction finger2 = new   TouchActionBuilder().pointerDown().pause(100).
  pointerMove(x, y).pointerUp().build();
MultiTouchAction multiAction = new MultiTouchAction(finger1, finger2);
multiAction.perform(driver);

Flick the page using selendroid.

#Please import: org.openqa.selenium.interactions.touch.TouchActions
WebElement pages = driver.findElement(By.id("vp_pages"));
TouchActions flick = new TouchActions(driver).flick(pages, -100, 0, 0);
flick.perform();



Saturday, 29 August 2015

Roles and Responsibilities of a Software Tester/ Lead

1. Be updated on the latest testing techniques, strategies, testing tools/ test frameworks and so on
2. Be aware of the current and upcoming projects in the organization
3. Review and analyze the project requirements
4. Plan and organize the knowledge transfer to the Software Test Engineers and self
5. Collect the queries related to the requirements and get them resolved by the business person (e.g. the client, business analyst, product manager or project manager) assigned to the project
6. Plan, organize and lead the testing kick-off meeting
7. Scope the required tests
8. Design the required test strategy in line with the scope and organization standards
9. Create the software test plan, get it reviewed and approved/ signed-off by the relevant stakeholders
10. Evaluate and identify the required test automation and test management tools
11. Estimate the test effort and team (size, skills, attitude and schedule)
12. Create the test schedule (tasks, dependencies and assigned team members)
13. Identify the training requirements of the Software Test Engineers
14. Identify any test metrics to be gathered
15. Communicate with the client or on site/ offshore team members, as required
16. Review the test cases and test data generated by the Software Test Engineers and get them to address the review comments
17. Track the new/ updated requirements in the project and modify testing artifacts accordingly
18. Determine, procure, control, maintain and optimize the test environment (hardware, software and network)
19. Get information on the latest releases/ builds from the development team/ the client
20. Create and maintain the required test automation framework(s)
21. Administer the project in the test management system
22. Administer the Application under test (e.g. add users for the tests), as required
23. Assign tasks to the Software Test Engineers based on the software test plan
24. Check the status of each assigned task daily and resolve any issues faced by the team members with their tasks
25. Ensure that each team member is optimally occupied with work (i.e. each Software Test Engineer should not be too overloaded or too idle)
26. Re-assign the testing tasks, as required
27. Track the assigned tasks with respect to the software test plan and the project schedule
28. Review the test automation created by the Software Test Engineers and get them to address the review comments
29. Own and maintain the test automation suite of the project
30. Schedule and execute the test automation on the project
31. Review defect reports  and assign valid defects to the relevant developer/ development manager
32. Assign returned defect reports and assist the concerned Software Test Engineer, as required
33. Ensure the resolved defects are re-tested
34. Consolidate and report test results to the concerned stakeholders
35. Be approachable and available to the Software Test Engineers, as required by them
36. Update the software test plan, as required
37. Ensure that the test cases are updated by the Software Test Engineers, as required
38. Ensure that the test automation is updated based on the updated test cases
39. Gather the decided test metrics
40. Escalate and obtain resolution of the issues related to the test environment and team
41. Plan, organize and lead team meetings and ensure action is taken based on the team discussions
42. Plan and organize training for the Software Test Engineers
43. Review the status reports of the Software Test Engineers
44. Review the time logged by the Software Test Engineers for various activities
45. Report the status to the stakeholders (e.g. the client, project manager/ test manager and the management)
46. Keep the Software Test Engineers motivated
47. Improve the test process based on the suggestions by others and own judgment
48. Manage own energy level and time


**********************************************************
Responsibilities of a Software Test Engineer :
 

1. Go through the software requirements and get clarifications on one’s doubts (learn using my video on Requirement Analysis)
2. Become familiar with the software under test and any other software related to it
3. Understand the master test plan and/ or the project plan
4. Create or assist in creating own test plan
5. Generate test cases based on the requirements and other documents
6. Procure or create test data required for testing
7. Set up the required test beds (hardware, software and network)
8. Create or assist in creating assigned test automation
9. Test software releases by executing assigned tests (manual and/ or automated)
10. Report defects (usually in a defect database) to the stakeholders
11. Create test logs
12. Report test results to the stakeholders
13. Reply to returned bug reports (for example, when a bug report is returned as not reproducible)
14. Re-test resolved defects
15. Update test cases based on the discovered defects
16. Update test automation based on the updated test cases
17. Provide inputs to the team in order to improve the test process
18. Log own time in the project management software or time tracking system
19. Report work progress and any problems faced to the Test Lead or Project Manager as required
20. (If applicable) Support the team with testing tasks as required
21. Keep himself/ herself up-to-date on the overview of the development technology, the popular testing tools (e.g. automated testing tools and test management systems) and the overview of the business domain 


**********************************************************
1. Prepare Software QA Test Plan.
2. Estimate and review QA efforts as part of the overall development effort Check / Review QA artefacts
3. System, Integration and User Acceptance prepared by test engineers.
4. Get involved in analysing requirements during the requirements analysis phase of projects.
5. Keep track of the new requirements from the Project.
6. Forecast / Estimate the Project future requirements.
7. Arrange the Hardware and software requirement for the Test Setup.
8. Develop and implement test strategies.
9. Escalate the issues about project requirements (Software, Hardware, Resources) to Project Manager / QA Lead
10. Assign task to other QA Team members and ensure that all of them have sufficient work in the project.
11. Attend the regular client call and discuss the weekly status with the project leadership team.
12. Track and report upon testing activities, including testing results, test case coverage, required resources, defects discovered and their status, performance baselines, etc.
13. Assist in performing any applicable maintenance to tools used in Testing and resolve issues if any.
14. Ensure content and structure of all Testing documents / artefacts is documented and maintained.
15. Document, implement, monitor, and enforce all processes and procedures for testing is established as per standards defined by the organization.
16. Review various reports prepared by QA Engineers.
17. Log project related issues in the defect tracking tool identified for the project.
18. Check for timely delivery of different milestones.
19. Identify Training requirements and forward it to the Project 

Manager/QA Lead 

**********************************************************
 
1) Analyzing the Requirements from the client
2) Participating in preparing Test Plans
3) Preparing Test Scenarios
4) Preparing Test Cases for module, integration and system testing
5) Preparing Test Data’s for the test cases
6) Preparing Test Environment to execute the test cases
7) Analyzing the Test Cases prepared by other team members
8) Executing the Test Cases
9) Defect Tracking
10) Giving mandatory information of a defect to developers in order to fix it
11) Preparing Summary Reports
12) Preparing Lesson Learnt documents from the previous project testing experience
13) Preparing Suggestion Documents to improve the quality of the application
14) Communication with the Test Lead / Test Manager
15) Conducting Review Meetings within the Team


Monday, 17 August 2015

Page scroll up/Down in Selenium.

Using Selenium RC1
selenium.getEval("window.scrollTo(0,0)");

Using WbdDriver
Scroll down:
WebDriver driver = new FirefoxDriver();                JavascriptExecutor jse = (JavascriptExecutor)driver; jse.executeScript("window.scrollBy(0,250)", "");
or, you can do as follows:
jse.executeScript("scroll(0, 250);");

For Scroll up:
jse.executeScript("window.scrollBy(0,-250)", ""); OR, jse.executeScript("scroll(0, -250);");

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