Showing posts with label Selenium-WebDriver. Show all posts
Showing posts with label Selenium-WebDriver. Show all posts

Monday, May 12, 2014

How to pass the Data to test script through xml or How to use @Parameters in TestNG ?

Ans- use @Parameters to pass the input through xml.

Ex-

import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class PassInputThruXML {
@Test
@Parameters({"para1","para2"})
public void passInput(String para1, double para2){
    System.out.println(para1);
    System.out.println(para2);
}
}


testng.xml->


<suite name="Suite" parallel="none">
  <test name="Test">
    <parameter name="para1" value="selenium-makeiteasy" />
    <parameter name="para2" value="5.0" />
      <classes>
          <class name="TestNg.PassInputThruXML"/>
      </classes>
  </test>
</suite>

How to get the dropdown value in notepad ?

Note: FileWriter("path of the directory with filename.txt");

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

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.interactions.Actions;


public class DropdownNotepad extends Thread {
    public static WebDriver driver;
    public static void main(String[] args) throws IOException {
        driver = new FirefoxDriver();
        driver.get("http://www.etouch.net/home/index.html");
        WebElement service = driver.findElement(By.xpath("//a[text()='Services']"));
        Actions act = new Actions(driver);
        act.moveToElement(service).perform();
        List<WebElement> dropdown = driver.findElements(By.xpath("//li[@id='services']//ul//ul/li"));
        System.out.println(dropdown.size());
       
        FileWriter fileWriter = new FileWriter("C:\\selenium\\out1.txt");
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
       
       
       
        for(WebElement ele: dropdown){
            System.out.println(ele.getText());
            bufferedWriter.write(ele.getText()+"\n");
        }
        bufferedWriter.close();
       
        driver.close();
    }
}

How to verify BreadCrumb ?

ex- Home>Services>Enterprise Web, this kind of sequence is called as breadcrumb.

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.interactions.Actions;

public class BreadCrumb {
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("http://www.etouch.net/home/index.html");
        WebElement service = driver.findElement(By.xpath("//a[text()='Services']"));
        Actions act = new Actions(driver);
        act.moveToElement(service).perform();
        driver.findElement(By.xpath("//li[a[text()='Services']]//a[text()='Enterprise Web']")).click();
       
       
        String breadcrumb = driver.findElement(By.xpath("//div[@class='breadcrumb']")).getText();
        System.out.println(breadcrumb);
       
        String lastBreadcrumb = driver.findElement(By.xpath("//div[@class='breadcrumb']/span[last()]")).getText();
        System.out.println(lastBreadcrumb);
        if(lastBreadcrumb.equals("Enterprise Web")){
            System.out.println("bread crumb is in correct order.");
        }else{
            System.out.println("bread crumb is not in correct order.");
        }
    }
}

How to scroll down and up in any web page.

Note- window.scrollBy(forUp,forDown). Here in this method forUp, you can give any value depends on how much you want to scroll up but before that you have to scroll down so that there would be some space to scroll up.
Ex-

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

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&otracker=hp_nmenu_sub_women_1_View%20all");
        driver.manage().window().maximize();
        JavascriptExecutor jsx = (JavascriptExecutor)driver;
        jsx.executeScript("window.scrollBy(0,4500)", "");
        Thread.sleep(3000);
        jsx.executeScript("window.scrollBy(2000,0)", "");
    }
}

How to open a link in new tab.



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.interactions.Actions;

public class NewTab {
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.google.com");
        Actions act = new Actions(driver);
        WebElement link = driver.findElement(By.id("gb_70"));
        act.moveToElement(link).contextClick().sendKeys("T").perform();
    }
}

How to move the pointer as well while moving the cursor or How to use Robot class.

Ans- To move the pointer with the cursor we have to use the Robot class.
Ex-

import java.awt.AWTException;
import java.awt.Robot;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Myntra {
    public static void main(String[] args) throws InterruptedException, AWTException, IOException {
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.navigate().to("http://www.myntra.com/");
        WebElement women = driver.findElement(By.xpath("//div[@class='head']//a[4][@href='/shop/women?src=tn&nav_id=34']"));
       
        Point coordinate = women.getLocation();
        Robot robot = new Robot();
        robot.mouseMove(coordinate.getX()+30, coordinate.getY()+120);
        Thread.sleep(10000);
        driver.findElement(By.xpath("//a[@href='/women-jeans?src=tn&nav_id=48']")).click();
        driver.findElement(By.xpath("//div[@id='login']//div[@class='close']")).click();
       
    }
}

Integrate Automation framework with Build using Jenkins.

‘Jenkins’ is a tool which is used for continuous integration testing.

Please follow the below steps to configure the Jenkins with your Automation Framework-

Step1- click on this link : http://jenkins-ci.org/
Step2- click on ‘Long term support release’ tab which is there in right side.
Step3- click on 'older but stable' then one pop-up will come to save the file & there in pop-up click ‘OK’ which will save Jenkins the war file in the Downloads folder, copy paste the downloaded file inside the project.
Step4- Open the command prompt (cmd) and go to project directory.
For ex- say your project directory is -> C:\selenium\SpiceJet\Owler
so here you open cmd, then give command as cd C:\selenium\SpiceJet\Owler and hit enter
Step5- Then type the command ‘java –jar jenkins.war’ & hit enter.
Step6- If Jenkins server is loaded successfully it will display following message in command prompt.      Jenkins is fully up and running

Step7- Now open the browser & enter the following URL in the address bar “local host:8080” which will display homepage of the Jenkins server.
Step8- Click on New Job & specify the job name
For ex: AutomationFramework
Step9- Select the first radio button ‘Build a free-style software project’ then click on OK.
Step10- Click on ‘Advanced’ & select last checkbox 'use custom workspace' under ‘Advanced Project options’ section.
Step11- Type the java project path in the directory (For ex- the java project path –
C:\selenium\SpiceJet\Owler)
Step12- Go down, There you will find Build section, there click on ‘Add Build Step’ & select ‘Execute Windows Batch Command’ & type ‘RunMe.bat’ in the command field.
**How to create RunMe.bat file -
             a) open notepad
             b) paste this command- java -cp bin;jars/* org.testng.TestNG testng.xml
             c) save the file as RunMe.bat
Step13- Go down and click on Save button.
Step14- Now you are all set to use Jenkins. Click on Build Now. It will start the execution of your framework.
Note- In order to create a Build, Developer clicks on ‘Build Now’ which will start the Build creation process once the build is created it will start Framework execution automatically. Every time when we run the build, Jenkins will display a link under Build History, the name of the link will be current system Date & Time, when we click that link it will take us to Build details page where if we click on ‘Console output’ link it will display output of the Automation Framework which is printed on the command prompt.

Please find snapshot below, where you should put .bat file and jenkins.war

screenshot of project

Please leave your valuable feedback. Thanks!!

Sunday, May 11, 2014

How to get the tooltip for all the images present in the webpage.

Note- code has been done in such a way so that it will not print those title which are blank.


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;

public class Deepika {
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("http://www.swissoutpost.com/");
        List<WebElement> imgs = driver.findElements(By.tagName("img"));
        System.out.println(imgs.size());
        int num =0;
        String toolTip="";
        for(int i=0; i<imgs.size(); i++){
            toolTip = imgs.get(i).getAttribute("title");
            num+=1;
            if(toolTip.equals("")){
            }else{
                System.out.println(toolTip);
            }
        }
        System.out.println(num);
    }
}

How to send a mail through gmail with attachment.



import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;

public class SendMailWithAttachment{
    public static void main(String[] args) throws IOException, InterruptedException {
        Scanner kb = new Scanner(System.in);
        System.out.println("enter ur id: ");
        String id = kb.nextLine();
        System.out.println("enter ur pass: ");
        String password = kb.nextLine();
        System.out.println("enter email-id to whom u want to send the mail: ");
        String toId = kb.nextLine();
        System.out.println("enter subject for mail: ");
        String subject = kb.nextLine();
        System.out.println("enter the content of the mail: ");
        String content = kb.nextLine();
       
        //open gamil
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
        driver.get("https://accounts.google.com/ServiceLogin?service=mail&passive=true&rm=false&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&ss=1&scc=1&ltmpl=default&ltmplcache=2&hl=en&emr=1&elo=1");
       
        //login to gmail
        driver.findElement(By.id("Email")).sendKeys(id);
        driver.findElement(By.xpath("//input[@id='Passwd']")).sendKeys(password);
        driver.findElement(By.xpath("//input[@type='checkbox']")).click();
        driver.findElement(By.name("signIn")).click();
       
        //click on compose and add the to mail id, and subject
        driver.findElement(By.xpath("//div[text()='COMPOSE']")).click();
        driver.findElement(By.xpath("//form[1]//textarea[1]")).sendKeys(toId);
        driver.findElement(By.xpath("//div[@class='aoD az6']//input[@class='aoT']")).sendKeys(subject);
       
        //wirte the mail body, that mail body is under frame so 1st switch the control to frame then write
        driver.switchTo().frame(driver.findElement(By.xpath("//iframe[@tabindex='1']")));
        driver.findElement(By.xpath("//body[@class='editable LW-avf']")).sendKeys(content);
        driver.switchTo().defaultContent(); // again switch back to main page
       
        //click on attachment
        driver.findElement(By.xpath("//div[@class='a1 aaA aMZ']")).click();
        //use autoit tool to attach a file
        Runtime.getRuntime().exec("C:\\selenium\\AutoIT\\fileUpload.exe");
        Thread.sleep(10000); //wait for 10sec to upload file
       
        //click on send
        driver.findElement(By.xpath("//div[text()='Send']")).click();
        String msg = driver.findElement(By.xpath("//div[contains(text(),'Your message has been sent.')]")).getText();
        String exp = "Your message has been sent. View message";
        Assert.assertEquals(msg, exp);
        System.out.println("pass");
        driver.close();
    }
}



Note- Here Autoit tool has been used to attach the file because by using sendKeys() method we can't upload the file in gmail. Below is the script used to upload the file thru autoit-

WinWaitActive("File Upload")
Send("path of the file")
ControlClick("","&Open","Button1")

ex- path of the file = C:\java learn\important cmd for Java.txt

How to login, get the number of mails in inbox and logout from the gmail account.


import java.util.List;
import java.util.Scanner;
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;

public class InboxCount {

    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);
        System.out.println("enter ur gmail id: ");
        String id = kb.nextLine();
        System.out.println("enter ur gmail pass: ");
        String password = kb.nextLine();
       
       
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
        driver.get("https://accounts.google.com/ServiceLogin?service=mail&passive=true&rm=false&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&ss=1&scc=1&ltmpl=default&ltmplcache=2&hl=en&emr=1&elo=1");
        driver.findElement(By.id("Email")).sendKeys(id);
        driver.findElement(By.xpath("//input[@id='Passwd']")).sendKeys(password);
        driver.findElement(By.xpath("//input[@type='checkbox']")).click();
        driver.findElement(By.name("signIn")).click();
       
        String inbox = driver.findElement(By.xpath("//a[@href='https://mail.google.com/mail/u/0/#inbox']")).getText();
        System.out.println(inbox);
       
        //sign out
        driver.findElement(By.xpath("//span[@class='gb_V gbii']")).click();
        driver.findElement(By.linkText("Sign out")).click();
       
        driver.close();
       
    }
}

How to get the suggestion's text by google which come as dropdown while typing in the search box of google.

package BhanuSir;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Scanner;
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.firefox.FirefoxProfile;

public class GoogleSearch {
    public static void main(String[] args) {
        System.out.println("Enter the word which u want to search in Google: ");
        Scanner in = new Scanner(System.in);
        String srchWord = in.nextLine();
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://www.google.co.in/");
       
        driver.findElement(By.name("q")).sendKeys(srchWord);
        //get the test suggested by google from the dropdown.
        List<WebElement> sugg = driver.findElements(By.xpath("//table[@class='gssb_m']/tbody/tr"));
        for(WebElement ele: sugg){
            System.out.println(ele.getText());
        }
        driver.close();
    }
}

How to upload the file.

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class FileUpload {
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        driver.get("http://www.megafileupload.com/");
        driver.findElement(By.xpath("//input[@class='upload_txt']")).sendKeys("path of file to be uploaded");
        driver.findElement(By.cssSelector("input[id='terms']")).click();
        driver.findElement(By.cssSelector("input[name='send']")).click();
    }
}

How to find the broken link in a web page or how to determine a link is working or not.

Note- Here in place of any website i have created my webpage with broken link which i passed as url in to("url") method.

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
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;

public class BrokenLink {
    public static void main(String[] args) throws InterruptedException, IOException {
       
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.navigate().to("file:///C:/Program%20Files%20%28x86%29/sank_java/selenium/WebDriver/Selenium_web.html");
        List<WebElement> elements = driver.findElements(By.tagName("a"));
        System.out.println(elements.size());
       
        for(WebElement linkElement: elements){
            String link = linkElement.getAttribute("href");
            System.out.println(link);
            if(link!=null){
                 if(!isLink(link)){
                     continue;
                 }
            }
            verifyLinkActive(link);
        }
        driver.quit();
    }
    public static boolean isLink(String link){
       
        return link.contains("http://") ;
    }
    public static void verifyLinkActive(String linkUrl) throws IOException{
        try {
            URL url = new URL(linkUrl);
            HttpURLConnection httpURLConnect = (HttpURLConnection)url.openConnection();
            httpURLConnect.setConnectTimeout(3000);
            httpURLConnect.connect();
            if(httpURLConnect.getResponseCode()==HttpURLConnection.HTTP_NOT_FOUND){
                System.out.println(linkUrl+"-"+httpURLConnect.getResponseMessage()+"-"+
            HttpURLConnection.HTTP_NOT_FOUND);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

   
}

How to open browser with Add Ons using WebDriver

Note- File extension = new File("give here the path of the Add Ons file with use you want to open browser.");

import java.io.File;
import java.io.IOException;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;

public class AddOns {
    public static void main(String[] args) {
        File extension = new File("C:/Users/IBM_ADMIN/Documents/SametimeFileTransfers/firebug-1.12.7-fx.xpi");
        FirefoxProfile profile = new FirefoxProfile();
        try {
            profile.addExtension(extension);
        } catch (IOException e) {
            e.printStackTrace();
        }
        WebDriver driver = new FirefoxDriver(profile);
        driver.get("https://mail.google.com/mail/u/0/#inbox");
       
    }
}

What are the advantages of POM (page object model) frame work in selenium ?

Main advantage-
1- avoid to write the duplicate locators for same WebElement which is the big issue in other frameworks.
2- Maintenance of the test script which becomes very easy.
3- improves readability.

What is annotations ? How will u configure in Framework ?

There are many annotations which has been provided in TestNG to make the scripting easy and code reusability.

Here are the Annotations used in TestNG-
@Test
@BeforeSuite, @AfterSuite
@BeforeTest, @AfterTest
@BeforeClass, @AfterClass
@BeforeMethod, @AfterMethod
@DataProvider
@Parameters.

How to use-
ex-
@BeforeMethod
public void openBrow(){
WebDriver driver = new FirefoxDriver();
System.out.println("open browser");
}
@Test
public void atTest(){
System.out.println("here 1st @BeforeMethod will execute then @Test");
}