Blog to understand automation concepts in QTP, Selenium Webdriver and Manual Testing concepts

Showing posts with label Selenium Automation. Show all posts
Showing posts with label Selenium Automation. Show all posts

Tips to handle first hurdles using selenium webdriver on IE browser

Some useful tips while launching tips in launching browser:

          HurdleGet following error on launching the IE browser:
Exception in thread "main"org.openqa.selenium.remote.SessionNotFoundException: Unexpected error launching Internet Explorer. Protected Mode settings are not the same for all zones. Enable Protected Mode must be set to the same value (enabled or disabled) for all zones. (WARNING: The server did not provide any stacktrace information).


In case such error is displayed in the console, it is asking to set same protected mode setting for all the zones. This can be set as shown in screenshot below:



 Hurdle:  Some Websites especially in QA environment do not have proper certificates installed due to which we get an error Page with issue with security certificate. Once user clicks on Continue to this Website (not recommended), a pop up appears. How to handle the pop up window?



Usually in QA environment, on navigating a page is https://, certificate error is displayed. The links in the Page are identified easily using selenium, but the pop up is not handled properly using alerts as:
Alert alert = driver.switchTo().alert();
alert.accept();

Alerts are used to handle javascript alerts that pop up in between.
Alerts can be used to accept a pop up, dismiss a pop up,getText(),SendKeys.

I tried to handle the pop up for res://ieframe.dll/ using alerts, but it did not work out. On further trying, I find a simple solution to the solution. The solution to the problem is to add res://ieframe.dll/ to the trusted sites or local intranet.

       Hurdle: Exception in thread "main" org.openqa.selenium.remote.SessionNotFoundException: Unexpected error launching Internet Explorer. Browser zoom level was set to 150%. It should be set to 100% (WARNING: The server did not provide any stacktrace information


This error occurs in case the zoom level is set different from 100% zoom level.

So to consolidate, before running any test in IE, we should ensure :
      a.      Protected mode is set same for all the internet zones and
      b.      Zoom level is set as 100% in the IE browser.

     How do we maximize the browser on launching the browser?


Using  below code , we can maximise the browser:

WebDriver driver;
File file = new File("D:\\Selenium\\IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath()); 
driver = new  InternetExplorerDriver();
driver.manage().window().maximize();

Converting an existing project in Selenium to Maven Project in Eclipse

Maven can be integrated with eclipse IDE to manage build and deploy selenium or any java project in eclipse. In this article we will discuss on first step in Setting up existing project to maven project.

Installing Maven plugin in eclipse is simple and takes around thirty minutes to install. Below are simple steps to install maven plugin in eclipse.


  • Open eclipse and click on Help>Eclipse Marketplace



  • Search for maven in eclipse marketplace. Install Maven integration for Eclipse
  • Once maven is installed, restart eclipse.
  •  Go to workspace and right click on the project and click on configure as shown in screenshot below
  • Click on Convert to Maven Project.
  • A pop up to create a new Maven POM will appear.

  • Click on finish. A POM file will be created automatically.

You can set project dependencies in the POM file POM stands for "Project Object Model". It is an XML representation of a Maven project held in a file named pom.xml.


Once the project is set as maven project, we can perform various action in Project using maven as shown in screenshot below. We can also add selenium dependencies in the POM to manage selenium artifacts , which will be explained in next articles.






Automating Mouse and Keyboard Interaction using Selenium Webdriver

Using Interactions. Action class, we can automate various mouse and keyboard operations using Selenium Webdriver. We can also create a series of operation using Actions class, build the operations and perform the action in series.

Suppose we visit a shopping site, there can be main categories in the header of the Page, on hovering over a main category, sub categories can be displayed, and we can click on the sub categories.
There are three main steps which should be performed.
  •  Identify the series of actions to be performed. This can be an individual action e.g. hovering over a link to a series of event, e.g. pressing up Key in Keyboard, hovering over a link, click on a sub menu.
  • Once we have identified the series of event we need to build the action.
  • Once we have built the action, we need to perform the action.

This can be explained in code below:

//Import following class libraries
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;

Together with this, all the other class libraries for object identification needs to be imported, We assume we have set up for selenium in the machine and knows object Identification using Selenium as this is an advance concept in Selenium.If you want to learn more on basic concepts in Selenium, refer to previous posts in Selenium in this blog or visit the Selenium official website for required knowledge.

//define an object act of Actions class
Actions act = new Actions(driver);
// define the main link in the Page.
WebElement ElemElec = driver.findElement(By.linkText("Electronics"));
// define an object mousehover1 of action class. In action mousehover1, define the flow of event. Example in below case, we define series of events, hovering on the main menu, followed by submenu and then clicking the link.
Action mousehover1 = act.moveToElement(ElemElec).moveToElement(driver.findElement(By.linkText("Access"))).click().build();
mousehover1.perform();

This was an example of using action/ actions to identifying an element in the page using mouse operation and performing action on the same similarly we can automate keyboard actions using Interactions class.

Some of the useful methods of Acton/Actions class are:

  • click() or click(WebElement) – clicks on current mouse location or in the middle of the webElement.

  • doubleClick() or doubleClick(WebElement) – clicks on current mouse location or in the middle of the webElement.

  • dragAndDrop(WebElement src, WebElement tgt) - performs click-and-hold at the location of the source element, releases the mouse at  target location.

  • movetoElement(() or movetoElement(WebElement) – hovers at current location or Element identified by the webElement.

  • SendKeys, KeyUp, and KeyDown – Used to perform keyboard operation by sending keys

  • Build() – Once we have defined the sequence of action to be performed, we use build() to build the sequence of operations to be performed.

  • Perform() – Executing an action.


Details of all the methods of the action or actions class are explained in the Google code site for Selenium.
Please refer http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/interactions/Actions.html for further details on the topic.



In the end, this is 100th Post of this blog. I would like to thanks all readers of the blog for supporting the effort.

Learning Selenium - Validating existence of object based on text of object




In this post, We will discuss on an example to verify if an element exist in the Page using Selenium. Together with Selenium concept of finding list of elements using findElements, we will discuss on following concepts useful on using Selenium with Java.



1. In this article, we will know how to create a generic function to verify elements of a specific object type based on text of object. Since this is a genric approach, we can use similar concept on working with multiple object. 


2. Explaining how to split a string based on delimiter into a string array.


3. Explaining how to use try catch statements to handle error in the Page. In case of no element found in the page matching the identifier, Exception needs to be handled using try catch block,


4. We will explain how to use switch statement in Java useful from a tester's perspective.  Switch is a useful concept to work with different inputs to create a generic function.


5.How to loop through list of elements is explained in the below example. Once we find a list of web Elements. how to extract each element in the list.


6. Creating a function with return value as boolean is explained.





Please find the code below: 





public boolean boolElementExists(String strObjType, String strText)
{
 boolean boolret = false;
//Suppose there are multiple object text provided of an object type provided in the strText, we will provide text separated by > .
//for e.g : login>HELP as link object in the Page
 String[] sre = strText.split(">");
// Loop through each of the text provided 
 for ( int j = 0;j<sre.length;j++)
 {
  List<WebElement> elemlst = null;
  // We will convert the strObjType to Upper Case and trimming the text around.
  strObjType = strObjType.toUpperCase().trim();
  //we will use try catch to return false mostly to handle scenario of object not found expection , in this case we will return false from the function
  try
  {
   //we will use a switch to perform action on an object.A case is used in this case to store different value in WebElement List Object. Using switch provides good option to create generic functions 
   switch (strObjType)
   {
   // in case of link object storing all the elements of type link in elemlst
   case "LINK":
// driver is already discussed in a previous article . Please refer to below article to understand how a driver object is created. 
Understanding Selenium Web Driver: Launching Selenium on different browsers

     elemlst = driver.findElements(By.tagName("a")); 
    break;
    // in case of link object storing all the elements of type link in label
   case "LABEL":
    elemlst = driver.findElements(By.tagName("label")); 
    break;
    // This is just a example , we can define other objects type also
   }
   
   // Now we will loop through all the objects of link , and whereever the text matches , we will loop out of the function and true will be returned.
   for (int i=0;i<elemlst.size();i++)
   {
    if (elemlst.get(i).getText().contentEquals(strText.trim()))
      {
       boolret = true;
       i= elemlst.size()-1;
      }
   }
   // In case no match is found , it will return false.
   if (boolret = false)
   {
    return false;
   }
   }
  catch(Exception e)
  {
   return false;
  }
 }
 return boolret;
}

Identifying Elements in Selenium – Using By

In the previous article, we discuss on the concept and difference between FindElement and FindElements. While FindElement returns the first  webElement matching the condition, FindElements return a list of Web Elements.

We can identify a web Element using the class Name, Id, css Selector, link Text, name, partial link Text, tag Name, or Xpath property. Let us discuss now what these properties are and how to extract these in an HTML Page. We can identify the DOM structure of the objects in page. In Firefox browser, we can install the firebug add-on to identify the properties of element.


In Internet explorer, Chrome, or Firefox, Press F12 which will open the developer toolbar. Installing Firebug or similar add-on in browser helps to identify the object’s property in a better way, so is recommended to install firebug add-on in Firefox to extract object information to be used to identify object properties in a better way.


Let us take a simple example of link for Gmail in the Google Page, to understand how we can use properties in selenium to uniquely identify the element in the Page.
Consider code as shown in below image. We are focusing on element link for Gmail.



For the element gmail in the Page, we have following information from the firebug. It is a link, so tagName of the object is “a”, classname of the object is “gb_g”, Id is “gma3”, href is https://mail.google.com/mail/?tab=wm. nad name is "tna";

Now to identify this element in the Page in Selenium using different by method is explained below: 

Using Id - Iattribute can be used to uniquely identify web element in the Page. Since Id is unique for a web element in the Page. If Id is provided for an object, we should use Id to identify the object uniquely.


So suppose we use Id to uniquely identify the web element, the syntax will be:

WebElement usr= driver.findElement(By.id("gma3"));

Using TagName – We usually use tagName to find list of elements in the Page. A common example includes finding number of link in the Page.


List<WebElement> logi = driver.findElements(By.tagName("a"));
System.out.println(logi.size());

      Using ClassName - The class attribute specifies the class of element defined. Several objects in the Page can have same class and is usually useful  o get a list of objects. 


E.g: there are five edit boxes in a form. Once we click on submit with invalid data in the forms. Five different error messages will be displayed, and is very much possible, all will have same class. Using ClassName and findelements, we can get a list of webelement and extract the error message using getText Method;

WebElement usr= driver.findElement(By.className("gb_g"));

In case of using findElement, first object identified by properties will be selected as webElement.

Name - Finds element /element (s) that match the name attribute supplied.


WebElement usr= driver.findElement(By.name("name"));

      linkText – Find element that matches the exact text of the link, used for element of type link only.

     WebElement usr= driver.findElement(By.linkText("gmail"));

   partialLinkText – Find element that matches the text partially of the link based on text provided, used for element of type link only.

     
     WebElement usr= driver.findElement(By.partiallinkText("gma"));

   cssSelector – As Per Wiki Definition,In CSS, selectors are used to declare which part of the markup a style applies to by matching tags and attributes in the markup itself. Based on location of objects, its property, e.g : Id or className or relative location in the Page, we can identify the element. We will discuss various scenario and syntax to identify the element using css.


In the current example, we can identify link Gmail using css in following ways.

WebElement usr= driver.findElement(By.cssSelector("a. gb_g")); Or
WebElement usr= driver.findElement(By.cssSelector("a#gma3")); Or
WebElement usr= driver.findElement(By.cssSelector("a#gma3.gb_g")); Or
WebElement usr= driver.findElement(By.cssSelector("a[name=tna"));


      Xpath – Xpath is a query language for selecting nodes from an XML document. XPath is rendered on most HTML Pages


WebElement usr= driver.findElement(By.xpath("//a"));
WebElement usr= driver.findElement((By.xpath("//a[@id='gma3']"));
WebElement usr= driver.findElement((By.xpath("//a[contains(@href, 'https://mail.google.com/mail/?tab=wm')]”));

How to Use FindElement(s) to identify Elements in Selenium WebDriver

The objective of this article  is to understand object Identification in selenium for the basic login Page in the application.Let us assume we have username/Password available for website. In this example, We will click on Link for Login, provide username and Password and click on Login button and validate login is successful.


Since we have to perform action on different objects, we need to identify objects or elements in the Page based on properties of the object. We use findElement or findElements to find a particular element or a list of element satisfying the object description. 

The findElement() method returns a WebElement object based on object description and throws exception if it does not find any element matching the object description. To return a webelement object, below is the syntax:

WebElement elemlink = driver.findElement(By.linkText("log in"));

Once we have the webelement defined, we can perform required action on the element. E.g: clicking a link, inputting text in an edit box or get text of the object.
Methods to work on an object using Selenium

In this example, we find collection of all elements in list elemlnk which have tagName as a, i.e collection of all the links in the page. Once we have the list, we can validate if a particular link is available in the Page by comparing the text or validating for broken links in the page based on http response.List<WebElement> elemlnk = driver.findElements(By.tagName("a"));for (int i=0;i<elemlnk.size();i++)
{String strData = elemlnk.get(i).getText();}So now, since we are familiar with basic of WebElement and WebElements, We can go further with the original problem in the Page which was:In this article, we will click on Link for Login, provide username and Password and click on Login button and validate login is successful.

Code for the problem:public void LoginInSagenda() { try {//finding link in the page for login and clicking on the link. WebElement elemlink = driver.findElement(By.linkText("Log in")); elemlink.click(); new WebDriverWait(driver,40).until(ExpectedConditions.titleContains("Log in"));//once link is clicked, we will verify title of the new page if (driver.getTitle().contains("Log in")) { System.out.println("Title of the Page contains text :" + driver.getTitle();          } else { System.out.println("Title of the Page does not contains text : Log in"); } //define elements on which to perform action. Note we use different ways to identify object in page by using Id, name and xpath in the page WebElement usr= driver.findElement(By.id("Email")); WebElement pwd= driver.findElement(By.name("Password")); WebElement login = driver.findElement(By.xpath("//input[@value='Login']"));// perform required action in the objects identified. usr.sendKeys("abc@xyz.com"); pwd.sendKeys("abcxyz"); login.click();// dynamic wait until a particular condition is met new WebDriverWait(driver,40).until(ExpectedConditions.titleContains("Dashboard"));//once link is clicked, we will verify title of the new page if (driver.getTitle().contains("Dashboard")) { System.out.println("Title of the Page contains text :" + driver.getTitle());   } else { System.out.println("Title of the Page does not contains text : Dashboard");   } } catch (Exception e) { System.out.println(e.getMessage());
}
}

The findElements() method returns a list of WebElements matching the object description. If no elements are found, it returns an empty list. 



How to Launch Selenium WebDriver on different browsers

In this article, we will discuss on how we launch Selenium web driver in different browsers in Java. 

Before we go further with this, We need installing different jar files and making initial set up in Java, Please go through below link and other useful links to set up initial java project in eclipse with selenium jar files added to project build path.


Once we have configured eclipse and added required external libraries in the build path, we can start with a basic test in eclipse to solve following requirement: 
  It is required to perform following action on different browsers
  •         Open www.sagenda.net on browser specified by user
  •         Verify the title of the Page has Sagenda in the text.
  •      Close the browser.
Below is the self explanatory code in java using Selenium to perform the required job:


//These are the class libraries that needs to be imported
import java.io.File;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;

public class Iteration {

//Define Webdriver object

 WebDriver driver;

//This is the main method to drive the test flow  

public static void main(String[] args) throws InterruptedException

//There are two part in the flow for which we created the required methods 

Iteration iter = new Iteration();

//a. Launching the required Browser

iter.LaunchBrowser("chrome");

//b. Providing the url of application and condition to verified in the test. Text in title in this example

iter.homePage("https://sagenda.net", "Sagenda");

}

//Function to launch required browser

public void LaunchBrowser (String strBrowser)

{

//based on the expected browser as provided in argument of method, we will launch the required browser

if (strBrowser.trim().toLowerCase().contentEquals("ie"))

{

//Launch IE browser://Pre-Conditions: Download IE driverServer.exe from the selenium download site and provide location where it is downloaded

 File file = new File("D:\\Selenium\\IEDriverServer.exe");

System.setProperty("webdriver.ie.driver", file.getAbsolutePath()); 

driver = new  InternetExplorerDriver();

}


else if (strBrowser.trim().toLowerCase().contentEquals("firefox"))

{

driver = new  FirefoxDriver();

}

else if (strBrowser.trim().toLowerCase().contentEquals("chrome"))

{

//Pre-Conditions: Download IE driverServer.exe from the selenium download site and provide location where it is downloaded

    System.setProperty("webdriver.chrome.driver", "d://chromedriver.exe");

   DesiredCapabilities capabilities = DesiredCapabilities.chrome();

   ChromeOptions options = new ChromeOptions();

   options.addArguments("test-type");

//Provide location where chrome is currently installed.  

    String Chrome_Path = "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe";

   capabilities.setCapability("chrome.binary",Chrome_Path);

   capabilities.setCapability(ChromeOptions.CAPABILITY, options);

   driver = new ChromeDriver(capabilities);

}

else

{

//In case browser is not in above three , print below message 

System.out.println("This browser is currently not supported by me, Please select from IE/Firefox or chrome");

}

}

//Function to perform required action on the application

public void homePage(String url, String strTextinTitle)
{
try
{
//open the required url 
driver.get(url);
//once the url is launched, verify the title contains the required text.
//Note : In case we require exact match , we will use contentequals instead of contains
if (driver.getTitle().contains(strTextinTitle))
{
System.out.println("Title of the Page contains text :" + strTextinTitle );
}
else
{
System.out.println("Title of the Page does not contains text :" + strTextinTitle );
}
}
catch(Exception e)
{
System.out.println(e.getClass());
}
}
}