Saturday, 19 October 2013

Data Driven Testing in WebDriver Using jxl

Data Driven Testing through WebDriver using jxl
Prerequisite 
1- Download jxl jar file and add it in to path
2- Junit jar file
3- Selenium-server-standalone-2.x.jar
Add these three jar file in build path  .
In general when we say Data Driven then only thing that should come in to mind is thatinput is going to be read from some xls file, xml,csv or some other table oriented file and might be output would also be written in xls,xml or csx file. All read data from various files are stored in variables and finally used by scripts to run the test cases.
Data Driven testing is mainly divided in two part
1- Reading data and storing in to variable
2- Using data stored in variable in to some generic script.
Reading Data and storing in to variableSince Webdriver don’t have structure like other automation tools like QTP to have its own Data table to store data to run tests in Data Driven framework. So we normally two jar file(Binaries) JXL(Java Excel API) and Apache POI to make Data Driven test framework for  WebDriver.
I am using JXL binary in this example. so for reading data from xls file we need to follow these step
1- Opening Excel file , so to open excel file we would use these two line. I have created one excel file r.xls and now we would write code to reach to this file and to open this excel sheet.
import java.io.FileInputStream;
import jxl.Workbook;
FileInputStream fi = new FileInputStream(“C:\\Users\\kaushal\\Desktop\\r.xls”);
Workbook w = Workbook.getWorkbook(fi);
In above code
FileInputStream obtains input bytes from a file in a file system
2- Opening worksheet
import jxl.Sheet;
Sheet sh = w.getSheet(0); or w.getSheet(Sheetnumber)
Here 0 as argument states about firest sheet, if we want to read second sheet then we may use 1 in place of 0
3- Reading data
code used is 
String variable1 = s.getCell(column, row).getContents();
These are 3 steps that is used in reading data from excel sheet
In my example or code I am going to write code to test login to Gmail for various user and Username and Password is save in excel sheet and we will keep reading this data by using loop and we would store these data in two variable username and password
package learing;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import jxl.JXLException;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Data{
public static void main(String args[]) throws IOException, JXLException,BiffException,FileNotFoundException, InterruptedException{   
WebDriver driver = new FirefoxDriver();
Sheet s;

FileInputStream fi = new FileInputStream("D:\\data1.xls");
System.out.println("Brahmi");
Workbook w = Workbook.getWorkbook(fi);
s = w.getSheet(0);
for(int row=1; row <=s.getRows();row++)
{
String username = s.getCell(0, row).getContents();
System.out.println("Username "+username);
driver.get("http://www.gmail.com");
driver.findElement(By.name("Email")).sendKeys(username);
String password= s.getCell(1, row).getContents();
System.out.println("Password "+password);
driver.findElement(By.name("Passwd")).sendKeys(password);
Thread.sleep(10000);
driver.findElement(By.name("signIn")).click();
 System.out.println("Waiting for page to load fully...");
Thread.sleep(30000);
}
driver.quit();
}

}

Important set of test cases for Login Page

Here is the set of test cases that would help you in getting the right job with a better understanding of a login page.
  • Test with correct username and password: This is the most basic positive test cases, while using this user should successfully logged in.If correct username and password is not helping you to login in to your application then file a bug because this shows that something is wrong with application.
  • Test with incorrect username or password: access should be denied
  • Test with correct username and empty password:  In this case when user click on login button then a message should flash that says “Enter a password or something unexpected went wrong”
  • Test with empty username and correct password: Again an error message should appear to enter a valid email or username
  • Verify the correct error messages like  Incorrect combination of user name and password. If you are getting anything like Incorrect username or Incorrect password then be conscious because you application is giving half the information to hacker and your application is in great danger.
  • Verify that back button is not able to push you to your logged in page just after you logout from your specific account:  This kind of test cases invoke the flaw associated with Session management. When session is not closed just after your log-out means any one can access you account if you have opened your specific login enabled account at any time just by clicking Back button in Browser.So one way to save your account from such misconducts is to close browser when ever you log-out from your account.
  • Test a page url without login to application: For such thing login with correct username and correct password and go to certain page, copy the url and paste the same in another browser.if you are able to open the page then this application is not in good shape to protect the user’s information because anyone can open a specific page just by entering direct url.
  • Verify the session timeout: This is most important test case for any finance related site.Session should time out if user is inactive for few minute. This is normally a sustainability test of session. If your application is not prompting for session timeout then think once this may be issue.
  • Verify https in url for login page:  S with Http mean secure http. If login is associated with http in url means you information to login in to application is not secure and anyone can access your information just by doing small effort. While HTTPS ensure encryption of information that is being sent to server from client end.
  • Verify ID in url while processing your request :  keep track on ID associated with your request url and ID associated with request url should be dynamic not static otherwise this may help some hacker to nab your information.
  • Verify deletion of ID while browsing : Go to the place where cookies are saved and try to delete cookies when you are just browsing your account and try to find out the cookies that have your username and password because as soon as you delete that cookies you should be reached to login page. If you find the same cookies then try to change the numbers in cookies and should verify what is happening, hopefully corrupt cookies that have your real id should redirect you on login page once again even you haven’t deleted the cookies.
  • Try to login when your cookies are disable
  • Check SQL injection: most devastating vulnerabilities to  impact a business, as it can lead to exposure of all of the sensitive information stored in an application’s database, including handy information such as usernames, passwords, names, addresses, phone numbers, and credit card details.
    So I would suggest including this test cases if you are going to test some banking and insurance related application. Most common SQL injection that is used  or ‘1’=’1, if this got executed then be ready for the loss of your important information. If means hacker can login without any problem to system or application.
  • Verify account lock out: I would like to include this test case with priority, if user is using 3 or some specific number of time a wrong password then his/her account should be locked out and access should be allowed after certain assurance form filling or by calling customer care. This may help user from hackers hand.
  • Verify simultaneous login to application on different browser: I think you all would be familiar with this in daily life if you would have used railway ticket booking site.
  • Try some hit and trial username and password : before deploying application, username and password like Admin:Admin , Guest:Guest, some username :password, author:author  should be use to test but should be denied when application is deployed.
These all test cases not only test the functionality but also test the security of the application. But I am not saying that these test cases are enough to test security of application. Because security testing is the part of testing that does not have any relation with requirement document so more and more effort is needed if we are talking about the security of an application.
Hope this would help you in testing login page

Thursday, 3 October 2013

Handling Multiple Windows in WebDriver

Dealing with multiple windows in Automation Testing has always been a little tricky and require an extra effort.
Before commencing, let us first consider a few situations when we are likely to deal with multiple windows.
  • Filling forms may require to select the date from a separately opened window.
  • Clicking on some link/button can kick-off yet another window.
  • Handling Advertisement windows
Hence, we can come up with various scenarios depending upon the application.
Now let us motion ourselves towards the challenge we face under above situations. The most particular of all is switching the focus from one window to another. Let us understand the same in the following way:
1Comprehending from the above figure, the entire process can be fundamentally segregated into following steps:
Step 1 : Clicking on Link1 on Window A
A new Window B is opened.
Step 2 : Move Focus from Window A to Window B
Window B is active now
Step 3 : Perform Actions on Window B
Complete the entire set of Actions
Step 4 : Move Focus from Window B to Window A
Window A is active now
These are the steps which we can easily interpret out of the diagram, but there are a few more steps to add to complete this process and making our script execute. These steps don’t have visibility but plays a very vital role. Let us now re-consider the same scenario.
Step 1 : Clicking on Link1 on Window A
A new Window B is opened.
Step 2 : Save reference for Window A
Step 3 : Create reference for Window B
Step 3 : Move Focus from Window A to Window B
Window B is active now
Step 3 : Perform Actions on Window B
Complete the entire set of Actions
Step 4 : Move Focus from Window B to Window A
Window A is active now
Let us understand the same with a small coding example.
 public class MultiWindowHandle {  
 WebDriver driver;  
 @Before  
 public void setup() throws Exception {  
 driver=new FirefoxDriver();  
 String URL="https://www.abc.co.in/";   
 driver.get(URL);  
 driver.manage().window().maximize();  
 }  
 @Test  
 public void test() throws Exception {   
 // Opening Calender  
 driver.findElement(By.xpath("//img[@alt='Calender']")).click();  
 // Storing parent window reference into a String Variable  
 String Parent_Window = driver.getWindowHandle();    
  // Switching from parent window to child window   
 for (String Child_Window : driver.getWindowHandles())  
 {  
 driver.switchTo().window(Child_Window);  
 // Performing actions on child window  
 driver.findElement(By.id("calendar_month_txt")).click();  
 List  Months=driver.findElements(By.xpath("//div[@id='monthDropDown']//div"));  
 int Months_Size=Months.size();  
 System.out.println("Month size is:"+Months_Size);  
 Months.get(1).click();  
 driver.findElement(By.xpath("//*[@id='calendarDiv']/div/table/tbody/tr/td[contains(text(),'16')]")).click();  
 }  
 //Switching back to Parent Window  
 driver.switchTo().window(Parent_Window);  
 //Performing some actions on Parent Window  
 driver.findElement(By.className("btn_style")).click();  
 }  
  @After  
  public void close() {  
  driver.quit();  
  }   
 }  

WebDriver’s most popular Commands

Most common functions used in WebDriver to make a web-application testing.

  1. IsElementPresent/Text Present
    1. Finding elements by using function that take argument of By classprivate boolean isElementPresent(WebDriver driver, By by)
      try{
      driver.findElement(by);
      return true;
      }
      catch(Exception e)
      {
      return false;
      }
      }
    2. Using the size to decide whether element is there or not
      if(driver.findElements(Locator).size()>0
      {
      return true
      }else
      {
      return false
      }
      }
    3. Finding the text using the PageSourcedriver.PageSource.Contains("TEXT that you want to see on the page");
  2. Finding WebElement  by using various locators
    1. Using ID  WebElement welement = driver.findElement(By.id("Id from webpage"));
    2. Using Name  WebElement welement = driver.findElement(By.name("Name of WebElement"));
    3. Using Tag Name  WebElement welement = driver.findElement(By.tagName("tag name"));
    4. Using Xpath  WebElement welement = driver.findElement(By.xpath("xpath of  webElement"));
    5. Using CSS  WebElement welement = driver.findElement(By.CSS("CSS locator path"));
    6. Using LinkText  WebElement welement = driver.findElement(By.LinkText("LinkText"));
  3. Fetching pop-up message
    this is the function that would help you in fetching the message

    public static String getPopupMessage(final WebDriver driver) {
    String message = null;
    try {
    Alert alert = driver.switchTo().alert();
    message = alert.getText();
    alert.accept();
    } catch (Exception e) {
    message = null;
    }
    System.out.println("message"+message);
    return message;
    }
  4. Canceling pop-up
    public static String cancelPopupMessageBox(final WebDriver driver) {
    String message = null;
    try {
    Alert alert = driver.switchTo().alert();
    message = alert.getText();
    alert.dismiss();
    } catch (Exception e) {
    message = null;
    }
    return message;
    }
  5. Inserting string in Text Fieldpublic static void insertText(WebDriver driver, By locator, String value) {
    WebElement field = driver.findElement(locator);
    field.clear();
    field.sendKeys(value);
    }
  6. Reading ToolTip text
    public static String tooltipText(WebDriver driver, By locator){
    String tooltip = driver.findElement(locator).getAttribute("title");
    return tooltip;
    }
  7. Selecting Radio Button
    public static void selectRadioButton(WebDriver driver, By locator, String value){ List select = driver.findElements(locator);
    for (WebElement element : select)
    {
    if (element.getAttribute("value").equalsIgnoreCase(value)){
    element.click();
    }
    }
  8.  Selecting CheckBox

    public static void selectCheckboxes(WebDriver driver, By locator,String value)
    {
    List abc = driver.findElements(locator);
    List list = new ArrayListArrays.asList(value.split(",")));
    for (String check : list){
    for (WebElement chk : abc){
    if(chk.getAttribute("value").equalsIgnoreCase(check)){
    chk.click();
    }}}}
  9. Selecting Dropdownpublic static void selectDropdown(WebDriver driver, By locator, String value){
    new Select (driver.findElement(locator)).selectByVisibleText(value); }
  10. Selecting searched dropdownpublic static void selectSearchDropdown(WebDriver driver, By locator, String value){
    driver.findElement(locator).click();
    driver.findElement(locator).sendKeys(value);
    driver.findElement(locator).sendKeys(Keys.TAB);
    }
  11. Uploading filepublic static void uploadFile(WebDriver driver, By locator, String path){
    driver.findElement(locator).sendKeys(path);
    }
  12. Downloading fileHere we will click on a link and will download the file with a predefined name at some specified location.
    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();
    // Here we are specifying the location where we really want to save the file.
    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();
  13. Wait()
    1. Implicit Wait :
      driver.manage.timeouts().implicitlyWait(10,TimeUnit.SECONDS);
    2. Explicit Wait:WebDriverWait wait = new WebDriverWait(driver,10);
      wait.until(ExpectedConditons.elementToBeClickable(By.id/xpath/name("locator"));
    3.  Using Sleep method of java
      Thread.sleep(time in milisecond)
  14. Navigation method of WebDriver Interface

    1. to() method (its a alternative of get() method)
      driver.navigate().to(Url);
      This will open the URL that you have inserted as argument
    2. back() – use to navigate one step back from current position in recent history syntax == driver.navigate().back();
    3. forward() – use to navigate one step forward in browser historydriver.navigate().forward();
    4. refresh() – This will refresh you current open urldriver.navigate().refresh();
  15. Deleting all Cookies before doing any kind of action  driver.manage().deleteAllCookies();
    This will delete all cookies
  16. Pressing any Keyboard key using Action builder class of WebDriverWebDriver has rewarded us with one class Action to handle all keyboard and Mouse action. While creating a action builder its constructor takes WebDriver as argument. Here I am taking example of pressing Control key
    Actions builder = new Actions(driver);
    builder.keyDown(Keys.CONTROL).click(someElement).click(someOtherElement).keyUp(Keys.CONTROL).build().perform();
    When we press multiple keys or action together then we need to bind all in a single command by using build() method and perform() method intend us to perform the action.
    In the same way you can handle other key actions.
  17. Drag and Drop action in Webdriver
    In this we need to specify both WebElement means Source and target and for draganddrop Action class has a method with two argument so let see how it normally look like
    WebElement element = driver.findElement(By.name("source"));
    WebElement target = driver.findElement(By.name("target"));
    (new Actions(driver)).dragAndDrop(element, target).perform();

Hybrid Testing (Data + Keyword Driven) using Selenium

Today, we’ll see how to do hybrid testing using selenium. Let’s discuss what’s hybrid testing first. Hybrid testing is a combination of Data Driven testing along with keyword. Here we’ll use some keywords as the driving parameters in data driven testing the data sheet. The keywords will be defined by the user, and let’s call them user defined keywords.
Before getting into the framework, let’s discuss on what are the external files which will be required. The list of files that will be required in addition to selenium client driver and selenium server jar files are as below
  1. TestNG: in order to data drive our test, we would require the latest version of testNG jar file which is now testng-5.14.1.jar and can be downloaded from http://testng.org/doc/download.html
  2. JXL: in order to use Microsoft Excel files as data source we would need the jxl jar file which can be downloaded fromhttp://sourceforge.net/projects/jexcelapi/files/
  3. Latest Junit: this will be required to verify certain condition and can be downloaded fromhttps://github.com/KentBeck/junit/downloads
  4. TestNG plugin for Eclipse: This will be required to run the TestNG scripts in eclipse and the content of this plugin has to be placed inside the “dropin” folder inside the eclipse directory. The file can be downloaded fromhttp://testng.org/doc/download.html
The first 3 file need to be added to the build path in the project in eclipse to use them. The fourth file needs to extracted in the dropin folder of the eclipse folder so that when you open the droping folder, a plugin folder is created inside it. This is all about configuration that is required for such testing.
Now let’s start with how to test using this framework. Let’s test the IBN Live website, where we’ll use the keyword ‘link’ to drive our test. So to do this, we need to place this keyword ‘link’ in the data sheet. This will decide the action when the ‘link’ keyword is passed to the program. The corresponding cell values for that particular row will be used for different operations on the same. Below is the data sheet that we are going to use.
testDatapropertyxPathvalueexpectedResultpermissionname
pagetitleCNN-IBN, Live India News,Top Breaking News,World,India,Business,Sports, Entertainment & Health News
linklink=NewsclickNews
linklink=PoliticsclickPolitics
linklink=MoviesclickMovies
testData
Here using selenium, we are going to test the page title of the landing page and use the link property to navigate to different pages. So first let me explain the data table. “testData” is the table marker which will tell the start and end point of the table. The column headers will be used as variables. Here property defines the property on which we are going to perform certain actions. xPath will be used to locate the properties, value will be used to enter some data or select any object, expected result will be used to compare the actual value to the expected value, permission will determine the course of action and name will be used to give meaningful name while generating result. Below is the sample code that will drive our Hybrid test.
import com.thoughtworks.selenium.*;
import org.junit.AfterClass;
import org.openqa.selenium.server.SeleniumServer;
import org.testng.annotations.*;
import java.io.File;
import jxl.*;

public class DataDrivenTest extends SeleneseTestCase{

    @BeforeClass
    public void setUp() throws Exception {
        setUp("http://ibnlive.in.com/", "*iexplore");
        selenium.open("/");
        selenium.setTimeout("60000");
        selenium.waitForPageToLoad("60000");
        selenium.windowMaximize();
        selenium.windowFocus();
    }

    @DataProvider(name = "DP")
    public Object[][] createData() throws Exception{
        Object[][] retObjArr=getTableArray("D:\\Work\\Data Driven Testing\\Data Driven Test\\Resources\\Data Sheet.xls",
                "Data", "testData");
        return(retObjArr);
    }

    @Test (dataProvider = "DP")
    public void testElements(String property, String xPath, String value, String expectedResult, String permission,
 String name) throws Exception {
        if(property.equals("pagetitle")){
        	if(selenium.getTitle().equals(expectedResult)){
        		System.out.println("The page title is displaying properly");
        	}
        	else
        		System.out.println("The page title is not correct");
        }
        if(property.equals("link")){
        	if(selenium.isElementPresent(xPath))
        		System.out.println("The link "+name+" is present");
        	else
        		System.out.println("The link "+name+" is not present");
        	if(permission.equals("click"))
        	{
        		selenium.click(xPath);
        		selenium.waitForPageToLoad("60000");
        	}
        }
    }

    @AfterClass
    public void tearDown(){
        selenium.close();
        selenium.stop();
    }

    public String[][] getTableArray(String xlFilePath, String sheetName, String tableName) throws Exception{
        String[][] tabArray=null;

            Workbook workbook = Workbook.getWorkbook(new File(xlFilePath));
            Sheet sheet = workbook.getSheet(sheetName);
            int startRow,startCol, endRow, endCol,ci,cj;
            Cell tableStart=sheet.findCell(tableName);
            startRow=tableStart.getRow();
            startCol=tableStart.getColumn();

            Cell tableEnd= sheet.findCell(tableName, startCol+1,startRow+1, 100, 64000,  false);

            endRow=tableEnd.getRow();
            endCol=tableEnd.getColumn();
            System.out.println("startRow="+startRow+", endRow="+endRow+", " +
                    "startCol="+startCol+", endCol="+endCol);
            tabArray=new String[endRow-startRow-1][endCol-startCol-1];
            ci=0;

            for (int i=startRow+1;i<endRow;i++,ci++){
                cj=0;
                for (int j=startCol+1;j<endCol;j++,cj++){
                    tabArray[ci][cj]=sheet.getCell(j,i).getContents();
                }
            }

        return(tabArray);
    }

}//end of class
The createData method will create a virtual copy of the data sheet in memory. Inside it, we need to specify the data sheet path along with its name, the sheet name, the table marker that we discussed earlier. Here, the testElements method is driving the test depending on the input, it’s getting from the excel sheet. It can be customized to accommodate more types of properties like drop down, text box, text area, etc. according to user needs.

Explicit and Implicit Waits in Selenium Web Driver

When implementing time synchronization for waiting with Selenium Web Driver technology, we can use two types of waits:

Explicit Wait

In Explicit Wait, we write a code to define a wait statement for certain condition to be satisfied until the wait reaches its timeout period. If WebDriver can find the element before the defined timeout value, the code execution will continue to next line of code. Therefore, it is important to setup a reasonable timeout seconds according to the system response.
For example:

public void ExplicitWait(int timeouseconds)

{

IWebDriver driver = new FirefoxDriver();
driver.Url = “http://www.google.com&#8221;;
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeouseconds));
IWebElement elementToWait = wait.Until<IWebElement>((d) =>
{
return d.FindElement(By.Id(“theElementId”));
});

}

Implicit Wait

In Implicit Wait, we define a code to wait for a certain amount of time when trying to find an element or elements. If the Web Driver cannot find it immediately because of its availability, the WebDriver will wait. The default setting is zero. Once we set a time, the Web Driver waits for the period of the WebDriver object instance.
For example:

public void ImplicitWait(int waitSeconds)

{

WebDriver driver = new FirefoxDriver();
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(waitSeconds));
driver.Url = “http://www.google.com&#8221;;
IWebElement elementToWait = driver.FindElement(By.Id(“theElementId”));

}

Highlight elements with Selenium WebDriver

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

Technical challenges with selenium

As you know Selenium is a free ware open source testing tool. There are many challenges with Selenium.
1.Selenium Supports only web based applications
2.It doesn’t support any non web based (Like Win 32, Java Applet, Java Swing, .Net Client Server etc) applications
3.When you compare selenium with QTP, Silk Test, Test Partner and RFT, there are many challenges in terms of maintainability of the test cases
4.Since Selenium is a freeware tool, there is no direct support if one is in trouble with the support of applications
5.There is no object repository concept in Selenium, so maintainability of the objects is very high
6.There are many challenges if one have to interact with Win 32 windows even when you are working with Web based applications
7.Bitmap comparison is not supported by Selenium
8.Any reporting related capabilities, you need to depend on third party tools
9.You need to learn any one of the native language like (.Net, Java, Perl, Python, PHP, Ruby) to work efficiently with the scripting side of selenium

Selenium Web Driver Command List

Command                                               Description
driver.get(“http://www.google.com&#8221;); To open an application
driver.findElement(By.id(“passwd-id”)); Finding Element using Id
driver.findElement(By.name(“passwd”)); Finding Element using Name
driver.findElement(By.xpath(“//input[@id=’passwd-id’]“)); Finding Element using Xpath
element.sendKeys(“some text”); To type some data
element.clear(); clear thecontents of a text field or textarea
driver.findElement(By.xpath(“//select”)); Selecting the value
select.findElements(By.tagName(“option”)); Selecting the value
select.deselectAll(); This will deselect all OPTIONs from the first SELECT on the page
select.selectByVisibleText(“Edam”); select the OPTION withthe displayed text of “Edam”
findElement(By.id(“submit”)).click(); To click on Any button/Link
driver.switchTo().window(“windowName”); Moving from one window to another window
driver.switchTo().frame(“frameName”); swing from frame to frame (or into iframes)
driver.switchTo().frame(“frameName.0.child”); to access subframes by separating the path with a dot, and you can specify the frame by itsindex too.
driver.switchTo().alert(); Handling Alerts
driver.navigate().to(“http://www.example.com&#8221;); To Navigate Paeticular URL
driver.navigate().forward(); To Navigate Forward
driver.navigate().back(); To Navigate Backword
driver.close() Closes the current window
driver.quit() Quits the driver and closes every associated window.
driver.switch_to_alert() Switches focus to an alert on the page.
driver.refresh() Refreshes the current page.
driver.implicitly_wait(30) Amount of time to wait
driver.set_script_timeout(30) The amount of time to wait
driver.get_screenshot_as_file(‘/Screenshots/foo.png’) The full path you wish to save your screenshot to
driver.get_screenshot_as_base64() Gets the screenshot of the current window as a base64 encoded string which is useful in embedded images in HTML

Login Scenario – Providing Login Detail from Excel Sheet

Excel Sheet format should be in .XLS format
import java.io.FileInputStream;
import jxl.Sheet;
import jxl.Workbook;
import com.thoughtworks.selenium.*;
import org.openqa.selenium.server.*;
import org.testng.annotations.*;
public class Loginexcel {
public Selenium selenium;
public SeleniumServer seleniumserver;
@BeforeClass
public void setUp() throws Exception {
RemoteControlConfiguration rc = new RemoteControlConfiguration();
seleniumserver = new SeleniumServer(rc);
selenium = new DefaultSelenium(“localhost”, 4444, “*firefox”, “http://&#8221;);
seleniumserver.start();
selenium.start();
}
@Test
public void testDefaultTNG()throws Exception {
FileInputStream fi=new FileInputStream(“E:\\Selenium\\LoginExcel.xls”);
Workbook w=Workbook.getWorkbook(fi);
Sheet s=w.getSheet(0);
selenium.open(“http://127.0.0.1/orangehrm-2.6/login.php&#8221;);
selenium.windowMaximize();
for (int i = 1; i < s.getRows(); i++)
{
//Read data from excel sheet
String s1 = s.getCell(0,i).getContents();
String s2 = s.getCell(1,i).getContents();
selenium.type(“txtUserName”,s1);
selenium.type(“txtPassword”,s2);
selenium.click(“Submit”);
Thread.sleep(2000);
selenium.click(“Link=Logout”);
}
}
@AfterClass
public void tearDown() throws InterruptedException{
selenium.stop();
seleniumserver.stop();
}
}

Angular JS Protractor Installation process - Tutorial Part 1

                     Protractor, formally known as E2E testing framework, is an open source functional automation framework designed spe...