Friday, April 10, 2015

Invisible or Ghost Browser Opening

Ghost Browser/Invisible Browser:
  • We know already some popular browser already.But here some interesting  fact about the invisible browser.
  • There is no UI for this browser(browser window)
  • This is also called as headless browser ,but its has brain just for fun..
  • without opening Browser the scripts will run.
  • Its will run more fast rather than traditional browser
  • Its mainly used in regression testing
  • smoke and sanity testing it will be used 
Sample Program :
package gmr;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.testng.Assert;
import org.testng.annotations.Test;

public class GhostBrowser{
   
    WebDriver driver;
   
    @Test()
    public void test() throws InterruptedException{
    /*
    * Opening Browser
    */
       
    driver=new HtmlUnitDriver();
     /*
    * Maximize the window
    */   
    driver.manage().window().maximize();
    /*
    * Open Gmail Login Page
    */
    driver.get("http://www.gmr-automation.blogspot.in/");
    Thread.sleep(1000);
    System.out.println("title      " +driver.getTitle());
    Thread.sleep(1000);
   /*
   * browser closing and driver closing.
   */
    driver.close();
    driver.quit();

}
}

What Selenium IDE

Selenium IDE:(Integrated development environment)

  • Selenium IDE is one of the main component or part of the Selenium Automation Tool.
  • Its a Plugin for Firefox Browser.
  • Its a open source
  • Selenium IDE is Record and Playback tool
  • In IDE we have Export option to export recoded script into particular language.
  • It supports multiple languages like java,python,ruby,.net etc.
  • it support different platforms.
  • It automates the user actions on the webpage
  • Easy to Operate 
  • No Need of Programming Language knowledge
  • Its Implemented in HTML Language (PHP ).
Its Console Mainly divided into 3 regions

1.Command
2.Target/locators
3.Value
 
 Refer bellow image:

Drawbacks:
  • Its just works in Firefox alone
  • Conditional like if ,while loops we can't setup in IDE
  • Its contains duplicate methods leads to the user little bit confusion
  •  
 

What Is Selenium:Overiew




Selenium is a browser automation tool.Selenium automates browsers.which is open source Not required any license to use this tool like QTP .To automate web application selenium will be more useful.

Why We go for Selenium:
  • For Regression Testing.
  • For Smoke and Sanity Testing
  • Quick Testing
  • To Reduce the Manual Effort
  • Time saving
  • For Effective testing purpose
  • avoiding doing same working again and again.
Reason:
  • Before Releasing the product or services we have to Regression Testing To ensure that all are working fine or not.
  • Testing The build:Each and every time the development team will the build with new implementations.But Earlier Sprints or  earlier developed things may affect due latest development or code changes.
  • So we should not give any guarantee for that functionality will works in all builds.So every build we have do Regression at least for one Release one .

Selenium is combination of these 4 




1.Selenium IDE
2.Selenium RC
3.Selenium WebDriver
4.Selenium Grid


Before learning Selenium Few basics are needed.That very easy.
1.Core java(Not fully,you have full knowledge you can develop better methods while writing scripts )

AT Least few Topics like:
1.class and object creation
2.conditional loops
3.File Streams
4.LIST,SET,MAP basic concepts.
5.Data types

Later on if time permits i will post java concepts with Programs

Softwares:Eclipse,Java





Thursday, April 9, 2015

Sending Gmail with Screen shot Attachment.

Note: Here you need to give package,email and password,to mail,and chrome driver path as well as saving file path as specified.



package gmr;


import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class GMAIL_ATTACHFILE_SENDING {
   
    WebDriver driver;
   
    @BeforeMethod
    public void setup(){
       
        System.setProperty("webdriver.chrome.driver", "D:/Selenium/chromedriver.exe");
         driver = new ChromeDriver();
         driver.manage().window().maximize();
         driver.get("http://www.gmr-automation.blogspot.in/");
         File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
         try {
            FileUtils.copyFile(scrFile, new File("C:\\Users\\muraligandham.r\\Desktop\\SonarCube.png"));
        } catch (IOException e) {
            // TODO Auto-generated catch blockC:\\Users\\Public\\Pictures\\SonarCube.png
            e.printStackTrace();
        }
    }
   
   
   
    @Test
    public void gmailMailSednd() throws InterruptedException, AWTException{
        driver.navigate().to("https://accounts.google.com/ServiceLoginAuth");
        /*
        * AJax Handling That means Implicitly wait
        */
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        /*
        * User Name
        */
        driver.findElement(By.xpath(".//*[@id='Email']")).sendKeys("murali.royal123@gmail.com");
        /*
        * Password
        */
        driver.findElement(By.xpath(".//*[@id='Passwd']")).sendKeys("password");
        /*
        * Click The Login Button
        */
        driver.findElement(By.xpath("//*[@id='signIn']")).click();
        /*
        * Click The Compose Button
        */
        driver.findElement(By.xpath("//div[contains(text(),'COMPOSE')]")).click();
        /*
        * To Email Address Typing
        */

        driver.findElement(By.xpath("//form[1]//textarea[1]")).sendKeys("muraligmr9@gmail.com");
        /*
        * Subject Typing
        */

        driver.findElement(By.xpath("//div[@class='aoD az6']//input[@class='aoT']")).sendKeys("Please Find SonarCube IMage attachment");
        /*
        * Wait For Some Time
        */
         Thread.sleep(7000);
         /*
         * Click The Attachment Icon.
         *
         */
         /*
          * Click The Attachment Icon.
          */
         driver.findElement(By.xpath("//div[@class='a1 aaA aMZ']")).click();
         /*
         * Copying The Specified file Path into the clipboard by Using StringSelection class
         */
         StringSelection selection = new StringSelection("C:\\Users\\muraligandham.r\\Desktop\\SonarCube.png");
                Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, null);
         /*
         * Create object for The Robot class we can use keyboard actions.
         */  
             Robot robot = new Robot();
             Thread.sleep(5000);
          /*
          * Paste The Address Into The Cursur focused place by pressing Control+V
         */
             robot.keyPress(KeyEvent.VK_CONTROL);
             robot.keyPress(KeyEvent.VK_V);
             robot.keyRelease(KeyEvent.VK_CONTROL);
             robot.keyRelease(KeyEvent.VK_V);
             Thread.sleep(6000);
             /*
              * Click The Enter button.
              */
             robot.keyPress(KeyEvent.VK_ENTER);
             robot.keyRelease(KeyEvent.VK_ENTER);
             Thread.sleep(20000);
             /*
              * Click The Send Option.
              */
            driver.findElement(By.xpath("//div[text()='Send']")).click();
           
            
       
    }
   
    @AfterMethod
    public void tearDown(){
       
    driver.close();
    driver.quit();
    }
   

}

Sending Gmail Using Selenium .

 Here some of them you need to replace:like package,Chrome driver path,


package gmr;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class GMR_AUTOMATION_GMAIL_SENDING {
   
    WebDriver driver;
   
    @BeforeMethod
    public void setup(){
       
        System.setProperty("webdriver.chrome.driver", "D:/Selenium/chromedriver.exe");
         driver = new ChromeDriver();
         driver.manage().window().maximize();
    }
   
   
   
    @Test
    public void gmailMailSednd() throws InterruptedException{
        driver.get("http://www.gmail.com/");
        /*
        * AJax Handling That means Implicitly wait
        */
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        /*
        * User Name
        */
        driver.findElement(By.xpath(".//*[@id='Email']")).sendKeys("murali.royal123@gmail.com");
        /*
        * Password
        */
        driver.findElement(By.xpath(".//*[@id='Passwd']")).sendKeys("No buddy use your mail and your password");
        /*
        * Click The Login Button
        */
        driver.findElement(By.xpath("//*[@id='signIn']")).click();
        /*
        * Click The Compose Button
        */
        driver.findElement(By.xpath("//div[contains(text(),'COMPOSE')]")).click();
        /*
        * To Email Address Typing
        */

        driver.findElement(By.xpath("//form[1]//textarea[1]")).sendKeys("yoursmail@gmail.com");
        /*
        * Subject Typing
        */

        driver.findElement(By.xpath("//div[@class='aoD az6']//input[@class='aoT']")).sendKeys("Please Find SonarCube IMage attachment");
        /*
        * Wait For Some Time
        */
         Thread.sleep(7000);
         /*
         * Click The Attachment Icon.
         *
         */
         /*
             * Click The Send Option.
             */
           driver.findElement(By.xpath("//div[text()='Send']")).click();
    }
   
    @AfterMethod
    public void tearDown(){
       
    driver.close();
    driver.quit();
    }
   

}





Note Here am not typing any text in the body later i will update for you soon.

Saturday, April 4, 2015

Selenium All Basic Commands

1.Opening Browser

WebDriver driver=new FirefoxDriver();

2.Window Maximize

driver.manage().window().maximize();

3.Open URL

driver.get("https://mail.google.com/");

4.Navigate

driver.navigate().to("http://gmr-automation.blogspot.in/");

5.Back

driver.navigate().back();

6.Forward

driver.navigate().forward();

7.Refresh

driver.navigate().refresh();

8.Close the Browser

driver.close();

9.Quit The Browser

driver.quit();

10.Get Page Title

driver.getTitle();      

11.Fetch current URL of The browser

driver.getCurrentUrl();

12.Fetch Entire page Source Code/HTML code

driver.getPageSource();

13.Get Current Window ID

driver.getWindowHandle();     

14.Get All Windows ID's

 Set<String> elements= driver.getWindowHandles();

15.Finding WEB Element

driver.findElement(By.id("value"));
driver.findElement(By.name("Locator value"));
driver.findElement(By.xpath("Locator value"));
driver.findElement(By.cssSelector("Locator value"));
driver.findElement(By.linkText("Locator value"));
driver.findElement(By.partialLinkText("Locator value"));
driver.findElement(By.className("Locator value"));
driver.findElement(By.tagName("Locator value"));

16.Click on Element

driver.findElement(By.id("value")).click();

17.Typing Text

driver.findElement(By.id("value")).sendKeys("GMR-AUTOMATION");

18.Fetching Element Text and Storing
  
String text =driver.findElement(By.id("value")).getText();

19. Normal Wait Statement

Thred.sleep(int number);

20.Implicit Wait statement
    
driver.manage().timeouts().implicitlyWait(mSeconds, TimeUnit.MILLISECONDS);

21.Explicit Wait Statement

WebDriverWait wait = new WebDriverWait(driver, Time in Seconds);
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.id("locatorvalue"),"Messge"));

 22.Setting  Size of the Window

driver.manage().window().setSize(new Dimension(int number, int number));

23.Setting Position of the Window

  driver.manage().window().setPosition(new Point(int x, int y));

24.Dragging  element
    
WebElement src = driver.findElement(By.id("draggable"));
    Actions actions=new Actions();
     actions.dragAndDropBy(src, int xOffset, int  yOffset).build() .perform();

 25.Drag and Drop:
    
WebElement src = driver.findElement(By.id("draggable"));
    WebElement dest = driver.findElement(By.id("droppable"));
    new Actions(driver).dragAndDrop(src, dest).build().perform();
26.Drop Down Selecting

   /*
     * drop down select by visible text method
     */
           Select select=new Select(dropdown element);
        select.selectByVisibleText(visibleText);
      /*
     * drop down select by index method
     */
         Select select=new Select(dropdown element);
        select.selectByIndex(index);
     /*
      *  drop down select by value method
      */
           Select select=new Select(dropdown element);
        select.selectByValue(value);
  
27.Drop Down Deselecting
     
     /*
     * drop down Dselect by visible text method
     */
           Select select=new Select(dropdown element);
        select.deselectByVisibleText(visibleText);
    
      /*
     * drop down Dselect by index method
     */
         Select select=new Select(dropdown element);
         select.deselectByIndex(index);

     /*
      *  drop down Dselect by value method
      */
           DSelect select=new Select(dropdown element);
           select.deselectByValue(value);
 
 28.Deselect all from drop down

Select select=new Select(dropdown element);
 select.deselectAll();

29.Check For Multiselect

Select select=new Select(dropdown element);
select.isMultiple();

30.Mouse over to an element

  Actions actions=new Actions(driver);
actions.moveToElement(WebElement e ).build().perform();

sample method:

public void moveToElement(WebElement e){
        Actions actions=new Actions(driver);
        actions.moveToElement(e).build().perform();
    }

31.Right Click

  Actions actions=new Actions(driver);
        actions.contextClick(WebElemet e).build().perform();
sample: 

public void rightclick(WebElement e)    {
        Actions actions=new Actions(driver);
        actions.contextClick(e).build().perform();
       
    }

32.Other Mouse Actions

These will be performed at the within the  window 

Actions actions=new Actions(driver);
actions.clickAndHold();
actions. release()
actions. doubleClick();

33.Other Mouse Actions On Element

Actions actions=new Actions(driver);
actions.clickAndHold(WebElement e);
actions. release(WebElement e)
actions. doubleClick(WebElement e);

34.Switching To Alert boxes

 

Alert alert = driver.switchTo().alert();

Alert is an Interface

 

35.Alert box accepting

 

 Alert alert = driver.switchTo().alert();

 alert.accept();

     (or)

 driver.switchTo().alert().accept();

 

36. Alert box closing

 Alert alert = driver.switchTo().alert();

  alert.dismiss();

     (or)

 driver.switchTo().alert().dismiss();

 

 

37.Typing Text in The Alert message Text boxes 

  

  Alert alert = driver.switchTo().alert(); 

  clearing and typing

  alert.clear();

  alert.sendKeys("Message into The alert box");

             (or)

driver.switchTo().alert().sendKeys("Message into The alert box");

38.Fetching alert Box Message and displaying

    Alert alert = driver.switchTo().alert();  

    String text=alert.getText();

    System.out.println("alert message"+text);

 

39.Text clearing in the text box/any

driver.findElement(By.id("value")).clear();

40.Switching Window

ON 2 Windows Opening

        List<String> strings =(List<String>) driver.getWindowHandles();
        String childWindowID=strings.get(0);
        String parentWindowID=strings.get(1);
        switching child window:
        driver.switchTo().window(childWindowID);
        switching parent window:
        driver.switchTo().window(parentWindowID);

41.Screen Shot of web page


 File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
  FileUtils.copyFile(scrFile, new File("Path of the image"));
   
  We have to use TakesScreenshot interface for taking screen shot of the page as shown bellow.
   Here the path of the image we can give like this "C:\\Users\\Public\\Pictures\\gmr-automation.png"

    Here gmr-automation.png image will be created in that place


This will be continued up to ......



















Opening Browser and Customizing:

Before we want do any actions in the web page we have open the browser ,that may be any browser
here is some useful tips to open the browser:

WebDriver is An Interface, which has only the public and abstract methods 

SO we can't create object to the WebDriver Interface just we will create a reference variable and point to the object of any class.Such that we can use same abstract methods in the interface we can use with different implementation

EX:Interfaces

WebDriver,
JavascriptExecutor,
 SearchContext, 
TakesScreenshot,
 FindsByClassName, 
FindsByCssSelector,
 FindsById,
 FindsByLinkText,
 FindsByName,
 FindsByTagName, 
FindsByXPath.



WebDriver driver;

1.Opening Firefox browser

WebDriver driver=new FirefoxDriver();

2.Opening Chrome Browser:

System.setProperty("webdriver.chrome.driver", "path of the Chrome driver in your system");
 driver = new ChromeDriver(); 



3.Opening IE browser

System.setProperty("webdriver.ie.driver", "path of the IE driver in your system");
            driver = new InternetExplorerDriver();



Customizing:

 WebDriver driver;
1.New Size
driver.manage().window().setSize(new Dimension(int number, int number));
2.Position of the Window
  driver.manage().window().setPosition(new Point(int x, int y));
3.Maximize The Window
driver.manage().window().maximize();
 








 


   

 

What is WebElement & What is Locators/Object Path

Web Element's is part of webpage such as text,link,check box,radio button,text box....anything in the webpage is called as Web Element.
Web Element:
1.button
2.text
3.link
4.image
5.check box,radio buttons.....

If You want do any action in the selenium first you need to identify the web elements then we can do following actions in the page.


Common actions any user can do:
1.Click
2.Right click
3.Typing
4.Drag and Droping
5.Mouse Over

So if want perform this kind operations first we need find web elements .

In Selenium There are 8 Locators are there to identify any web element in the web page:they are

Basic Syntax for Identifying web elements:

driver.findelemet(By.Locator Name("locator value"));

LOCATORS:
  1. By ID
  2. By Name
  3. By cssSelector
  4. By XPath
  5. By Link Text
  6. By Partial Link Text
  7. By ClassName
  8. By Tag Name                                                                                         

Friday, April 3, 2015

Simple Code For Screen Shot of Web Page.

We have to use TakesScreenshot interface for taking screen shot of the page as shown bellow.
Here the path of the image we can give like this "C:\\Users\\Public\\Pictures\\gmr-automation.png"

Here gmr-automation.png image will be created in that place


 File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
  FileUtils.copyFile(scrFile, new File("Path of the image"));
  

Sample Program:

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class ScreenShotOfFacebookLoginPage {

 WebDriver driver;

 @BeforeTest
 public void start(){
  driver = new FirefoxDriver();
  driver.manage().window().maximize();
 }

 @Test
 public void Test() {

  driver.get("https://www.facebook.com");
  File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
  FileUtils.copyFile(scrFile, new File("C:\\Users\\Public\\Pictures\\facebookloginpage.png"));

   }
}

Drag and Drop Logic

Drag and Drop Can be done creating object to the Actions class as shown bellow.
private static WebDriver driver;
driver = new FirefoxDriver();
Create an object to action class 
Actions actions=new Actions(driver);


Dragging :
    WebElement src = driver.findElement(By.id("draggable"));
    Actions actions=new Actions();
     actions.dragAndDropBy(src, int xOffset, int  yOffset).build() .perform();

       ( OR)
    new Actions(driver).dragAndDropBy(src, int xOffset, int  yOffset).build() .perform();
Drag and Drop:
    WebElement src = driver.findElement(By.id("draggable"));
    WebElement dest = driver.findElement(By.id("droppable"));
    new Actions(driver).dragAndDrop(src, dest).build().perform();
 

WIndow Managing

WebDriver driver;
1.New Size
driver.manage().window().setSize(new Dimension(int number, int number));
2.Position of the Window
  driver.manage().window().setPosition(new Point(int x, int y));
3.Maximize The Window
driver.manage().window().maximize();

There is no minimize method in selenium  ,so by using above methods we can minimize and customize the position.

    Sample Program:
    import java.util.List;
    import org.openqa.selenium.By;
   import org.openqa.selenium.Dimension;
    import org.openqa.selenium.Keys;
    import org.openqa.selenium.Point;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.interactions.Action;
    import org.openqa.selenium.interactions.Actions;
    import org.testng.annotations.AfterClass;
    import org.testng.annotations.BeforeClass;
    import org.testng.annotations.Test;
    public class DragAndDrop {
    private static WebDriver driver;
 


 @BeforeClass
    public void setUp() {
    driver = new FirefoxDriver();
    driver.manage().window().setSize(new Dimension(200, 200));
    System.out.println("size is decreased to mention size");
    driver.manage().window().setPosition(new Point(200, 200));
    System.out.println("position changed");
    driver.manage().window().maximize();
    System.out.println("window maximaized");
    }
 
    @Test
    public void Test() {
    driver.get("http://gmr-automation.blogspot.in/");
        }

  @AfterClass
    public void tearDown() {
    driver.close();
    driver.quit();
    }
       }

Basics of Selenium 1

/**
     * implicit wait method  
     * @param Time
     */
    public  void impWait(int Time){
        driver.manage().timeouts().implicitlyWait(Time, TimeUnit.SECONDS);
    }
    /**
     * window maximized
     */
    public  void windowMaximize(){
        driver.manage().window().maximize();
    }
    /**
     *
     * @return current window title
     */
    public  String getTitle(){
        return driver.getTitle();
    }
 
     * click on the element method
     */
    public void clickOnElement(WebElement e){
        e.click();
    }
    /*
     * clear  method
     */
    public void clear(WebElement e){
        e.clear();
    }
    /*
     * get text method
     */
    public String getElementText(WebElement e){
        return e.getText();
        }
    /*
     * get attribute  method
     */
    public String getElementAttribute(WebElement e,String attribute){
        return e.getAttribute(attribute);
        }
    /*
     * getCss value method
     */
    public String getCssValue(WebElement e,String css){
        return e.getCssValue(css);
       
    }
/*
 * type text method
 */
    public void typeText(WebElement e,String text){
        e.sendKeys(text);
    }

Drop Down's Handling



We Have 3 Methods in Select class To handle the drop down's:First we have to create object to that class and then we can call that methods as shown in bellow.


/*
     * drop down select by visible text method
     */
    public void selectDropDownByVisibleText(WebElement dropdown,String visibleText){
        Select select=new Select(dropdown);
        select.selectByVisibleText(visibleText);
    }
    /*
     * drop down select by index method
     */
    public void selectDropDownByIndex(WebElement dropdown,int index){
        Select select=new Select(dropdown);
        select.selectByIndex(index);
    }
     /*
      *  drop down select by value method
      */
    public void selectDropDownByValue(WebElement dropdown,String value){
        Select select=new Select(dropdown);
        select.selectByValue(value);
    }

Waiting Methods in Selenium:Handling Ajax

/*
     * wait method for milliseconds
     */
    public void waitForMilliseconds(long mSeconds){
        driver.manage().timeouts().implicitlyWait(mSeconds, TimeUnit.MILLISECONDS);
    }
    /*
     * wait method for seconds
     */
    public void waitForseconds(long mSeconds){
        driver.manage().timeouts().implicitlyWait(mSeconds, TimeUnit.SECONDS);
    }
/*
  * wait method for seconds
*    
*/
public void waitForseconds(long mSeconds){
       Thread.sleep(int number);
    }

Cross Browser Testing

/*
     * open browser method
     */
    public WebDriver openBrowser(String browser){
        if(browser.equalsIgnoreCase("firefox")){
            driver=new FirefoxDriver();
        }else if(browser.equalsIgnoreCase("chrome")){
            System.setProperty("webdriver.chrome.driver", "D:/Selenium/chromedriver.exe");
             driver = new ChromeDriver();
        }else if(browser.equalsIgnoreCase("ie")){
            System.setProperty("webdriver.ie.driver", "D:/Selenium/IEDriverServer.exe");
            driver = new InternetExplorerDriver();
        }
        return driver;
    }