Thursday, 9 March 2017

Common Exception in Selenium


NoSuchElement : An element could not be located on the page using the given search parameters.


NoSuchFrame : A request to switch to a frame could not be satisfied because the frame could not be found.

StaleElementReference : An element command failed because the referenced element is no longer attached to the DOM.

Firefox Not Connected : Firefox browser upgraded toop new version.

ElementIsNotSelectable : An attempt was made to select an element that cannot be selected.

UnknownCommand : The requested resource could not be found, or a request was received using an HTTP method that is not supported by the mapped resource.

ElementNotVisible : An element command could not be completed because the element is not visible on the page.

InvalidElementState : An element command could not be completed because the element is in an invalid state (e.g. attempting to click a disabled element).

UnknownError : An unknown server-side error occurred while processing the command.

JavaScriptError : An error occurred while executing JavaScript code.

XPathLookupError : An error occurred while searching for an element by XPath.

Timeout : An operation did not complete before its timeout expired.

NoSuchWindow : A request to switch to a different window could not be satisfied because the window could not be found.

InvalidCookieDomain : An illegal attempt was made to set a cookie under a different domain than the current page.

UnableToSetCookie : A request to set a cookie’s value could not be satisfied.

UnexpectedAlertOpen : A modal dialog was open, blocking this operation

NoAlertOpenError : An attempt was made to operate on a modal dialog when one was not open.

ScriptTimeout : A script did not complete before its timeout expired.

InvalidElementCoordinates : The coordinates provided to an interactions operation are invalid.

IMENotAvailable : IME was not available.

IMEEngineActivationFailed : An IME engine could not be started.

InvalidSelector : Argument was an invalid selector (e.g. XPath/CSS).

Tuesday, 15 July 2014

Generate Random Data based on type using Faker

https://github.com/stympy/faker

Faker

This gem is a port of Perl's Data::Faker library that generates fake data.
It comes in very handy for taking screenshots (taking screenshots for my project, Catch the Best was the original impetus for the creation of this gem), having real-looking test data, and having your database populated with more than one or two records while you're doing development.

Installing

gem install faker

Usage


Faker::Name.name      #=> "Christophe Bartell"

Faker::Internet.email #=> "kirsten.greenholt@corkeryfisher.info"

Faker::Address


Faker::Address.city #=> "Imogeneborough"

Faker::Address.street_name #=> "Larkin Fork"

Faker::Address.street_address #=> "282 Kevin Brook"

Faker::Address.secondary_address #=> "Apt. 672"

Faker::Address.building_number #=> "7304"

Faker::Address.zip_code #=> "58517"

Faker::Address.zip #=> "58517"

Faker::Address.postcode #=> "58517"

Faker::Address.time_zone #=> "Asia/Yakutsk"

Faker::Address.street_suffix #=> "Street"

Faker::Address.city_suffix #=> "fort"

Faker::Address.city_prefix #=> "Lake"

Faker::Address.state_abbr #=> "AP"

Faker::Address.state #=> "California"

Faker::Address.country #=> "French Guiana"

Faker::Address.latitude #=> "-58.17256227443719"

Faker::Address.longitude #=> "-156.65548382095133"


Faker::Bitcoin


Faker::Bitcoin.address #=> "1HUoGjmgChmnxxYhz87YytV4gVjfPaExmh"

Faker::Business


Faker::Business.credit_card_number #=> "1228-1221-1221-1431"

Faker::Business.credit_card_expiry_date #=> 

Faker::Business.credit_card_type #=> "visa"

Faker::Code


Faker::Code.isbn #=> "759021701-8"

Faker::Commerce


Faker::Commerce.color #=> "lavender"

Faker::Commerce.department #=> "Grocery, Health & Beauty"

Faker::Commerce.product_name #=> "Practical Granite Shirt"

Faker::Company


Faker::Company.name #=> "Hirthe-Ritchie"

Faker::Company.suffix #=> "Group"

# Generate a buzzword-laden catch phrase.
Faker::Company.catch_phrase #=> "Business-focused coherent parallelism"

# When a straight answer won't do, BS to the rescue!
Faker::Company.bs #=> "empower one-to-one web-readiness"

Faker::Company.duns_number #=> "08-341-3736"

Faker::Internet


# Optional argument name=nil
Faker::Internet.email #=> "eliza@mann.net"

Faker::Internet.email('Nancy') #=> "nancy@terry.biz"

# Optional argument name=nil
Faker::Internet.free_email #=> "freddy@gmail.com"

Faker::Internet.free_email('Nancy') #=> "nancy@yahoo.com"

# Optional argument name=nil
Faker::Internet.safe_email #=> "christelle@example.org"

Faker::Internet.safe_email('Nancy') #=> "nancy@example.net"

# Optional arguments specifier=nil, separators=%w(. _)
Faker::Internet.user_name #=> "alexie"

Faker::Internet.user_name('Nancy') #=> "nancy"

Faker::Internet.user_name('Nancy Johnson', %w(. _ -)) #=> "johnson-nancy"

# Optional argument min_length=0
Faker::Internet.password #=> "doloremquealiquidrerum"

Faker::Internet.password(8) #=> "consecteturadasperiores"

Faker::Internet.domain_name #=> "effertz.info"

Faker::Internet.fix_umlauts('äöüß') #=> "aeoeuess"

Faker::Internet.domain_word #=> "haleyziemann"

Faker::Internet.domain_suffix #=> "info"

Faker::Internet.ip_v4_address #=> "24.29.18.175"

Faker::Internet.ip_v6_address #=> "ac5f:d696:3807:1d72:2eb5:4e81:7d2b:e1df"

# Optional arguments: host=domain_name, path="/#{user_name}"
Faker::Internet.url #=> "http://thiel.com/chauncey_simonis"
Faker::Internet.url('example.com') #=> "http://example.com/clotilde.swift"
Faker::Internet.url('example.com', '/foobar.html') #=> "http://example.com/foobar.html"

# Optional arguments: words=nil, glue=nil
Faker::Internet.slug #=> "pariatur_laudantium"
Faker::Internet.slug('foo bar') #=> "foo.bar"
Faker::Internet.slug('foo bar', '-') #=> "foo-bar"


Faker::Lorem


Faker::Lorem.word #=> "repellendus"

# Optional arguments: num=3, supplemental=false
Faker::Lorem.words #=> ["dolores", "adipisci", "nesciunt"]
Faker::Lorem.words(4) #=> ["culpa", "recusandae", "aut", "omnis"]
Faker::Lorem.words(4, true) #=> ["colloco", "qui", "vergo", "deporto"]

# Optional arguments: char_count=255
Faker::Lorem.characters #=> "uw1ep04lhs0c4d931n1jmrspprf5wrj85fefue0y7y6m56b6omquh7br7dhqijwlawejpl765nb1716idmp3xnfo85v349pzy2o9rir23y2qhflwr71c1585fnynguiphkjm8p0vktwitcsm16lny7jzp9t4drwav3qmhz4yjq4k04x14gl6p148hulyqioo72tf8nwrxxcclfypz2lc58lsibgfe5w5p0xv95peafjjmm2frkhdc6duoky0aha"
Faker::Lorem.characters(10) #=> "ang9cbhoa8"

# Optional arguments: word_count=4, supplemental=false, random_words_to_add=6
Faker::Lorem.sentence #=> "Dolore illum animi et neque accusantium."
Faker::Lorem.sentence(3) #=> "Commodi qui minus deserunt sed vero quia."
Faker::Lorem.sentence(3, true) #=> "Inflammatio denego necessitatibus caelestis autus illum."
Faker::Lorem.sentence(3, false, 4) #=> "Aut voluptatem illum fugit ut sit."
Faker::Lorem.sentence(3, true, 4) #=> "Accusantium tantillus dolorem timor."

# Optional arguments: sentence_count=3, supplemental=false
Faker::Lorem.sentences #=> ["Vero earum commodi soluta.", "Quaerat fuga cumque et vero eveniet omnis ut.", "Cumque sit dolor ut est consequuntur."]
Faker::Lorem.sentences(1) #=> ["Ut perspiciatis explicabo possimus doloribus enim quia."]
Faker::Lorem.sentences(1, true) #=> ["Quis capillus curo ager veritatis voro et ipsum."]

# Optional arguments: sentence_count=3, supplemental=false, random_sentences_to_add=3
Faker::Lorem.paragraph #=> "Neque dicta enim quasi. Qui corrupti est quisquam. Facere animi quod aut. Qui nulla consequuntur consectetur sapiente."
Faker::Lorem.paragraph(2) #=> "Illo qui voluptas. Id sit quaerat enim aut cupiditate voluptates dolorum. Porro necessitatibus numquam dolor quia earum."
Faker::Lorem.paragraph(2, true) #=> ""
Faker::Lorem.paragraph(2, false, 4) #=> ""
Faker::Lorem.paragraph(2, true, 4) #=> ""

# Optional arguments: paragraph_count=3, supplemental=false
Faker::Lorem.paragraphs #=> ""
Faker::Lorem.paragraphs(1) #=> ""
Faker::Lorem.paragraphs(1, true) #=> ""

Faker::Name


Faker::Name.name #=> "Tyshawn Johns Sr."

Faker::Name.first_name #=> "Kaci"

Faker::Name.last_name #=> "Ernser"

Faker::Name.prefix #=> "Mr."

Faker::Name.suffix #=> "IV"

Faker::Name.title #=> "Legacy Creative Director"

Faker::Number


# Required parameter: digits
Faker::Number.number(10) #=> "1968353479"

Faker::Number.digit #=> "1"

Faker::PhoneNumber


Phone numbers may be in any of the following formats:
  • 333-333-3333
  • (333) 333-3333
  • 1-333-333-3333
  • 333.333.3333
  • 333-333-3333
  • 333-333-3333 x3333
  • (333) 333-3333 x3333
  • 1-333-333-3333 x3333
  • 333.333.3333 x3333
(Don't let the example output below fool you - any format can be returned at random.)
Faker::PhoneNumber.phone_number #=> "397.693.1309"

Faker::PhoneNumber.cell_phone #=> "(186)285-7925"

# NOTE NOTE NOTE NOTE
# For the 'US only' methods below, first you must do the following:
Faker::Config.locale = 'en-us'

# US only
Faker::PhoneNumber.area_code #=> "201"

# US only
Faker::PhoneNumber.exchange_code #=> "208"

# Optional parameter: length=4
Faker::PhoneNumber.subscriber_number #=> "3873"

Faker::PhoneNumber.subscriber_number(2) #=> "39"

Faker::PhoneNumber.extension #=> "3764"

Customization

Since you may want to make addresses and other types of data look different depending on where in the world you are (US postal codes vs. UK postal codes, for example), Faker uses the I18n gem to store strings (like state names) and formats (US postal codes are NNNNN while UK postal codes are AAN NAA), allowing you to get different formats by switching locales. Just set Faker::Config.locale to the locale you want, and Faker will take care of the rest.

Wednesday, 28 May 2014

How to use test/unit and ruby assertions

require 'selenium-webdriver'
require 'test/unit'

module Test
  class TestHomePage < Test::Unit::TestCase

    def setup
      @driver = Selenium::WebDriver.for :firefox
      @driver.navigate.to('http://ruby-selenium.blogspot.in/')
    end

    def teardown
      @driver.quit
    end

    def test_home_page_title
      assert_equal('ayan', @driver.title)
    end
  end
end

Friday, 16 May 2014

Automation Frameworks

Automation Frameworks With Example (Selenium)


There are 5 types of Framework  

1. Linear Framework
2. Library Architecture Framework
3. Keyword driven framework
4. Data Driven Framework
5. Hybrid Framework
Each and Every framework has its own merits and demerits. These all frameworks can be applied to any Automation Tool.
How to choose a particular framework?
There is no thumb rule to choose a framework, but it depends on many factors like Type of Application (AUT), Number of available resources, Reusability of Test Script.
We will see each and every framework with Example.
Example Scenario: User books a flight ticket on Travel portal and logout .
1.       Linear Framework
This is very simple framework and good for beginner.
Merits : Not  much coding expertise  is required .
Demerits : 1.Test case is not reusable .
                   2. Lots of Rework will be required in case of any Change.
Following code is an example of Linear Framework.
package com.project1;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.support.ui.Select;
 public class Linear_Framework {
      
        
       public static void main(String[] args) {
              //Initiate Driver
        WebDriver driver = new FirefoxDriver();
        //Login
        driver.navigate().to("http://newtours.demoaut.com/");
        driver.findElement(By.name("userName")).sendKeys("Mercury");
        driver.findElement(By.name("password")).sendKeys("mercury");
        driver.findElement(By.name("login")).click();
         //Book a Ticket
     Select Passangers= new Select(driver.findElement(By.cssSelector("select[name='passCount']")));
        Passangers.selectByVisibleText("2");
        Select Departingfrom = new Select(driver.findElement(By.cssSelector("select[name='fromPort']")));
        Departingfrom.selectByVisibleText("Frankfurt");
        Select FromMonth = new Select(driver.findElement(By.cssSelector("select[name='fromMonth']")));
        FromMonth.selectByVisibleText("September");
        Select ArrivingIn = new Select(driver.findElement(By.cssSelector("select[name='toPort']")));
        ArrivingIn.selectByVisibleText("New York");
        Select ToMonth = new Select(driver.findElement(By.cssSelector("select[name='toMonth']")));
        ToMonth.selectByIndex(10);
        driver.findElement(By.xpath("/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[9]/td[2]/font/font/input")).click();
        driver.findElement(By.name("findFlights")).click();
        driver.findElement(By.name("reserveFlights")).click();
        driver.findElement(By.name("passFirst0")).sendKeys("Name1");
        driver.findElement(By.name("passLast0")).sendKeys("LastName");
        driver.findElement(By.name("creditnumber")).sendKeys("1234566");
        driver.findElement(By.name("buyFlights")).click();
        
      
      
         //Logout
        driver.findElement(By.linkText("SIGN-OFF")).click();
        
        
     //Close Browser
        driver.quit();
        
        }
}
2.        Library Architecture Framework
This  is a approach where all test cases are analysed to  find out reusability and these test cases are created as functions and will be stored in other files and can be called whenever needed ,In Short  Test  case will be fragmented into functions .
Merits: It will save time and Effort due to reusability.
Demerits: 1.Programming Knowledge is required.
                   2. Data is hardcoded, so Test script cannot be run using different data values.
Following code is an example of Library Architecture, In Main () only functions are present.
package com.project1;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.support.ui.Select;
 public class Library_Framework {
      
       //Initiate Driver
               static WebDriver driver = new FirefoxDriver();
       public static void main(String[] args)
       {
              //Login
       Login("Mercury", "mercury");
       FlightBook();
       Logout();
      
       }
           //Function
       public static void Login(String Username,String Password)
       {
               driver.navigate().to("http://newtours.demoaut.com/");
               driver.findElement(By.name("userName")).sendKeys(Username);
               driver.findElement(By.name("password")).sendKeys(Password);
               driver.findElement(By.name("login")).click();
       }
       public static void FlightBook()
       {
               Select Passangers= new Select(driver.findElement(By.cssSelector("select[name='passCount']")));
               Passangers.selectByVisibleText("2");
               Select Departingfrom = new Select(driver.findElement(By.cssSelector("select[name='fromPort']")));
               Departingfrom.selectByVisibleText("Frankfurt");
               Select FromMonth = new Select(driver.findElement(By.cssSelector("select[name='fromMonth']")));
               FromMonth.selectByVisibleText("September");
               Select ArrivingIn = new Select(driver.findElement(By.cssSelector("select[name='toPort']")));
               ArrivingIn.selectByVisibleText("New York");
               Select ToMonth = new Select(driver.findElement(By.cssSelector("select[name='toMonth']")));
               ToMonth.selectByIndex(10);
               driver.findElement(By.xpath("/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[9]/td[2]/font/font/input")).click();
               driver.findElement(By.name("findFlights")).click();
               driver.findElement(By.name("reserveFlights")).click();
               driver.findElement(By.name("passFirst0")).sendKeys("Name1");
               driver.findElement(By.name("passLast0")).sendKeys("LastName");
               driver.findElement(By.name("creditnumber")).sendKeys("1234566");
               driver.findElement(By.name("buyFlights")).click();
               
       }
public static void Logout()
{
        driver.findElement(By.linkText("SIGN-OFF")).click();
}
public static void quitdriver()
{
        driver.quit();
}
}
3.        Keyword driven Framework
There are 2 types of keyword driven framework
1. Operation level
2. Function level
  Merits:  1.Keyword Driven Framework is very Generic so it can be used to other Test  cases     
                  as well
  Demerits : It requires lots of efforts and expertise to prepare complex  Libraries
Here I have prepared a code for Function Level Keyword driven Framework.
 Steps:

1.       Create an Excel sheet for Test case Flow.
                2.  Create individual functions for test cases (Login(),FlightBook(),Logout())
                3.   Create a function Which Can read Excel sheet and can execute mapped function.
       By following above steps,  final code should look like as below.
       package com.project1;
import java.io.File;
import java.io.IOException;
import java.util.List;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.support.ui.Select;
public class Keyword_Driven {
      
       //Initiate Driver
        static WebDriver driver = new FirefoxDriver();
public static void main(String[] args)
{
      
        //Login
        driver.navigate().to("http://newtours.demoaut.com/");
        
      
              Workbook workbook;
              try {
                     workbook = Workbook.getWorkbook(new File("C:\\Users\\Public\\Documents\\Test Excel\\Keyword_driven.xls"));
                     Sheet sheet = workbook.getSheet(0);
                    
              //code to read Test Case
                     int row=sheet.getRows();
                     for(int i=1;i<row;i++)
                     {
                           String Testcasename=sheet.getCell(0,i).getContents().toString();
                           //Call function ExecuteFunction to Read Mapped Function
                           ExecuteFunction(Testcasename);
                          
                    
                     }
                     //Close Browser
                     quitdriver();
                    
              } catch (BiffException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              } catch (IOException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              }
             
}
public static void ExecuteFunction(String Casename)
{
       String Option=Casename.trim();
      
 if(Option.equalsIgnoreCase("TC_Login") )
 {
      
        //Execute Login Function
        Login("Mercury", "mercury");
 }
 else if(Option.equalsIgnoreCase("TC_Book Flight"))
 {
        //Execute FlighBook Function
        FlightBook();
 }
 else if(Option.equalsIgnoreCase("TC_Logout"))
 {
       //Execute Logout
        Logout();
 }
 }
public static void Login(String Username,String Password)
{
        driver.findElement(By.name("userName")).sendKeys(Username);
        driver.findElement(By.name("password")).sendKeys(Password);
        driver.findElement(By.name("login")).click();
}
public static void FlightBook()
{
        Select Passangers= new Select(driver.findElement(By.cssSelector("select[name='passCount']")));
        Passangers.selectByVisibleText("2");
        Select Departingfrom = new Select(driver.findElement(By.cssSelector("select[name='fromPort']")));
        Departingfrom.selectByVisibleText("Frankfurt");
        Select FromMonth = new Select(driver.findElement(By.cssSelector("select[name='fromMonth']")));
        FromMonth.selectByVisibleText("September");
        Select ArrivingIn = new Select(driver.findElement(By.cssSelector("select[name='toPort']")));
        ArrivingIn.selectByVisibleText("New York");
        Select ToMonth = new Select(driver.findElement(By.cssSelector("select[name='toMonth']")));
        ToMonth.selectByIndex(10);
        driver.findElement(By.xpath("/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[9]/td[2]/font/font/input")).click();
        driver.findElement(By.name("findFlights")).click();
        driver.findElement(By.name("reserveFlights")).click();
        driver.findElement(By.name("passFirst0")).sendKeys("Name1");
        driver.findElement(By.name("passLast0")).sendKeys("LastName");
        driver.findElement(By.name("creditnumber")).sendKeys("1234566");
        driver.findElement(By.name("buyFlights")).click();
        
}
public static void Logout()
{
 driver.findElement(By.linkText("SIGN-OFF")).click();
}
public static void quitdriver()
{
 driver.quit();
}
}
For Operation level framework different keywords are written in excel sheet and can be read using Function .this is quite complex.
Excel sheet can be as follows:
4.       Data-Driven  framework

In this type of framework Data is not hardcoded with script ,but data is provided from external  source.
This external source can be Excel sheet, TXT file, Database etc.
Merits:     As data is provided from external source same script can be run for different datasets.
Demerits:  Good efforts and technical expertise is required to create functions  which connects to        
                     Database
Following code is an example of Data-driven Framework
package com.project1;
import java.io.File;
import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.support.ui.Select;
import jxl.*;
import jxl.read.biff.BiffException;
public class DataDriven_Framework {
        public static void main(String[] args) {
               WebDriver driver = new FirefoxDriver();
               //Login
               driver.navigate().to("http://newtours.demoaut.com/");
               
               try {
                     Workbook workbook = Workbook.getWorkbook(new File("C:\\Users\\Public\\Documents\\Test Excel\\Excel1.xls"));
                     Sheet sheet = workbook.getSheet(0);
                    
                     driver.findElement(By.name("userName")).sendKeys(sheet.getCell(0, 1).getContents());
                     driver.findElement(By.name("password")).sendKeys(sheet.getCell(1, 1).getContents());
                     driver.findElement(By.name("login")).click();
                     Select Passangers= new Select(driver.findElement(By.cssSelector("select[name='passCount']")));
                     Passangers.selectByVisibleText(sheet.getCell(2, 1).getContents());
                     Select Departingfrom = new Select(driver.findElement(By.cssSelector("select[name='fromPort']")));
                      Departingfrom.selectByVisibleText(sheet.getCell(3, 1).getContents());
                      Select FromMonth = new Select(driver.findElement(By.cssSelector("select[name='fromMonth']")));
                      FromMonth.selectByVisibleText(sheet.getCell(4, 1).getContents());
                      Select ArrivingIn = new Select(driver.findElement(By.cssSelector("select[name='toPort']")));
                      ArrivingIn.selectByVisibleText(sheet.getCell(6,1).getContents());
                      Select ToMonth = new Select(driver.findElement(By.cssSelector("select[name='toMonth']")));
                      ToMonth.selectByVisibleText(sheet.getCell(5,1).getContents());
                      driver.findElement(By.xpath("/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[9]/td[2]/font/font/input")).click();
                      driver.findElement(By.name("findFlights")).click();
                      driver.findElement(By.name("reserveFlights")).click();
                      driver.findElement(By.name("passFirst0")).sendKeys(sheet.getCell(7, 1).getContents());
                      driver.findElement(By.name("passLast0")).sendKeys(sheet.getCell(8, 1).getContents());
                      driver.findElement(By.name("creditnumber")).sendKeys(sheet.getCell(9, 1).getContents());
                      driver.findElement(By.name("buyFlights")).click();
                    
                    
                    
              } catch (BiffException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              } catch (IOException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              }
        }
        }
5.       Hybrid Frameworks
This is combination of Keyword Driven and Data Driven Framework  ,Both above examples can be used to explain it
Merits: Best features can be used of any type of framework
Demerits: Highly Complex Framework