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

Saturday, May 13, 2017

WaitFor Commands for AJAX application in selenium ide




AJAX stands for Asynchronous JavaScript And XML. AJAX uses combination of browser built-in XMLHttpRequest to request data from a web server and JavaScript/HTML DOM to display/use the data. Due to asynchronous nature of request and response of the calls, there may be delay in element being displayed in the page after an action has been performed on another element in the page.


To wait for the element to appear in the page, there are different waitfor commands in selenium IDE, which waits for default timeout set up for the element to appear. So in case an element is not displayed straightway, waitfor commands can be used to resolve sync issues in selenium IDE.


Some commonly used waitfor commands are:

  • waitForAlertNotPresent/waitForAlertPresent
  • waitForElementPresent
  • waitForTextPresent
  • waitForPageToLoad
  • waitForFrameToLoad
  • clickandWait
There are lot of commands waiting for different conditions in selenium IDE, you can have a look at all the commands by writing waitfor in command and can use the relevant wait as per the scernario

Tuesday, November 22, 2016

Tutorials for Selenium IDE easy understanding


Selenium IDE :: Add-ons for Firefox - Download Selenium IDE from the link for
firefox. Remember Selenium IDE is add-on for firefox browser only.

Download Selenium IDE - Official site for Selenium. Can learn about selenium
IDE and release notes from this page.

Introduction to Selenium IDE - Guru99 - Excellent link to start understanding about Selenium IDE

Introduction to Selenium IDE (Installation and its Features) - Another interesting blog to understand the concept of Selenium IDE.

Useful tutorial Posts for Selenium IDE in this blog:


Mindmap for understanding Selenium IDE - Mindmap to understand what selenium IDE is all about. 

Installing Selenium IDE add-on in firefox - How to install Selenium IDE add-on in firefox.

Understanding and locating Locators in Selenium IDE - What are locators in Selenium IDE and how are locators used to identify an element in Selenium IDE

Log file for Selenium IDE execution using FileLogging addon for firefox - Log file are useful to identify failures in execution and validating the performance of application response.This article explains how to create log file for execution in Selenium IDE

Selenium Commands in Selenium IDE - This article explains what are the selenese commands most commonly used in Selenium IDE

Exporting selenium IDE tests to WebDriver - Test recorded using Selenium IDE can be imported into different languages support. This article explains how to export selenium IDE tests to Selenium WebDriver.

Selenium IDE Panes and Shortcut keys - This article explains the Interface of Selenium IDE with details of different panes and shortkeys for operations in Selenium IDE.

How to run test with random data in Selenium IDE: store and storeText Command - This article explains how to store information in application or using javascript, generating random data and storing in a variable.



Validating conditions using assert and verify in Selenium IDE -This post explains how to add assertions in Selenium IDE and what is the difference between assert and verify statement.

Friends, there may be many interesting blogs/post for Selenium IDE, which you have come across. Please feel free to ion share such links as can be useful for other readers.

Saturday, November 19, 2016

Understanding and locating Locators in Selenium IDE

What is meant by Locator in Selenium

Selenese commands are executed on the target element. The target element is defined in the web application based on the locators. For example, suppose there is an link in the page with id as homepage, the link element will be located and identified by ‘id=homepage’ and then we can execute click command on the link homepage identified by locator ‘id=username’.

What are different locator types in Selenium IDE

The various locator types in Selenium IDE are as follows: 

  • Locating elements by ID – an element can be identified using the ‘id’ attribute defined for the object. Since it is assumed that id attribute is unique for an element in the page, hence element will be uniquely identified in the page using id attribute for target. E.g. ‘id=iamunique’.
  • Locating elements by name – In case id attribute is not defined for the target element, we can identify the element using name attribute in the target. E.g. ‘name = sonamgupta’. In case of object is not identified uniquely by name locator, we can use multiple locators like ‘name = sonamgupta value = bewafahai’ to uniquely identify the element.
  • Locating elements by link text – For link element, we can identify an element using link text in the target. e.g. ‘link =loginkaro’ will identify a link with text as loginkaro.
  • Locating elements by XPath – We can also use XPath to identify an element in the page. XPath allows us to query the DOM structure of the page like a XML document. For e.g. //input will find first input box in the page and perform action on the same. Can use firepath/firebug to uniquely identify the element xpath
  • Locating elements by css – Elements in the webpage can be identified using CSS selectors to find the objects that you need. Selenium is compatible with CSS 1.0, CSS 2.0, and CSS 3.0 selectors. Syntax for identifying an element using css is ‘css = CSS Selector’ for e.g. ‘css=input.kyabaathain’ where input is the tag name for element and kyabaathain is the classname. Both xpath and css are useful to identify elements with complex identifiers.

Tools to identify the attributes and locators for element in the webpage

We can identify element locators using different developer tools in different browsers. Below are some of the developer tools that help to identify objects in the page.
  • Firebug: Firebug is a Firefox developer add-on used to identify elements on the page by using the find functionality.
  • FirePath: It is a Firefox add-on used with firebug and helps in testing XPath and CSS on the page. Highlights all elements on the page that match the selector to your element location.
  •  IE Developer Tools: IE developer tools helps in identifying element. This is inbuilt with IE browser and can be launched by pressing F12.
  • Google Chrome Developer Tools: This is inbuilt in Google chrome and can be launched by Pressing F12.

Google developer tool

Thursday, November 17, 2016

Log file for Selenium IDE execution using FileLogging addon for firefox

We can create log files of selenium IDE test execution and store in an file using the below process:

1. Download the File Logging add-on to Firefox as shown below.








2. Firefox will restart once the add-on is installed.

3. Now Open Selenium IDE in Firefox.

4. Go to Options>Options. 

5. Selenium IDE options window will open.

6. Go to FileLogging tab.

7. Provide location of file where logs needs to be created.

8. Define the logging level.

9. Select the required checkbox for logging information.

Give it a try, it is quite useful.


Friday, November 11, 2016

Selenium Commands in Selenium IDE

Components of teststep in Selenium IDE

A test step in Selenium comprises of following:
Selenese Commands - set of selenium commands used in Selenium IDE. e.g: Open , type , sendKeys, etc.
Target -  object on which to execute the commands. Target object can be identified based on the locator for the object,i.e. by Id, classname, xpath,CSS, etc.
Value  - acts as input or the expected result on execution of command on the target object. 


Selenium commands in Selenium IDE

Below are some of the useful commands used in Selenium.

  • Open - open(url). URL provided accepts both relative and absolute URLs. The "open" command waits for the page to load before proceeding. URL is provided in the target of the command. In case only ‘/’is provided in the target. It will open the URL as provided in base URL. Following are few ways in which open command works. Suppose base url is http://www.google.com, below are the scenarios
    •  / in target will open http://www.google.com/ (relative path)
    • /#q=google in target will open http://www.google.com/#q=google (relative Path)
    • http://www.rediff.com in target will open http://www.rediff.com (absolute Path). Similar to this is OpenWindow(url) This will open url provided in target in a new window.
  • type(Locator, value) - Types the value in the object identified by the locator. This can be used to set the value of combo boxes, check boxes, etc. Target will be object
  • Sendkeys(Locator, value) - This command types the value key-by-key defined in value on the object identified by Locator. It may be confusing for new users the use of sendkeys when type command already exists. The difference between Sendkeys and type is when we use sendkeys, it does not replace the existing content in the field, whereas when we use type, it replaces the content of the field. Both the methods are used to input data in an edit field.
  • Click(locator) – Clicks an object defined by locator in Target. In case we need to wait for page to load completely before performing further action, we use ClickandWait.
  • Select(Locator, value) This is used to select a value from a webList identified by Locator defined in target and sets the value as defined in the value. In case of Page load in case of selecting value from the weblist, use selectandwait.
  • Store(expression, variable Name) – This stores the value of element defined in expression in the target and stores in the variable name defined in value. This value can be used further in the test by using variable as $variableName.
  • Similar to store are storeAttribute(an element locator followed by a @ sign and then the name of the attribute, e.g. "id=name@href"), storeText(stores the text of an element) to name a few.waitForPageToLoad(time in millisecond) – This waits for the Page to Load completely in the time defined in target. Will move to next step in case the Page loads before the defined time
  • pause(time in milliseconds) – This is similar to wait statement and execution is paused for the time defined for pause command in target.
  • Refresh – This command refreshes the page.
  • verifyText(locator, expected pattern) – This compares the text in the locator element with the expected pattern defined in value. To provide a pattern, you can use text within *value*. This will verify if value appears in the text displayed for locator. Similar to verifyText, we can use verifynottext, verifyalert, verifyattribute to validate information in the Page.
  • AssertText(locator, expected pattern) – This compares the text in the locator element with the expected pattern defined in value. To provide a pattern, you can use text within *value*. This will verify if value appears in the text displayed for locator. Similar to AssertText, we can use Assertnottext, Assertalert, Assertattribute to validate information in the Page. Difference between Assert and verify is while test stops in case of assert fails but remaining statements in the test are executed in case of verify statement even if the verify statement fails.
  • Highlight(Locator) – highlights the object identified by locator in the page.
  • Break – This halts the test execution, test execution will continue once we click on continue in the IDE. This should be used in test but removed once test stabilizes as it results in manual intervention.
  • captureEntirePageScreenshot(filename) – This command captures screenshot and save in the location defined in filename in the target
  • check(locator) – this checks a radio button/checkbox based on locator defined in target.
  • Close() – This command simulates the user clicking the "close" button in the title bar of a popup window or tab
  • windowMaximize() – this command will resize currently selected window to take up entire screen


Different types of Selenese Commands

Selenese commands can be classified into following types:
a.    Actions – Performs action on an object. E.g. Click, type
b.    Assertions – Used to add validation steps. E.g. AssertText, verifytext
c.    Accessors – checks the state of application and stores values from the test. E.g. storetext.


Default timeout for Selenium Commands

Default timeout for selenium commands is 30000. The timeout can be changed from Options>General>default timeout of recorded command

Exporting selenium IDE tests to WebDriver

Script created in Selenium IDE can be exported to WebDriver/Remote Control in the languages java/c#/python/ruby that can be run using junit(java), RSpec(ruby), nUnit and testNG. 


To export test in TestNG with selenium webdriver, follow below steps:

  • Record the required operations on the application.
  • Go to File>Export Test Case as Java / TestNG / WebDriver (can export test script in different formats)
Exporting test in Selenium IDE

  • Export the test.
  • A java file will be created with content as shown below


package com.example.tests;

import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.testng.annotations.*;
import static org.testng.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class TESTINGAA {
  private WebDriver driver;
  private String baseUrl;
  private boolean acceptNextAlert = true;
  private StringBuffer verificationErrors = new StringBuffer();

  @BeforeClass(alwaysRun = true)
  public void setUp() throws Exception {
    driver = new FirefoxDriver();
    baseUrl = "https://www.google.co.in/";
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
  }

  @Test
  public void testINGAA() throws Exception {
    driver.get(baseUrl + "/?gfe_rd=cr&ei=_OMdWJKzEO3I8AeAqrBg&gws_rd=ssl");
    driver.findElement(By.id("lst-ib")).clear();
    driver.findElement(By.id("lst-ib")).sendKeys("TESTING AUTOMATION CONEPTS");
    assertTrue(isElementPresent(By.linkText("TESTING AUTOMATION CONCEPTS")));
    driver.findElement(By.linkText("TESTING AUTOMATION CONCEPTS")).click();
    driver.findElement(By.linkText("Test automation - Wikipedia")).click();
    assertTrue(isElementPresent(By.linkText("Test automation - Wikipedia")));
  }

  @AfterClass(alwaysRun = true)
  public void tearDown() throws Exception {
    driver.quit();
    String verificationErrorString = verificationErrors.toString();
    if (!"".equals(verificationErrorString)) {
      fail(verificationErrorString);
    }
  }

  private boolean isElementPresent(By by) {
    try {
      driver.findElement(by);
      return true;
    } catch (NoSuchElementException e) {
      return false;
    }
  }

  private boolean isAlertPresent() {
    try {
      driver.switchTo().alert();
      return true;
    } catch (NoAlertPresentException e) {
      return false;
    }
  }

  private String closeAlertAndGetItsText() {
    try {
      Alert alert = driver.switchTo().alert();
      String alertText = alert.getText();
      if (acceptNextAlert) {
        alert.accept();
      } else {
        alert.dismiss();
      }
      return alertText;
    } finally {
      acceptNextAlert = true;
    }
  }
}

Monday, November 7, 2016

Selenium IDE Panes and Shortcut keys



Selenium IDE Layout is divided into following areas: 


 MenuBar – Below are the top level menu options available in Selenium IDE.
  • File – Allows creating new test case, test suite, open existing test case, test suite, exporting tests to other formats.
    • From the File Menu, We can perform various tasks:
      • Create New Test Case.
      • Create new Test Suite.
      • Save test cases and test suites.
      • Export Test cases/test suites to various formats. E.g : Ruby/Python/java/c# with WebDriver or RC.
      • Open existing test cases and test suites.
      • Rename a test case
  • Edit – Allows editing existing test steps, and adding new commands and comments
  • Actions – Allows to record, play a test, execute command, toggle breakpoint and set entry point.
  • Options – Allows changing of settings including set the timeout value for commands,specifying the format used for saving test cases and creating log file for selenium execution
  • Help – provides documentation for selenium IDE.
Selenium IDE Layout
Understanding Panes in Selenium IDE

  •      Toolbar – Provides buttons to manage test execution including test execution and test execution.
  •      Test Case Pane – Test Case Pane shows the list of test case on the left and test steps in table or    source pane on the right. We can add/modify commands, target and value in the table for the test.
  •      Log/Reference/UI-Element/Rollup Pane – This pane helps us to view logs of execution, reference explaining the selected command. We can also set to filter logs for info, warning, error and debug in this window.

ShortCut Keys: Selenium IDE


New Test - Ctrl + N
Open a test - Ctrl + O
Save a test - Ctrl + S
Add test to test suite - Ctrl + D.
Close Selenium IDE - Ctrl + W
Undo - Ctrl + Z
Redo - Ctrl + Y
Cut - Ctrl + X
Copy - Ctrl + C
Paste - Ctrl + V
Delete - Del
Select All - Ctrl + A

Saturday, September 24, 2016

Importing an existing maven Project in eclipse in three steps.

An existing Maven Project can be imported in eclipse following simple steps as shown below.


1. In the eclipse workspace, click on File>Import.



 2. Select Maven>Existing Maven Projects

3. Browse to the folder location when Maven Project to be imported exist. Once the location is provided. It will search for the POM file. Select the file and click on Finish. Maven Project will be imported successfully.It will take a while to download dependencies and available to use.

Extracting Tooltip text using Selenium WebDriver : Quick Codes

Tooltip displayed for an element is identifed based on the attribute title defined for the element. Knowing that title of the element is the tooltip resolves half of the problem.


Suppose there is an element with id as abcde, the tooltip of the element can be stored in a string using code as below: 

Tooltip example


//example 1: getting tooltip of the elemet 
String strToolTipText = driver.findElement(By.xpath("//input[@id='abcde']").getAttribute("title");

//example 2 : Validating tooltip is displayed correctly for an webElement 
public boolean verifyTooltipText(WebElement webElem, String expToolTiptext)
 {
  String acttooltiptext = webElem.getAttribute("title");
  if(acttooltiptext.contentEquals(exptooltiptext))
  {
  return true
  }
  else
  {
  return false
 }
}

Monday, August 22, 2016

Tips for xpath identifcation for selenium

  • Importance of XPath in Selenium?

Selenium WebDriver identifies element based on locators. XPath is one of the most important locator used for identifying an element or group of elements. XPath uses path expressions to work with element in the application.

  •  Tools for identifying element using Xpath?

An element attribute can be identified by accessing developer toolbar (pressing F12 in browser windows) by in each of the browser.  There are add-ons/extensions which can be added in the browser.  One of the useful extensions for Firefox browser is downloading firebug followed by firepath and identifying elements using Xpath.



firepath for xpath

  • Xpath for the element in case the Id of the element is available
Xpath = “.//*[@id='gb_testing123']”

This will search for any element with id as 'gb_testing123'. In case there are various element in 
the page with id dynamically changing on each page load ,e.g: Id changes from gb_testing123 to 
gb_testing224. In such cases , we can have expression as :

Xpath = “.//*[contains(@id,'gb_testing')]” 

There may be multiple elements of different element type, Suppose there are different element type
and we want to restrict our xpath to a button element, we can modify the xpath in above expression 
as:

Xpath = “.//button[contains(@id,'gb_testing')]”

  • Xpath for the element in case the class of the element is available. 
Xpath = “//*[@class='gb_testing123']”
Or 
Xpath = “.//*[contains(@class,'gb_testing')]” 
Or 
Xpath = “.//div[contains(@class,'gb_testing')]”

  • Xpath for element in case of attribute value is available 
Xpath = “//*[@activated='1']”
Or
Xpath = “.//*[contains(@activated,'1')]” 
Or  
Xpath = “.//div[contains(@activated,'1')]”

  • Starts with Prefix for attribute value

//div[starts-with(@class,"gb_")]


  • Based on text displayed of the element

//*[text()='Software Testing Tutorial']


  •  Identifying element based on multiple attribute value


a. Xpath for element using combination of different attribute in AND condition
.//div[contains(@id,'hdtb')][@class='hdtbna notl']
Or
.//div[contains(@id,'hdtb')  and @class='hdtbna notl']


b. Xpath for element using combination of different attribute in OR condition
.//*[contains(@id,'hdtb') or @class='hdtbna notl']


  • Identifying xpath using different element types matching either A or B.


//a[contains(@id,'hdtb')]|//div[@class='hdtbna notl']

This will return element which are either links containing id as hdtb or 
div objects with class as 'hdtbna notl'


  • Child element of object type


//div[@id='viewport']/div
 This will return the immediate div elements in the div with id as viewport
//div[@id='viewport']//div
 This will return all the  div elements inside the div with id as viewport
//div[@id='viewport']/div[5]
 This will return the fifth div element immediate child inside the div with id as viewport


  • Parent element


//div[@class='rc']/.. 
 This will return the parent element
//div[@class=’rc’]/../a 
 Sibling link element to the div with class as rc.

Monday, August 15, 2016

Quick Code - How to right click an element and select menu option with selenium

Using action, we can perform right click(context click) operation on an object in selenium and also select the menu option using Arrows.down key press as shown in the code below:


Right click and select menu option


Quick Code:



public static void contextMenuSelection(WebElement webElem, int iOption)
      {
 //create an instance of actions class
       Actions action = new Actions(driver); 
 //context click (right click) the element
       action.contextClick(webElem);
       for(int i =1;i<=iOption;i++) 
       {
     //Press send keys for arrow down
        action.sendKeys(Keys.ARROW_DOWN);
       }
 //Press Enter send keys and build and perform the action.
       action.sendKeys(Keys.ENTER).build().perform();
      }

Tuesday, July 26, 2016

Quick Codes -How to highlight element using Selenium WebDriver

This code snippet shows one of the way to highlight an element using JavaScript executor in Selenium WebDriver. Please share your inputs on other ways to highlight an element using Selenium.



package testingqaautomation; 

import org.junit.Test;
import org.openqa.selenium.By;  
import org.openqa.selenium.JavascriptExecutor;  
import org.openqa.selenium.WebDriver;  
import org.openqa.selenium.WebElement;  
import org.openqa.selenium.firefox.FirefoxDriver;  
 
 public class HighlightWithJE {  
      static WebDriver driver; 
      @Test
      public void Testing() throws InterruptedException {  
  // Connect to the firefox driver server 
  driver = new FirefoxDriver(); 
  //maximise the browser   
  driver.manage().window().maximize();   
  //Navigate to the application, change url to a valid url
  driver.navigate().to("https://www.seleniumbites.blogspot.com");  
  //find element to highlight, select a valid element
  WebElement linkElem = driver.findElement(By.linkText("Gmail"));  
  //create instance of javascript executor
  JavascriptExecutor js = (JavascriptExecutor) driver; 
  //highlight the element to green color and wait
  //for 3 sec and then click the element
  js.executeScript("arguments[0].setAttribute('style','border: solid 8px green')", linkElem);   
  Thread.sleep(3000);  
  js.executeScript("arguments[0].setAttribute('style', arguments[1]);", linkElem, "");  
  linkElem.click();            
      } 
}   

Tuesday, June 14, 2016

Understanding Locators in Selenium WebDriver and common element types

Locators are used to identify an element in the WebPage.  An object can be identified based on the attributes values.  In this article, we will discuss the different locators based on which an element can be identified in the page using selenium webdriver.


Locators are used to locate an element in the Page based on the unique address of the object in the Page. It can be unique attribute value, for e.g: id of the element or the absolute or relative xpath of the element in the Page. 


Once an object is identified in the Page, we can perform the required operation/action on the object. Below are the different common types of elements on the Page:


Common Elements Types
Type
Common Operations on Object Type
Anchor elements or links
Clicking on a link
Validating links in Page are correct or broken
Validating links exist in the Page
TextBox
Validating text box is available/enabled
Input data in the edit box
Radio Button
Selecting a radio button
Checkbox
Validating whether checkbox is selected or not.
Selecting/deselecting checkbox
DropDown
Selecting value from the dropdown
Labels
Extracting value from the label or validating label exist in the page.
Table
Extracting information from table.
Multi-Select ComboBox
Selecting multiple values from a combobox.


The different types of locators used to locate elements in selenium are described below:


Locator Types
Locator DefinitionUsage
IDelement matching "id" attribute of the element. Normally id of an element in the Page is expected to be unique. Hence if available, using id of the element is good option.
WebElement usr = driver.findElement(By.id("name"));
 Nameelement matching "name" attribute of the element. There may be multiple element with same name in Page. In such scenario, first element matching the name is selected.
WebElement usr = driver.findElement(By.name("uname"));
 Link Text
Partial Link text
For links in the Page, we can use linktext and partialLinkText to identify the links based on the name/Partial text of the link. Applicable for links element only

WebElement elem=driver.findElement(By.linkText("mail"));

driver.findElement(By.partialLinkText("mail"));
 CSS SelectorUsing CSS locators, we can identify elements. Both Xpath and CSS are useful and highly used in identifying elements in the Page.Absolute or relative Xpath can be created to identify element in the PageWebElement elem = driver.findElement(By.cssSelector("a.test"));
 XPathPlease refer to my previous post for details on xpath and css:
http://seleniumbites.blogspot.in/2016/01/xpath-and-css-for-selenium-webdriver.html
WebElement elem = driver.findElement(By.xpath("//input[@id='mail']"));
ClassNameClassName uses the class attribute of the element to locate the element. Foe e.g.: in case of identifying the random error message displayed in the Page, usually the message may have the same class attribute. We can create a collection of elements matching the class and gather the required error messages in the Pagedriver.findElement(By.className("errormessage"));
TagNameThis locator is useful while working with list of elements in the Page. E.g: Finding number of links in the PageList <WebElement> linklst = driver.findElements(By.tagName(“a”));