Sunday, November 23, 2014

Verify CSS (font, background color, etc) using selenium WebDriver


driver.findelement(By.Xpath("Xpath ").getcssvalue("font-size);
driver.findelement(By.Xpath("Xpath ").getcssvalue("font-colour);
driver.findelement(By.Xpath("Xpath ").getcssvalue("font-type);
driver.findelement(By.Xpath("Xpath ").getcssvalue("background-colour);

Error Collector in TestNg


  • Assert will stop its execution on test failure but it is must instead for better automation we have to use it as maximum as possible. 

                          If needs to pass the test 

                          try{ 
                                  Assert.assertequals(true,false); 
                              }
                           catch(Throwable ex){ 
                                   System.out.println("The case will pass"); 
                              } 

              but here u wont get the case marked failed



  • Use try catch, when test case fails, inside catch write "throw new RuntimeException();" so that it will capture in the TestNG report as fail
  • TestNG has support for custom listeners, which can run when tests pass/fail/skip, as well as before and after invocation. By adding a custom listener to check for verification failures after invocation, we can get the details of all verification failures that have occurred, and report them at the same time as we report our hard failure, or if there are no hard failures we can change the result to a failure and report the verification failures.

          This solution uses part of the TestNG soft failures patch by Dan Fabulich in order to combine the stack                 traces of multiple failures. Details of the patch are available here.

  • Class ErrorCollector :-The ErrorCollector rule allows execution of a test to continue after the first problem is found (for example, to collect _all_ the incorrect rows in a table, and report them all at once):

package myWorkjUnit; 
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;
 
public class UsesErrorCollectorTwice {
 /*
 * The ErrorCollector Rule allows execution of a test to continue after the
 * first problem is found and report them all at once
 */
 @Rule
 public ErrorCollector collector= new ErrorCollector();
 
@Test
 public void example() {
 collector.addError(new Throwable("first thing went wrong"));
 collector.addError(new Throwable("second thing went wrong"));
 
 // all lines will run, and then a combined failure logged at the end.
 }
 
}


Thursday, November 20, 2014

Reference sites for FQA on Webdriver


WebDriver:
https://code.google.com/p/selenium/wiki/FrequentlyAskedQuestions
http://www.studyselenium.com/2013/12/100-selenium-interview-questions.html
http://www.toolsqa.com/selenium-webdriver/selenium-interview-questions-part-1/

https://docs.google.com/document/d/1VWrD608H3tQCxWzfHsAfFb_Tx8BYUMj-K8Cffy_60mc/edit?usp=sharing


JavaScripExecutor
http://www.mythoughts.co.in/2013/02/executing-javascript-using-selenium.html#.VG7pR_mUdhx

Grid
http://qtp-help.blogspot.in/2011/08/selenium-grid-for-browser-compatibility.html

Monday, April 1, 2013

Xpath customization

If  xpath is unable to locate the element with IDs then other ways of creating the xpath is as below :-


Let say DOM structure is as below

<div class = "items">
       <div id="slide_page1" class="page" style="display: none;">
       <div id="slide_page2" class="property_div" style="">
                    <div id="head_text">
            <div class="service_list">
            <div class="service_list">
            <div id="toggle" class="tshow">
            <div class="service_list_button">
                 <button id="page_back" class="back_button" href="#"                                      onclick="hide_slide('slide_page2','slide_page1','back_button'); return false;" tabindex="5" title="Back" type="button"></button>

               <button id="zipcode_button" class="continue_button" onclick="hide_slide('slide_page2', 'slide_page3','')" tabindex="4" title="Continue" type="button"></button>
          </div>


And you want to click on button id = zipcode_button



Typically we write the xpath as below :
driver.findElement(By.xpath("//*[@id='zipcode_button']")).click();

                                                           OR
driver.findElement(By.xpath("//*[@id='zipcode_button' and  @class='continue_button'  and @type='button']"

                                                        OR

For Hyper Linked     :- "//a[@href= '/computer-periferal']"

                                                OR
If portion of xpath is constant   :-  "// input[@id, 'linktitle']"

                                                   OR

driver.findElement(By.xpath("//*[@id='zipcode_button']")).sendKeys(Keys.ENTER);


                                                   OR

Take the id of 1st element in DOM structure and id of element on which we are performing an action
 //div[@id='slide_page4']//button[@id='zipcode_button']
In the above xpath          [@id='slide_page4'] --> Id of first element in DOM

                                    [@id='zipcode_button']-----> id of element on which we are performing an action


                                                    OR

driver.findElement(By.xpath("//div[@id='slide_page2']/div[5]/button[2]")).click();

                                                    OR



WebElement parentelement=driver.findElement(By.xpath(".//div[@class='items']"));
List<WebElement> ListOptions=parentelement.findElements(By.xpath(".//div[starts-with(@id,'slide_page')]"));
System.out.println(ListOptions.size());
WebElement childele=ListOptions.get(1);
WebElement clickbutton=childele.findElement(By.xpath(".//button[starts-with(@id,'zipcode_button')]"));
System.out.println(clickbutton.isDisplayed());
clickbutton.click();

                                              And


price of say 1st property, we can use xpath like:
//li[starts-with(@id,'summary')][position()=1]//p[@class='price']


Thursday, March 7, 2013

Testng.xml file functionality and contains

TestNG.xml file is use to run the test in batch mode . below is the format for testng.xml file 

Save the below could as build .xml file report and run it , all the method associate with this testNG.xml file will executated



<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
// This is  the Suite name is which can be any thing
<suite name="LeadForm">
// This is the test name . again it can assign as per the our convenience

     <test name="google Lead Form Home Equity Service" >
    <classes>
// This is the name of class and it is case sensitive hence hQF is package name and   HomeEquity is class name

           <class name="hQF.HomeEquity"> </class>
      </classes>
     </test>

  <test name="google Lead Form Refinance" >
   <classes>
     <class name="hQF.Refinance"> </class>
     </classes>
  </test>
   
    <test name="google Lead Form Dept Service" >
   <classes>
           <class name="hQF.DebtConsolidation"> </class>
    </classes>
    </test>
 
    <test name="google Lead Form New Home Service" >
    <classes>
           <class name="hQF.NewHomeLoan"> </class>
      </classes>
     </test>
   
   

</suite>




WebDriver using TestNG annotations


If you are using the TestNG Annotation then no need to use the main() function . it is not supporting to main function. Simply use function :-

package hQF;

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class Refinance {

// Useing teh Annontation Test So used normal function
 @Test
 public static void Test() throws InterruptedException
// public static void main(String[] args) throws Exception {
final String var = "prog_bg";
WebDriver driver = new FirefoxDriver();
// WebDriver driver = new InternetExplorerDriver();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://hsh.com");
Thread.sleep(1000);
List<WebElement> DefualtRadio = driver.findElements(By
.xpath("//input[@value='REFI']"));
System.out.println("ByDefault Refinance radio is selected  "
+ DefualtRadio.get(0).getAttribute("checked"));
}
    else {
// Call the test method
      Test();
       }

Monday, February 11, 2013

WebDriver : use of Iterator to retrieve all the elements present in same class

Webdriver  program will help to use of Iterator to retrieve all the elements present in same class 
calling the main function again .


package hQF;
import static org.testng.AssertJUnit.assertTrue;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Keys;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.opera.core.systems.scope.protos.EcmascriptProtos.Object;

public class HAH1
{
public static void   main(String[] args)throws Exception
{
final String var = "prog_bg";
// final var means variable var's value never been change 
WebDriver driver = new FirefoxDriver();
driver.get("http://hweh.com");
Thread.sleep(1000);
driver.findElement(By.xpath("//input[@value='REFI']")).click();
// Select the values from dropdown field 
Select Droplist = new Select ( driver.findElement(By.name("propertyStateCode")));
Droplist.selectByVisibleText("California");
driver.findElement(By.className("MFC_submit")).click() ;
Thread.sleep(2000);
// Implicitly tell the browser to wait for 10 second. so that object is rendered. please use this command then Thread.sleep
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
// If  id='prog_bg' is present in source code then execute teh following code  
if(driver.findElements(By.xpath("//div[@id='prog_bg']")).size()!=0)
{
try{
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
driver.findElement(By.xpath("//div[@id='propertyvalue-div']/div[2]/button")).click();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
}
catch(Exception e){};

try{
driver.findElement(By.tagName("body")).getText().contains("Total Mortgage Balance");
Thread.sleep(100);
driver.findElement(By.xpath("//div[@id='mortgagebalance-div']/div[2]/button")).click();
System.out.println("Total Mortgage Balance is present");
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
}
catch(Exception e){
System.out.println("Total Mortgage Balance is NOT present");
}
try {
driver.findElement(By.tagName("body")).getText().contains("Approximately, how much cash");
driver.findElement(By.xpath("//div[@id='cashout-div']/div[2]/button")).click();
System.out.println("Approximately, how much cash would you like to receive at closing? is  present");
}
catch(Exception e){
System.out.println("Approximately, how much cash would you like to receive at closing? is NOT present");
}
try {
driver.findElement(By.tagName("body")).getText().contains("Bankruptcy Status");
driver.findElement(By.xpath("//div[@id='bankruptcyflag-div']/div[2]/button")).click();
System.out.println("Bankruptcy Status: is presend");
}
catch (Exception e){
System.out.println("Bankruptcy Status: is NOT present");
}
try{
driver.findElement(By.tagName("body")).getText().contains("Are you or your spouse on active duty");
driver.findElement(By.xpath("//div[@id='militaryeligibility-div']/div[2]/button")).click();
System.out.println("Are you or your spouse on active duty or a veteran of the U.S. military?" );
}
catch (Exception e){
System.out.println("window Are you or your spouse on active duty or a veteran of the U.S. military? NOT present" );
}
try{
// write the text "test@qs.com" in the field whose id = "email"
driver.findElement(By.id("email")).sendKeys("test@qs.com");
driver.findElement(By.xpath("//div[@id='email-div']/div[2]/button")).click();
}
catch (Exception e){}
driver.findElement(By.xpath("//input[@id='first_name']")).sendKeys("test");
driver.findElement(By.xpath("//input[@id='last_name']")).sendKeys("test");
driver.findElement(By.xpath("//input[@id='address']")).sendKeys("test");
driver.findElement(By.xpath("//input[@id='city']")).sendKeys("test");
driver.findElement((By.xpath("//input[@id='zip_code']"))).sendKeys("94154");
driver.findElement(By.xpath("//input[@id='phone_number_1']")).sendKeys("941");
driver.findElement(By.xpath("//input[@id='phone_number_2']")).sendKeys("321");
driver.findElement(By.xpath("//input[@id='phone_number_3']")).sendKeys("3212");
driver.findElement(By.xpath("//input[@id='get_lenders']")).click();
Thread.sleep(300);
driver.findElement(By.tagName("body")).getText().contains("Get Better, more Custom Results.Please answer ");
System.out.println("Window Get Better, more Custom Results.Please answer these last 4 questions' is rendered ");
driver.findElement(By.id("submitButton")).click();
Thread.sleep(300);
// Iterator function collect all teh element having class = "company-name" in ClientsName list (array) 
List<WebElement> ClientsName = driver.findElements(By.className("company-name"));
// Create a iterator function 
Iterator it = ClientsName.iterator();
//Displayed the total number of client present 
System.out.println("Total count of matched Client found  " +ClientsName.size());
// Executed the loop till a number of client present 
while (it.hasNext())
{
//Displayed all the clients name one by one
System.out.println("Name of clients are  :" +it.next());
}
driver.findElement(By.tagName("body")).getText().contains("Get your customized mortgage");
System.out.println("Window 'Get your customized mortgage' is rendered and client listing is displayed");
}
else
{
System.out.println("check console is going to one question at a time ");
driver.close();
// call the main function again
main(args);
}

}

}