Saturday 1 August 2015

UUID random number genaretion

package foo;

import java.util.UUID;
import org.junit.Test;

public class UUID_numberGeneration {
   
    @Test
    public void uuidNumberGenerationTEst(){
      
        for (int i = 0; i < 15; i++) {
                UUID idTwo = UUID.randomUUID();
                System.out.println("UUID "+i+" : " + idTwo);
        }
    }
}

New & high configured pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>fms_webapp_testing</groupId>
  <artifactId>fms_webapp_testing</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>
 
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  </properties>
 
   <build>
        <sourceDirectory>src</sourceDirectory>
        <testSourceDirectory>src</testSourceDirectory>
        <plugins>
             <plugin>
                 <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                  <version>3.1</version>
                  <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                  </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.15</version>
                <configuration>
                    <includes>
                        <include>**/SuiteRunner.java</include>
                    </includes>
                </configuration>   
            </plugin>
        </plugins>
    </build>
 
 
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.10.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.10-FINAL</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>3.10.1</version>
        </dependency>

        <dependency>
            <groupId>javax.xml.stream</groupId>
            <artifactId>stax-api</artifactId>
            <version>1.0-2</version>
        </dependency>

        <dependency>
            <groupId>org.apache.xmlbeans</groupId>
            <artifactId>xmlbeans</artifactId>
            <version>2.4.0</version>
        </dependency>
   
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>2.35.0</version>
        </dependency>
   
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-server</artifactId>
            <version>2.35.0</version>
        </dependency>
   
        <dependency>
            <groupId>net.sourceforge.jexcelapi</groupId>
            <artifactId>jxl</artifactId>
            <version>2.6</version>
        </dependency>
 
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4</version>
        </dependency>

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.4</version>
        </dependency>
       
       
       
   
    </dependencies>
</project>

Friday 31 July 2015

Create and Data write into PDF file.

 // Add the itextpdf-5.1.0.jar file to project

package testNG;

import java.io.FileOutputStream;
import org.junit.Test;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Section;
import com.itextpdf.text.pdf.CMYKColor;
import com.itextpdf.text.pdf.PdfWriter;


public class PDFfileWork {
   
    Font blueFont = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL, new CMYKColor(255, 0, 0, 0));
    Font redFont = FontFactory.getFont(FontFactory.COURIER, 12, Font.BOLD, new CMYKColor(0, 255, 0, 0));
    Font yellowFont = FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, new CMYKColor(0, 0, 255, 0));
    Document document = new Document();
   
    @Test
    public void pdfWorkTest(){
       
        try
        {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\Users\\Youtility\\Desktop\\StylingExample.pdf"));
            document.open();
            //document.add(new Paragraph("Styling Example"));
       
            //Paragraph with color and font styles
            Paragraph paragraphOne = new Paragraph("Some colored paragraph text", redFont);
            document.add(paragraphOne);
       
            //Create chapter and sections
            Paragraph chapterTitle = new Paragraph("Chapter Title", yellowFont);
            Chapter chapter1 = new Chapter(chapterTitle, 1);
            chapter1.setNumberDepth(0);
       
            Paragraph sectionTitle = new Paragraph("Section Title", redFont);
            Section section1 = chapter1.addSection(sectionTitle);
       
            Paragraph sectionContent = new Paragraph("Section Text content", blueFont);
            section1.add(sectionContent);
       
            document.add(chapter1);
       
            document.close();
            writer.close();
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

Thursday 30 July 2015

Work with log files.

Step :-1 
Adding changes in master script.
static Logger log = Logger.getLogger(Practice.class);
BasicConfigurator.configure();log.info("This is Logger Info");

Step :-2
Adding changes in Project.
And create the "log4j.properties" file under SRC

Step :3
Adding changes in log4j.properties file.
# This sets the global logging level and specifies the appenderslog4j.rootLogger=INFO, theConsoleAppender
# settings for the console appender
log4j.appender.theConsoleAppender=org.apache.log4j.ConsoleAppender
log4j.appender.theConsoleAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.theConsoleAppender.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n


Wednesday 29 July 2015

Screenshot of WebElement

package book.chapter05;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Point;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.Augmenter;

public class TakeElementScreenshot {
  private final String screenshotFolder = "target/screenshots/";
  protected WebDriver driver;

  public TakeElementScreenshot(WebDriver driver) {
    this.driver = driver;
  }

  public void shoot(WebElement element) throws IOException {
    try {
      driver = new Augmenter().augment(driver);
    } catch (Exception ignored) {
    }
    File screen = ((TakesScreenshot) driver)
        .getScreenshotAs(OutputType.FILE);
    Point p = element.getLocation();
    int width = element.getSize().getWidth();
    int height = element.getSize().getHeight();
    Rectangle rect = new Rectangle(width, height);
    BufferedImage img = null;
    img = ImageIO.read(screen);
    BufferedImage dest = img.getSubimage(p.getX(), p.getY(),
        rect.width, rect.height);
    ImageIO.write(dest, "png", screen);
    FileUtils.copyFile(screen, new File(screenshotFolder
        + System.nanoTime() + ".png"));
  }
}

Screenshot of page Using WebDriver

 public void takeScreenshot() throws IOException {
    File scrFile = ((TakesScreenshot) driver)
        .getScreenshotAs(OutputType.FILE);
    String fileName = UUID.randomUUID().toString();
    File targetFile = new File("target/screenshots/" + fileName
        + ".jpg");
    FileUtils.copyFile(scrFile, targetFile);
  }

How to find total number of iFrames on a webpage

There are two ways to find total number of iFrames in a web page. First by executing a JavaScript and second is by finding total number of web elements with a tag name of iFrame. Here is the code using both these methods:

        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.toolsqa.com/iframe-practice-page/");

        //By executing a java script
        JavascriptExecutor exe = (JavascriptExecutor) driver;
        Integer numberOfFrames = Integer.parseInt(exe.executeScript("return window.length").toString());
        System.out.println("Number of iframes on the page are " + numberOfFrames);

        //By finding all the web elements using iframe tag
        List<WebElement> iframeElements = driver.findElements(By.tagName("iframe"));
        System.out.println("The total number of iframes are " + iframeElements.size());



to switch to 0th iframe we can simple write driver.switchTo().frame(0). Here is the sample code:


    public static void main(String[] args) throws InterruptedException {
        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.toolsqa.com/iframe-practice-page/");

        //Switch by Index
        driver.switchTo().frame(0);
        driver.quit();
    }

Switch to Frames by Name

 
Now if you take a look at the HTMLcode of iFrame you will find that it has Name attribute. Name attribute has a value iframe1. We can switch to the iFrame using the name by using the command driver.switchTo().frame(“iframe1?). Here is the sample code

        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.toolsqa.com/iframe-practice-page/");

        //Switch by frame name
        driver.switchTo().frame("iframe1");
        driver.quit();

Switch to Frame by ID

Similar to the name attribute in the iFrame tag we also have the ID attribute. We can use that also to switch to the frame. All we have to do is pass the id to the switchTo command like this driver.SwitchTo().frame(“IF1?). Here is the sample code:

        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.toolsqa.com/iframe-practice-page/");

        //Switch by frame ID
        driver.switchTo().frame("IF1");
        driver.quit();

Switch to Frame by WebElement
Now we can switch to an iFrame by simply passing the iFrame WebElement to the driver.switchTo().frame() command. First find the iFrame element using any of the locator strategies and then passing it to switchTo command. Here is the sample code:

        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.toolsqa.com/iframe-practice-page/");
        //First find the element using any of locator stratedgy
        WebElement iframeElement = driver.findElement(By.id("IF1"));

        //now use the switch command
        driver.switchTo().frame(iframeElement);
        driver.quit();

Switching back to Main page from Frame
There is one very important command that will help us to get back to the main page. Main page is the page in which two iFrames are embedded. Once you are done with all the task in a particular iFrame you can switch back to the main page using the switchTo().defaultContent(). Here is the sample code which switches the driver back to main page.

        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.toolsqa.com/iframe-practice-page/");
        //First find the element using any of locator stratedgy
        WebElement iframeElement = driver.findElement(By.id("IF1"));

        //now use the switch command
        driver.switchTo().frame(0);

        //Do all the required tasks in the frame 0
        //Switch back to the main window
        driver.switchTo().defaultContent();
        driver.quit();

Sunday 26 July 2015

Work with Dropdown and Multiple Select in webdriver

Selecting Dropdown/Multiple Select Box
It is just an ordinary operation like selecting any other type of element on a webpage. You can choose it by ID, Name, Css & Xpath etc. But to perform any action on this element it is required to import ‘import org.openqa.selenium.support.ui.Select' package and to use it we need to create a new select object of class select.


Select oSelection = new Select(driver.findElement(By.id(id)));
Note: Select class only works for elements with <select> tags


Selecting an option using ‘selectByVisibleText’
It is very easy to choose or select an option given under any dropdowns and multiple selection boxes with selectByVisibleText method.


Select oSelection = new Select(driver.findElement(By.id(id)));

oSelection.selectByVisibleText(text);


Selecting an option using ‘selectByIndex’
It is almost the same as selectByVisibleText but the only difference here is that we provide the index number of the option here rather the option text.


Select oSelection = new Select(driver.findElement(By.id(id)));

oSelection.selectByIndex(index);


Selecting an option using ‘selectByValue’
It is again the same what we have discussed earlier, the only difference in this is that we need to provide the value of the option rather the option text.


Select oSelection = new Select(driver.findElement(By.id(id)));

oSelection.selectByValue(value);
Note: The value of an option and the text of the option may not be always same and there can be a possibility that the value is not assigned to Select webelement. If the value is given in the Select tag then only you can use the selectByValue method.


Getting the Size of Select item
Sometimes you may like to count the element in the dropdown and multiple select box, so that you can use the loop on Select element.

&nbsp;Select oSelection = new Select(driver.findElement(By.id(id)));

List<WebElement> oSize = oSelection.getOptions();

int iListSize = oSize.size();


Printing the Options Once you get the size of the Select element then it is easy to print the Text of the options.


Select oSelection = new Select(driver.findElement(By.id(id)));
List oSize = oSelection.getOptions();
int iListSize = oSize.size();
for(int i =0; i>iListSize ; i++){
        String sValue = oSelection.getOptions().get(i).getText();

        System.out.println(sValue);
}

All of the above methods work on both Dropdown and Multiple select box.


Deselect methods
This only works on Multiple selection boxes. If in case you want to deselect any selected option and that can be done with either deselectAll(), deselectByIndex, deselectByValue and deselectByVisibletext.


Select oSelection = new Select(driver.findElement(By.id(id)));
    oSelection.deselectAll();
    oSelection.deselectByIndex(index);

    oSelection.deselectByValue(value);

    oSelection.deselectByVisibleText(text);


Multiple selection method
This one also just works on Multiple selection boxes and not on regular List boxes or dropdowns. There is no additional logic behind selecting multiple options of Select element. All you need to do is to fire select commands on multiple elements one by one that’s it.


Select oSelection = new Select(driver.findElement(By.id(id)));

    oSelection.selectByIndex(index)

    oSelection.selectByIndex(index)

    // Or

    oSelection.selectByVisibleText(text)

    oSelection.selectByVisibleText(text)

    // Or

    oSelection.selectByValue(value)

    oSelection.selectByValue(value)


Practice Exercise -1 (Drop Down Box/List)
1) Launch new Browser

2) Open “http://www.toolsqa.com/automation-practice-form/”

3) Select ‘Continents’ Drop down ( Use Id to identify the element )

4) Select option ‘Europe’ (Use selectByIndex)

5) Select option ‘Africa’ now (Use selectByVisibleText)

6) Print all the options for the selected drop down and select one option of your choice

7) Close the browser

Solution

package practiceTestCases;

import java.util.List;

import java.util.concurrent.TimeUnit;

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 PracticeDropDown {

    private static WebDriver driver = null;

    public static void main(String[] args) throws InterruptedException {

     // Create a new instance of the Firefox driver

        driver = new FirefoxDriver();

        // Put an Implicit wait, this means that any search for elements on the page could take the time the implicit wait is set for before throwing exception

        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        // Launch the URL

        driver.get("http://www.toolsqa.com/automation-practice-form");

        // Step 3: Select 'Continents' Drop down ( Use Id to identify the element )

        // Find Select element of "Single selection" using ID locator.

        Select oSelection = new Select(driver.findElement(By.id("continents")));

        // Step 4:) Select option 'Europe' (Use selectByIndex)

        oSelection.selectByVisibleText("Europe");

        // Using sleep command so that changes can be noticed

        Thread.sleep(2000);

        // Step 5: Select option 'Africa' now (Use selectByVisibleText)

        oSelection.selectByIndex(2);

        Thread.sleep(2000);

        // Step 6: Print all the options for the selected drop down and select one option of your choice

        // Get the size of the Select element

        List oSize = oSelection.getOptions();

        int iListSize = oSize.size();

        // Setting up the loop to print all the options

        for(int i =0; i < iListSize ; i++){

           // Storing the value of the option   

            String sValue = oSelection.getOptions().get(i).getText();

            // Printing the stored value

            System.out.println(sValue);

            // Putting a check on each option that if any of the option is equal to 'Africa" then select it

            if(sValue.equals("Africa")){

                oSelection.selectByIndex(i);

                break;

                }

            }       

        // Kill the browser

        driver.close();

    }

}

Selenium WebDriver Switch Window Commands

GetWindowHandle Command
Purpose: To get the window handle of the current window.


 String  handle= driver.getWindowHandle();//Return a string of alphanumeric window handle


GetWindowHandles Command
Purpose: To get the window handle of all the current windows.


 Set<String> handle= driver.getWindowHandles();//Return a set of window handle


SwitchTo Window Command
Purpose: WebDriver supports moving between named windows using the “switchTo” method.


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

Or

Alternatively, you can pass a “window handle” to the “switchTo().window()” method. Knowing this, it’s possible to iterate over every open window like so:


 for (String handle : driver.getWindowHandles()) {

    driver.switchTo().window(handle);}
Or

Switching between windows with Iterators:


 driver.findElement(By.id(“id of the link which opens new window”)).click();

 //wait till two windows are not opened

 waitForNumberofWindowsToEqual(2);//this method is for wait

 Set handles = driver.getWindowHandles();

 firstWinHandle = driver.getWindowHandle(); handles.remove(firstWinHandle);

 String winHandle=handles.iterator().next();

 if (winHandle!=firstWinHandle){

 //To retrieve the handle of second window, extracting the handle which does not match to first window handle

 secondWinHandle=winHandle; //Storing handle of second window handle

//Switch control to new window

 driver.switchTo().window(secondWinHandle);

 driver.findElement(By.id(“id of the link which opens new window”)).click();

 //wait till two windows are not opened

 waitForNumberofWindowsToEqual(2);//this method is for wait

 Set handles = driver.getWindowHandles();

 firstWinHandle = driver.getWindowHandle(); handles.remove(firstWinHandle);

 String winHandle=handles.iterator().next();

 if (winHandle!=firstWinHandle){

 //To retrieve the handle of second window, extracting the handle which does not match to first window handle

 secondWinHandle=winHandle; //Storing handle of second window handle

//Switch control to new window

 driver.switchTo().window(secondWinHandle);


SwitchTo Frame Command
Purpose: WebDriver supports moving between named frames using the “switchTo” method.

driver.switchTo().frame("frameName");


SwitchTo PopUp Command
Purpose: WebDriver supports moving between named PopUps using the “switchTo” method. After you’ve triggered an action that opens a popup, you can access the alert and it will return the currently open alert object. With this object you can now accept, dismiss, read its contents or even type into a prompt. This interface works equally well on alerts, confirms, and prompts.


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

How to check whether a text is underlined or not ?

Ans- Identify by getCssValue(“border-bottom”) or sometime getCssValue(“text-decoration”) method if the

 cssValue is 'underline' for that WebElement or not.

 ex- This is for when moving cursor over element that is going to be underlined or not-

 public class UnderLine {

 public static void main(String[] args) {

 WebDriver driver = new FirefoxDriver();

 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

 driver.get("https://www.google.co.in/?gfe_rd=ctrl&amp;ei=bXAwU8jYN4W6iAf8zIDgDA&amp;gws_rd=cr");

 String cssValue= driver.findElement(By.xpath("//a[text()='Hindi']")).getCssValue("text-decoration");

 System.out.println("value"+cssValue);

 Actions act = new Actions(driver);

 act.moveToElement(driver.findElement(By.xpath("//a[text()='Hindi']"))).perform();

 String cssValue1= driver.findElement(By.xpath("//a[text()='Hindi']")).getCssValue("text-decoration");

 System.out.println("value over"+cssValue1);

 driver.close();

 }

 }

Scroll down the Window using Actions.

Use java script to scroll down-




JavascriptExecutor jsx = (JavascriptExecutor)driver;

 jsx.executeScript("window.scrollBy(0,4500)", ""); //scroll down, value 4500 you can change as per your req

 jsx.executeScript("window.scrollBy(450,0)", ""); //scroll up

 ex-

 public class ScrollDown {

 public static void main(String[] args) throws InterruptedException {

 WebDriver driver = new FirefoxDriver();

 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

 driver.get("http://www.flipkart.com/womens-clothing/pr?sid=2oq,c1r&amp;otracker=hp_nmenu_sub_women_1_View%20all");

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

 JavascriptExecutor jsx = (JavascriptExecutor)driver;

 jsx.executeScript("window.scrollBy(0,4500)", ""); //scroll down

 Thread.sleep(3000);

 jsx.executeScript("window.scrollBy(450,0)", ""); //scroll up

 }

 }

Different exceptions you got when working with WebDriver ?


ElementNotVisibleException, 

ElementNotSelectableException, 

NoAlertPresentException,

NoSuchAttributeException,

NoSuchWindowException, 

TimeoutException, 

WebDriverException etc.