Automation Using Selenium Webdriver

Thursday, 20 October 2016

Enter a text without using SendKeys method() in Selenium Webdriver

How to Send text without using sendkeys methods

public class type{

public static void setattribute(WebElement element,String attributename,String Value){

WrapsDriver wrappedElement=(WrapsDriver)element;
JavascriptExecuter driver =(JavaScriptExecutor)wrappedElement.getWrapedDriver;
driver.executeScript(arguments[0].setAttribute(arguments[1],arguments[2]",element,
                                    attributeName,value);
}

//or

JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("document.getElementById('email').value = 'thotajagan@gmail.com';");


Onemore Example:

driver.get("http://facebook.com/");
WebElement cssValue= driver.findElement(By.xpath(".//*[@id='s']"));
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("document.getElementById('s').value='Virender Testing   
sending'");

Wednesday, 19 October 2016

PageObject Facebook test Real time Scenario Example

****************************************************************
    ***            Facebook MainPageObject Start                                      ****
_________________________________________________________________
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

public class FacebookMainPageObject extends WikiBasePageObject {

  @FindBy(css = "#email")
  private WebElement emailField;
  @FindBy(css = "#pass")
  private WebElement passwordField;
  @FindBy(css = "#loginbutton")
  private WebElement loginButton;

  public FacebookMainPageObject(WebDriver driver) {
    super();
  }

  public FacebookUserPageObject login(String facebookEmail, String facebookPassword) {
    typeEmail(facebookEmail);
    typePassword(facebookPassword);
    clickLoginButton();
    return new FacebookUserPageObject(driver);
  }

  public void clickLoginButton() {
    wait.forElementVisible(loginButton);
    loginButton.click();
    PageObjectLogging.log("clickLoginButton", "facebook login button clicked", true);
  }

  private void typePassword(String password) {
    wait.forElementVisible(passwordField);
    passwordField.sendKeys(password);
  }

  private void typeEmail(String email) {
    wait.forElementVisible(emailField);
    emailField.sendKeys(email);
  }
}
*****************************************************************************
   *                                   FacebookSettingsPageObject.java                                          *
_____________________________________________________________________________


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

import java.util.List;

public class FacebookSettingsPageObject extends WikiBasePageObject {

  @FindBy(css = "#pageLogo")
  private WebElement pageLogo;
  @FindBy(css = "#pop_content .uiButtonConfirm")
  private WebElement removeButton;
  @FindBy(css = ".pop_container_advanced")
  private WebElement removeAppConfirmationModal;
  @FindBy(css = "._4bl7")
  private List<WebElement> pageElementList;
  @FindBy(css = "#userNavigationLabel")
  private WebElement fbDropDown;
  @FindBy(xpath = "//span[text()='Log Out']")
  private WebElement fbLogOut;

  public FacebookSettingsPageObject(WebDriver driver) {
    super();
  }

  public FacebookSettingsPageObject open() {
    getUrl(URLsContent.FACEBOOK_SETTINGS_APP_TAB);

    return this;
  }

  public void verifyPageLogo() {
    wait.forElementVisible(pageLogo);
    PageObjectLogging.log("verifyPageLogo", "Page logo is present", true);
  }

  /**
   * from facebook Apps.
   */
  public FacebookSettingsPageObject removeAppIfPresent() {
    if (isAppPresent()) {
      for (WebElement element : pageElementList) {
        if (element.getText().toString().matches("^Wikia.*\n?.*")) {
          wait.forElementVisible(element);
          element.click();
          WebElement AppRemoveButton =
              element.findElement(By.xpath("//a[contains(text(), 'Remove')]"));
          if (AppRemoveButton != null) {
            wait.forElementVisible(AppRemoveButton);
            AppRemoveButton.click();
            wait.forElementVisible(removeButton);
            removeButton.click();
            waitForElementNotVisibleByElement(removeAppConfirmationModal);
            driver.navigate().refresh();
            try {
              Thread.sleep(3000);
            } catch (InterruptedException e) {
              PageObjectLogging.log("SLEEP INTERRUPTED", e, false);
            }

            PageObjectLogging.log("removeApp", "Wikia App removed", true);
          }
        } else {
          PageObjectLogging.log("removeApp", "Wikia App not found", true);
        }
      }
    }
    return this;
  }

  /**
   * This method verifies if App is present on facebook apps list. It searches  string.
   */
  private boolean isAppPresent() {
    try {
      Thread.sleep(3000);
    } catch (InterruptedException e) {
      PageObjectLogging.log("isAppPresent", e, false);
    }
    boolean isPresent = false;
    for (WebElement element : pageElementList) {
      if (element.getText().toString().matches("^Wikia.*\n?.*")) {
        isPresent = true;
      }
    }
    return isPresent;
  }

  public void logOutFB() {
    wait.forElementVisible(fbDropDown);
    fbDropDown.click();
    wait.forElementVisible(fbLogOut);
    fbLogOut.click();
  }
}

**************************************************************
  *                       Facebook User PageObject                                        *
______________________________________________________________

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

public class FacebookUserPageObject extends WikiBasePageObject {

  @FindBy(css = "a[href$='?ref=logo']")
  private WebElement pageLogo;

  public FacebookUserPageObject(WebDriver driver) {
    super();
  }

  public void verifyPageLogo() {
    wait.forElementVisible(pageLogo);
    PageObjectLogging.log("verifyPageLogo", "Page logo is present", true);
  }

  public FacebookSettingsPageObject fbOpenSettings() {
    getUrl(URLsContent.FACEBOOK_SETTINGSPAGE);
    return new FacebookSettingsPageObject(driver);
  }
}
**********************************************************************************
                     PageObject for facebook   Ends
______________________________________________________________________________*____

how to delete default values in text field using selenium

Selenium WebDriver:  overwrite value in field instead of appending to it with sendKeys using Java

Use this Code:

element.sendKeys(Keys.chord(Keys.CONTROL, "a"), "55");


how to delete default values in text field using selenium:
Use this Code

WebElement toClear = driver.findElement("locator");
toClear.sendKeys(Keys.CONTROL + "a");
toClear.sendKeys(Keys.DELETE);

Selenium: delete contents from a textbox


The keyPress event of selenium can be helpful:

selenium.sendKeys("text1", "ABCD");
selenium.sendKeys("text1", "\b");
selenium.sendKeys("text1", "\b");

This will Click Backspace key twice

Significance of Maven,Svn,Jenkins in selenium webdriver

Significance of Maven,Svn,Jenkins in selenium webdriver?

Most Important in Selenium webdriver this topics and uses


The tools you name are used during different steps in the SDLC, they can be replaced by other
alternative tools

Example (partial) development life cycle:
Programming -> Check-in to version control -> Schedule build and run build -> Run automated test --->against build -> Report failing tests/buildsCheck-in to version control

After developers are finished with development they Check-In the code into a version controlsystem,
this to keep a history of all the changes. SVNs relation to Selenium testing is that you want to test against the latest version of the application. Also its advisable to keep the test-code close to the
application code and I would version it in the same repository.

Schedule build and run build

The build-server / continuous integration server monitors the version control, checks out any changes
and schedules a build against this version. Relation to Selenium testing is that Jenkins can prepare
the application and set it up in such a state that you can run the tests against it. Its possible to
use Maven as a tool to automate the building,integrating and or setup of the application instead of
using shell scripts.

Run automated test against build

After the build is OK, the build-server checks out and starts the Selenium tests. Maven can be used to
 build and start tool that is fired by Jenkins to trigger the test start

Report failing tests/builds

The build-server reports any failing tests in its main overview or sends out e-mail to the person who
broke or monitors the build.

Alternative tools:

Build-tools
Build-servers
Version control systems

@ TestNG Annotations & Uses

TestNG Annotations

@BeforeSuite: The annotate method will be run before all tests in this suite have run.
@AfterSuite: The annotated method will be run after all tests in this suite have run.
@BeforeClass: The annotated method will be run before the first test method in the current class is
 invoked.
@AfterClass: The annotated method will be run after all the test methods in the current class have been run.
@BeforeTest: The annotated method will be run before any test method belonging to the classes inside the tag is run.
@AfterTest: The annotated method will be run after all the test methods belonging to the classes inside the tag have run.
@BeforeMethod: The annotated method will be run before each test method.
@Test: The annotated method is a part of a test case.
@AfterMethod: The annotated method will be run after each test method.
@DataProvider: The annotated method provides data to the @Test methods.
The annotated method returns an Object [][].
@BeforeGroups: The list of groups that this configuration method will run before.
This method is guaranteed to run shortly before the first test method that belongs to any of these
groups is invoked.
@AfterGroups: The list of groups that this configuration method will run after.
 This method is guaranteed to run shortly after the last test method that belongs to any of these
groups is invoked.

alwaysRun----> For before methods (beforeSuite, beforeTest, beforeTestClass and                     beforeTestMethod,but not beforeGroups): If set to true, this configuration method will be run regardless of what groups it belongs to. For after methods (afterSuite, afterClass, ...): If set to true, this configuration method will be runeven if one or more methods invoked previously failed or was skipped.
dependsOnGroups----> The list of groups this method depends on.
dependsOnMethods----> The list of methods this method depends on.
enabled                  -----> Whether methods on this class/method are enabled.
groups                 ------>The list of groups this class/method belongs to.
inheritGroups      ------->If true, this method will belong to groups specified in the @Test annotation
at the class level.

package testng;

import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class TestNGAnnotations {

 @BeforeSuite
 public void instantiate() {
  System.out.println("Instantiate Object");
 }

 @BeforeTest
 public void dataBaseConnection() {
  System.out.println("Database Connected");
 }

 @BeforeMethod
 public void BeforeMethod() {
  System.out.println("Run before each Test Case.");
 }

 @Test
 public void testCase1() {
  System.out.println("First Test Case Result..... ");
 }

 @Test
 public void testCase2() {
  System.out.println("Second Test Case Result.... ");
 }

 @AfterMethod
 public void AfterMethod() {
  System.out.println("Run after each Test Case");
 }

 @AfterTest
 public void dataBaseDisconnection() {
  System.out.println("Database Disconnected");
 }

 @AfterSuite
 public void destory() {
  System.out.println("Destory Object");
 }
}
Create testng.xml:

testng.xml: Right click on Project --> TestNG --> Convert to TestNG.

<!--?xml version="1.0" encoding="UTF-8"?-->

<suite name="Suite" parallel="none">
  <test name="Test">
    <classes>
      <class name="testng.TestNGAnnotations">
    </class></classes>
  </test> <!-- Test -->
</suite> <!-- Suite -->
Execute TestNG:
Right click on testng.xml --> Run As --> TestNG Suite OR Right click on java file -->
 Run As --> TestNG Test

OUTPUT:


Download file using Selenium WebDriver with AutoIt and Sikuli

Download file using Selenium WebDriver with AutoItand Sikuli
Selenium can not handle the Download file window. We can use third party tools to handle download
file window. Some of the tools are AutoIT and Sikuli.

AutoIT: Save the below script with extension as download_file.au3 and compile it then it will generatedownload_file.exe file.

Local $pathToSave=$CmdLine[1]
Local $windHandle=WinGetHandle("[Class:IEFrame]", "")
Local $winTitle = "[HANDLE:" & $windHandle & "]";
;get coordinates of default HWND
Local $ctlText=ControlGetPos ($winTitle, "", "[Class:DirectUIHWND;INSTANCE:1]")

; wait till the notification bar is displayed
Local $color= PixelGetColor ($ctlText[0],$ctlText[1])
while $color <> 0
sleep(500)
$ctlText=ControlGetPos ($winTitle, "", "[Class:DirectUIHWND;INSTANCE:1]")
$color= PixelGetColor ($ctlText[0],$ctlText[1])

wend
; Select save as option
WinActivate ($winTitle, "")
Send("{F6}")
sleep(500)
Send("{TAB}")
sleep(500)
Send("{DOWN}")
sleep(500)
Send("a")

WinWait("Save As")
; activate Save As window
WinActivate("Save As")
; path to save the file is passed as command line arugment
ControlFocus("Save As","","[CLASS:Edit;INSTANCE:1]")
Send($pathToSave)
sleep(500)
;click on save button
ControlClick("Save As","","[TEXT:&Save]")

; wait till the download completes
Local $sAttribute = FileGetAttrib($pathToSave);
while $sAttribute = ""
sleep(500)
$sAttribute = FileGetAttrib($pathToSave)
wend
sleep(2000)
;close the notification bar
WinActivate ($winTitle, "")
Send("{F6}")
sleep(300)
Send("{TAB}")
sleep(300)
Send("{TAB}")
sleep(300)
Send("{TAB}")
sleep(300)
Send("{ENTER}")

import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class DownloadFile_IE_AutoIT {

 public static void main(String[] args) throws InterruptedException {
  System.setProperty("webdriver.ie.driver",System.getProperty("user.dir")+"\\IEDriver.exe");
  WebDriver driver = new InternetExplorerDriver();
  driver.manage().window().maximize();
  driver.get("http://www.seleniumhq.org/download/");
  driver.findElement(By.xpath("//*[@id='mainContent']/p[9]/a[2]")).sendKeys(Keys.ENTER);
  try {
   String path="E:\\AutoIT\\test232";
   String file="E:\\AutoIT\\download_file.exe"+" "+path;
         Runtime.getRuntime().exec(file);
     } catch (IOException e) {
   e.printStackTrace();
  }
 }
}
AutoIT: Download AutoIT from http://www.autoitscript.com/site/autoit/downloads/
Once you install AutoIT in system. Write a autoit script to handle the authentication window.
WinWaitActive("Windows Security")
Send("username")
Send("{TAB}")
Send("password")
Send("{ENTER}")
Save this file as “auth.au3"
Right click on the file and chose “Compile Script (x86)” option and it will make “auth.exe”
Now write the sample java code to use it
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class WinAuthentication_Autoit {

 public static void main(String[] args) {
  System.setProperty("webdriver.ie.driver",System.getProperty("user.dir")+"\\IEDriver.exe");
  WebDriver driver = new InternetExplorerDriver();
  driver.get("http://codesorcery.net/old/authentication/secret/");
  try {
   Runtime.getRuntime().exec("E:\\AutoIT\\Auth.exe");
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

How to verify element present or visible in selenium 2 (Selenium WebDriver)


Verify Element Present or Visible in Web Application Check
1.ispresent
2.isvisible
3.isenable
4.textpresent

in Selenium WebDrvier using Java

To check Element Present:

if(driver.findElements(By.xpath("value")).size() != 0){
System.out.println("Element is Present");
}else{
System.out.println("Element is Absent");
}

                  OR
if(driver.findElement(By.xpath("value"))!= null){
System.out.println("Element is Present");
}else{
System.out.println("Element is Absent");
}

To check Visible:

if( driver.findElement(By.cssSelector("a > font")).isDisplayed()){
System.out.println("Element is Visible");
}else{
System.out.println("Element is InVisible");
}


To check Enable:

if( driver.findElement(By.cssSelector("a > font")).isEnabled()){
System.out.println("Element is Enable");
}else{
System.out.println("Element is Disabled");
}

To check text present:

if(driver.getPageSource().contains("Text to check")){
System.out.println("Text is present");
}else{
System.out.println("Text is absent");
}