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

Monday, May 15, 2017

Jenkins - Adding a conditional build step.

In Jenkins, at times we may require Jenkins to execute some build step on one condition and another in case of other condition. For e.g: It may be required to run a particular test/batch command on Weekdays and some other batch condition on weekends. We can create a job to perform different tasks based on the condition satisfied. 

To add a conditional build step, follow below steps in Jenkins.

  • Navigate to Jenkins>Manage Jenkins>Manage Plugins and go to available tab.
  • Search for Conditional buildstep as shown below and click on install without restart.
  • It will install the plugin and will show success once installation completes.
  • Now the plugin can be used in the Jenkins job as shown below.In the job, add build step as Conditional step (single)

  • Provide the conditional step from the list as shown below and execute the build command.







Saturday, April 8, 2017

How to identify and close window alert using selenium

At times in browser,Alert box with a specified message and an OK button is displayed to ensure information comes through to the user. 

Alert box prevents the user from accessing other parts of the page until the box is closed. An alert is displayed is as shown below:

an example of alert window

While automating the web application, we can handle the pop up using alert Interface
The alert() method displays an alert box with a specified message and an OK button.

Below code shows how to close an window alert pop up using selenium:



public void Accept_Alert_Message() {
    try {
  //Using webdriver wait, we will wait for the alert
  //to appear before performing action on the alert
        WebDriverWait driverwait = new WebDriverWait(driver, 5);
        driverwait.until(ExpectedConditions.alertIsPresent());
  //switch to the alert element
        Alert alert = driver.switchTo().alert();
  //accept the alert displayed
        alert.accept();
  //switch to the default content
  driver.switchTo().defaultContent();
    } catch (Exception e) {
     // in case alert is not displayed, the code will go to catch loop
    }
}

Tuesday, March 14, 2017

How to select values in dropdown using select in Selenium


  •  How to define an element of type dropdown or tag as select: We can define a element of type dropdown using the statement as shown below:             



Select selectElement = new Select(driver.findElement(By.id("SelectApp")));

  • Example of Select tag in html page: Below example shows how the values are defined in a select dropdown.


<select id="SelectApp">
<option value="Facebook">FB</option>
<option value="TasteBook">TB</option>
<option value="ClassBook">CB</option>
<option value="HomeBook">HB</option>
<option value="TestBook">TTB</option>
</select>


  • SelectByValue would select the option from the dropdown for option: <option value="Facebook">FB</option> if provided. selectByValue: Selects value based on argument value for the tag.

 selectElement.selectByValue("Facebook");  

  • selectByVisibleText: Select value based on the text of the tag


selectElement.selectByVisibleText("FB");        

  • selectByIndex: select the fifth dropdown using selectByIndex



 selectByIndex.selectByIndex(4);              

Tuesday, December 6, 2016

Tutorials to understand TestNG for Selenium Webdriver

Installing TestNG in eclipse - This post explains how to install TestNG in eclipse.


MindMap for TestNG - Understanding the concept in TestNG using MindMap.


Annotations in TestNG - Different annotations used in TestNG 


Assertion and Soft Assertions in Selenium Webdriver using TestNG - What are different assertions and soft assertions in selenium webdriver. What is the difference between assertions and soft assertion. How to use assertion in the test.


Maven POM.xml: Dependencies for Selenium, TestNG and junit - How to add TestNG dependenies in maven project.


Using dependencies and priority in TestNG tests: Ordering tests execution - how to define dependencies between tests and priotising order of tests execution in TestNG.


Creating TestNG.xml to run Selenium test suites - How to create testNG xml file for executing testsuite in TestNG. This article explains, how to create xml file for execution in  different scenarios.


How to run multiple test suites in TestNG? - Suppose we have individual suite for different module. This article explains how to create testNG xml file to run multiple test suites.


Maven POM.xml: Dependencies for Selenium, TestNG and junit - How to add dependencies for TestNG in Maven POM.xml

Sunday, November 27, 2016

Validating conditions using assert and verify in Selenium IDE

The purpose of any automation/manual tests is to validate the application is working correctly and validating the actual outcome with the expected outcome for a condition.


  • Now the first question arises, what are the commands in selenium IDE which validates the outcome of condition There are different commands in different tools/automated suite. In selenium IDE, we can use assert or verify commands to validate the results.
  • Now the question two arises, what is the difference between assert and verify commands, When we use Assert command, it checks whether the given condition is true or false and stops further test execution if the assert statement fails. In case of verify command, in case the execution fails, the execution moves to next step in the test although the test is marked as failed.
  • Now coming to question three, when to use verify or assert command. In case of critical condition failing and no point to continue with test, use assert command. In case of minor condition failing in the test and we still wants to continue with further steps in the test, we can use verify statement.
  • So what is the next logical question in mind, when and how  to add the validation steps in test.Since Selenium IDE is a record and play tool,
    • Record execution flow. Once execution flow is recorded, we can add assertions in Selenium IDE.
    • Just right click the element on which the condition needs to be verified in Firefox browser e.g : Validating the text of the link. 
    • Click on the assertion to be added as shown below:

Add assertions selenium IDE


Similar to assert/verify commands in selenium IDE, we can use assert and soft.assert class for assert and verify command in Selenium Webdriver.

How to run test with random data in Selenium IDE: store and storeText Command

Selenium IDE is a tool for record and play functionality, which runs the script with same set of data, however we can generate random data. store the values in a variable , and use the value stored in the variable in the later steps in the test.


Expected Learning from this article:

  • Store command to store random generated data in the a variable. 
  • Using the stored information in later steps in the test.
  • Using command storeText to store value of an object in the test and storing in a test.
  • Using the stored information in later stage in the test.



Below screenshot shows how to use store and storetext in the test:




  • In the above test, we open an application and save the text of the link in variable using command storeText. test in Value is the variable in each we can store the value of the link/object.
  • In the next step, we can use the value in the variable using ${variable_name} which is ${test} in our example.
  • Similarly using store command and javascript, we can generate random data, store in the variable and use further in the test.
  • We have saved the test in an html file and the test file looks as below:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://selenium-ide.openqa.org/profiles/test-case">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="https://www.google.co.in/" />
<title>testing stored value</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">testing stored value</td></tr>
</thead><tbody>
<tr>
 <td>open</td>
 <td>/search?q=selenium&amp;ie=utf-8&amp;oe=utf-8&amp;client=firefox-b-ab&amp;gfe_rd=cr&amp;ei=r4E6WIqnEeXI8AfOn6awBw</td>
 <td></td>
</tr>
<tr>
 <td>storeText</td>
 <td>link=Selenium - Web Browser Automation</td>
 <td>test</td>
</tr>
<tr>
 <td>type</td>
 <td>id=lst-ib</td>
 <td>${test}</td>
</tr>
<tr>
 <td>click</td>
 <td>name=btnG</td>
 <td></td>
</tr>
<tr>
 <td>store</td>
 <td>javascript{&quot;Selenium&quot; +Math.random();}</td>
 <td>testrandom</td>
</tr>
<tr>
 <td>type</td>
 <td>id=lst-ib</td>
 <td>${testrandom}</td>
</tr>
<tr>
 <td>click</td>
 <td>name=btnG</td>
 <td></td>
</tr>

</tbody></table>
</body>
</html>

Copy paste the code in a text file and save in html format. Open the test in Selenium Ide and try to run the test and understand how to run test with random data in selenium IDE.

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.

Sunday, November 20, 2016

Installing Selenium IDE add-on in firefox

Selenium IDE is a record and play automation IDE/add-on with Firefox. It is very simple to install selenium IDE and creating automated script in selenium which can then be imported in different languages and formats. In this article, we will explain how to install Selenium IDE in firefox.
  • Pre-condition: Firefox browser is installed. 
  • Installation steps:
    • Search Selenium IDE and click on the link as shown below:
Selenium IDE link
    • Click on the link.In the add-ons Page, click on Add to Firefox
Selenium IDE add-on
developer selenium IDE
    • Once the add-on is installed, Selenium IDE can be accessed by navigating to developer>Selenium IDE or pressing Alt + Ctrl + S
    • This will open Selenium IDE on which we can record and play on the applications.

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

Friday, November 18, 2016

scrollIntoView JavaScriptExecutor - How to Scroll until element is visible

We can scroll to an element using Action class or JavaScript executor, Below code can be useful in case you encounter such a scenario in selenium Webdriver:


A. Using JavaSript Executor - scrollIntoView


Provide parameter value as true or false for scrollIntoView
true - Provide value as true if the element is below in the page from the current scroll position
false - Provide value as true if the element is below in the page from the current scroll position


WebElement webElement = driver.findElement(By.xpath("element xpath"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", webElement);
Thread.sleep(500); 


B. Using Actions - MovetoElement method


WebElement webElement = driver.findElement(By.xpath("element xpath"));
Actions actions = new Actions(driver);
actions.moveToElement(webElement);
actions.perform();

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

Sunday, September 25, 2016

Switching to frame, Windows, alert in Selenium WebDriver

1. How to Switch from one frame to another

 // How to Switch from one frame to another  
 WebElement iFrmeElement = driver.findElement(By.xpath("xPath for Frame"));  
 driver.switchTo().frame(frameElement);  
 //Or  
 driver.switchTo().frame(id or name)  
 //Or  
 driver.switchTo().frame(index of frame)  

2. We can switch to default again by:

 driver.switchTo().defaultContent();  

3. We can switch to a window based on name, Id or Windows handle

 driver.switchTo().window("windowName");  

4. We can switch to an alert

 Alert alert = driver.switchTo().alert();  
 // We can close an alert using methods for alert object  
 alert. accept();  

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
 }
}