Thursday, 30 July 2015

Download files using autoIt and firefoxProfiles(javaScript) and Robot keys

Download file using autoIt and firefoxProfiles(javaScript)

Autoit:

1) Download autoIT and extract
2) In 'SciTE Script Editor' write the below code and save(save with .au3 format) in specific location.

WinWait("[CLASS:#MozillaDialogClass]","",8)
Send("{ALTDOWN}s{ALTUP}")
Sleep(5000)
Send("{ENTER}")

3) Compile the script, and it will generate .exe application.

Eclipse:
public class Download_AutiIt_pass {

    WebDriver d=new FirefoxDriver();
    @Test
    public void downloadAutoIT() throws IOException
    {
        d.get("http://only-testing-blog.blogspot.in/2014/05/login.html");
        d.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS);
        d.findElement(By.xpath("//a[text()='Download Text File']")).click();
        Runtime.getRuntime().exec("D:\\Automation_workspace\\AutoIT\\download_keyboard_autoIT.exe");
           //give the path of .exe(after compile :step 3)   
    }
}
output:
It will downloads the file

  Download file using firefoxProfiles:

selenium webdriver do not have any feature to handle this save file dialogue.
 But yes, Selenium webdriver has one more very good feature by which you do not need to handle that dialogue
and you can download any file very easily. We can do It using webdriver's Inbuilt class FirefoxProfile and Its
 different methods

Code:
package testcases;

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.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.testng.annotations.Test;

public class Download_File_pass {

    WebDriver d=new FirefoxDriver();
    @Test
    public void downloadAutoIT() throws IOException, AWTException
    {
        FirefoxProfile pro=new FirefoxProfile();
        pro.setPreference("browser.download.folderList",2);
        pro.setPreference("browser.download.manager.showWhenStarting",false);
        pro.setPreference("browser.download.dir","D:\\Automation_workspace\\AutoIT\\downloaded_files");
        pro.setPreference("browser.helperApps.neverAsk.saveToDisk","application/octet-stream;application/csv;text/csv;application/vnd.ms-excel;");
           WebDriver d=new FirefoxDriver(pro);
        d.get("http://www.ox.ac.uk/admissions/graduate/applying-to-oxford/after-you-apply/accepting-your-offer");
        d.manage().timeouts().implicitlyWait(120, TimeUnit.SECONDS);
        d.manage().window().maximize();
        d.findElement(By.xpath("//*[@id='block-ds-extras-oxweb-ds-page-content-right']/div/div/div/div[2]/a")).click();
         WebElement element = d.findElement(By.xpath("//*[@id='block-menu-block-9']/h2/a"));
            ((JavascriptExecutor) d).executeScript("arguments[0].scrollIntoView(true);", element);

            d.findElement(By.xpath("//a[text()='Cancellation form']")).click();                       
    }
        }
output:
it will download the file 

+++++++Other way+++++
 package interview;

import java.util.concurrent.TimeUnit;

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

public class Auto_it {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

           
        FirefoxProfile profile=new FirefoxProfile();
        profile.setPreference("browser.download.folderList", 2);
        profile.setPreference("browser.download.dir", "D:\\selenium_NEW_PRACTICE");// give path where u want to download file
        profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf, application/x-pdf,text/csv,application/zip");
     
        WebDriver driver=new FirefoxDriver(profile);

   
        driver.get("http://seleniumhq.org/download/");
        driver.manage().timeouts().implicitlyWait(9000,TimeUnit.SECONDS);
        driver.findElement(By.xpath("html/body/div[1]/div[2]/div[2]/p[6]/a")).click();
        System.out.println("hiiii");
        driver.close();
   
    }
   

}


+++++Using robot keys++++++++++
driver21.findElement(By.xpath("//*[@id='csvbutton']")).click();
      Thread.sleep(20000);
      Robot robot = new Robot();
      robot.keyPress(KeyEvent.VK_ALT);
      robot.keyPress(KeyEvent.VK_S);
      robot.keyRelease(KeyEvent.VK_S);
       robot.keyRelease(KeyEvent.VK_ALT);
       robot.keyPress(KeyEvent.VK_ENTER);
       System.out.println("File is downloaded");

Scroll up/down using javaScript


package interview_practice;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.*;
import java.awt.event.KeyEvent;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriver.Window;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class ScrollDown_JavaScript {
     WebDriver driver;
@BeforeTest
 public void setup() throws Exception {
      driver = new FirefoxDriver();
      driver.manage().window().maximize();
     }
//@Test(priority=0) //working fine
public void Scroll_Page_usingJavaScript()
{
    driver.get("http://google.com");
    driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
     //To scroll down web page by 600 pixels In x(vertical) direction. 
      //You can y parameter to scroll page In horizontal direction
    JavascriptExecutor javascript = (JavascriptExecutor) driver;
    javascript.executeScript("window.scrollBy(0,600)", "");
     //To scroll up web page by 300 pixels In x(vertical) direction.
      javascript.executeScript("window.scrollBy(0,-300)", "");
   
    }
//@Test(priority=1) //working fine
public void Scroll_totalDown_usingJavaScript() throws AWTException
{
    driver.get("http://googlet.com");
    driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
    //Scroll down to bottom of the page.
      JavascriptExecutor javascript = (JavascriptExecutor) driver;
      javascript.executeScript("window.scrollTo(0, document.body.scrollHeight)", ""); 
   
    }

//Scroll till element.
//@Test(priority=2)  //working fine
public void Scroll_till_element_usingJavaScript() throws AWTException
{
    driver.get("http://google.com");
    driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
    JavascriptExecutor je = (JavascriptExecutor) driver;
    WebElement element = driver.findElement(By.xpath("//div[@id='dragdiv']"));
    je.executeScript("arguments[0].scrollIntoView(true);",element);
   
    }
@Test(priority=3)   //pending
public void Scroll_window_usingRobotKeys() throws AWTException
{
    driver.get("http://google.com");
    driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
    Robot robot = new Robot();
    robot.keyPress(KeyEvent.VK_PAGE_DOWN);
    robot.keyRelease(KeyEvent.VK_PAGE_DOWN);
   

   
    }


}

Set/Get window position and size(height and width)

package interview_practice;

import org.openqa.selenium.Dimension;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class Set_Get_WindowPosition_Size {
     WebDriver driver;
@BeforeTest
 public void setup() throws Exception {
      driver = new FirefoxDriver();
      driver.manage().window().maximize();
     }
@Test(priority=0)
public void setWindowSizePosition()
{
    driver.get("http://www.google.com");   
     //WebDriver setSize method used to set window size width = 300 and height = 500.
    driver.manage().window().setSize(new Dimension(300, 500));
   
    //WebDriver getSize method used to get window width and height
    Dimension getWinSize=driver.manage().window().getSize();
    System.out.println("current view of window hight size is :" + getWinSize.getHeight());
    System.out.println("current view of window Width size is :" + getWinSize.getWidth());
   
}
@Test(priority=1)
public void setWindowPosition()
{
    driver.manage().window().setPosition(new Point(50, 200));
    Point getWinSize=driver.manage().window().getPosition();
    System.out.println("current view of window hight size is :" + getWinSize.getX());
    System.out.println("current view of window Width size is :" + getWinSize.getY());
   
}
@AfterTest
public void tearDown() throws Exception
{
    driver.close();
}
}
+++++++++++++Change window position+++++++++++
 package All_Types_Run;
import java.awt.AWTException;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Change_Window_Position
{
public static void main(String[] args) throws InterruptedException, AWTException
{
    WebDriver driver = new FirefoxDriver();
    driver.get("http:\\google.com");
    driver.manage().window().setPosition(new Point(0,0)); //move the window to top right corner
    Thread.sleep(2000);
    driver.manage().window().setPosition(new Point(500,400)); //move the window to 500unit horizontally and 400unit vertical
}
}

Tuesday, 28 July 2015

How to add date format to string / append date format to string

Date date = new Date() ;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss") ;
File file = new File(dateFormat.format(date) ) ;
String name="prava1";
d.findElement(By.xpath("//*[@id='Email']")).sendKeys(name+"_"+file);

Tuesday, 21 July 2015

How to upload file using AutoIT and robot Keys

AutoIT:

1) Download autoIT and extract
2) In 'SciTE Script Editor' write the below code and save(save with .au3 format) in specific location.

ControlFocus ( "File Upload", "", "Edit1" )
Sleep(1000)
ControlSetText("File Upload", "", "Edit1","C:\Users\pabbu\Desktop\logo11w.png") (image/file location)
Sleep(2000)
ControlClick("File Upload", "","Button1");

3) Compile the script, and it will generate .exe application.

Eclips: write the below code in eclipse
@Test
public void uploadAutoIT() throws IOException
{
d.get("http://www.toolsqa.com/automation-practice-form/");
d.manage().timeouts().implicitlyWait(120, TimeUnit.SECONDS);
d.findElement(By.xpath("//*[@id='photo']")).click();
Runtime.getRuntime().exec("D:\\Automation_workspace\\Rought_importFindings\\export\\File_upload_1");
//give the path of .exe from step 3.
}

Output:
It will upload the file

Robot keys:

package All_Types_Run;

import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import java.awt.*;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class Upload_File {

@Test
public void Fileupload() throws AWTException, InterruptedException{

 WebDriver driver = new FirefoxDriver();
 driver.manage().window().maximize();
       
        // Specify the file location with extension
 StringSelection sel = new StringSelection("C:\\Users\\Desktop\\1.doc");

        // Copy to clipboard
 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(sel,null);
 System.out.println("selection" +sel);

 driver.get("http://my.monsterindia.com/create_account.html");
 Thread.sleep(2000);


 JavascriptExecutor js = (JavascriptExecutor)driver;
 js.executeScript("scroll(0,350)");
 Thread.sleep(5000);
 driver.findElement(By.id("wordresume")).click();
 Thread.sleep(2000);
 System.out.println("Browse button clicked");

        // Create object of Robot class
 Robot robot = new Robot();
 Thread.sleep(1000);
      
        // Press Enter
 robot.keyPress(KeyEvent.VK_ENTER);
 robot.keyRelease(KeyEvent.VK_ENTER);

        // Press CTRL+V
 robot.keyPress(KeyEvent.VK_CONTROL);
 robot.keyPress(KeyEvent.VK_V);
 robot.keyRelease(KeyEvent.VK_CONTROL);
 robot.keyRelease(KeyEvent.VK_V);
 Thread.sleep(1000);
       

 robot.keyPress(KeyEvent.VK_ENTER);
 robot.keyRelease(KeyEvent.VK_ENTER);

}

}
++++++Another Example +++++
package abcpack;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.*;

public class FileUpload_AutoIT {
public WebDriver driver;

@BeforeMethod
public void setUp() throws Exception
{
    driver= new FirefoxDriver();
    driver.manage().window().maximize();
}
@Test
public void testFileupload() throws Exception
{
    driver.get("http://www.2shared.com/");
    driver.findElement(By.id("upField")).click();
    Thread.sleep(2000);
    Process p = new ProcessBuilder("F:\\Selenium_Scripts_July13\\AutoIt Examples\\FileUpload.exe").start();
    Thread.sleep(3000);
    driver.findElement(By.xpath("//input[@title='Upload file']")).click();
    Thread.sleep(5000);
}

@AfterMethod
public void tearDown() throws Exception {
driver.quit();
}
}

++++++++++++
@Test
public void handlingWindowPopups() throws AWTException, InterruptedException, IOException
{
    String file="C:\\Users\\pravanjan.reddy\\Desktop\\stf.txt";
    driver.get("http://toolsqa.com/automation-practice-form/?firstname=&lastname=&sex=Female&photo=&continents=Asia&submit=");
    driver.findElement(By.xpath("//*[@id='photo']")).click();
   
    //way 1 using Robot class
     StringSelection ss = new StringSelection("C:\\Users\\pravanjan.reddy\\Desktop\\stf.txt");
     Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
    //imitate mouse events like ENTER, CTRL+C, CTRL+V
        Robot robot = new Robot();
        robot.keyPress(KeyEvent.VK_ENTER);
        robot.keyRelease(KeyEvent.VK_ENTER);
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_ENTER);
        robot.keyRelease(KeyEvent.VK_ENTER);
}





How get selected option/name text from dropdown

//Scenario: Want to get the selected option from dropdown

String selectedOption = new Select(d.findElement(By.xpath("//*[@id='cstate']"))).getFirstSelectedOption().getText();
System.out.println("Selected state is :" + selectedOption);
Assert.assertEquals("ASSAM", selectedOption);

Output: It verifys whether the selected option is 'assam' or not.

Print all the drop down values, if specific value matches(equals) then select the value from drop down


//Scenario: If assam option is available in dropdown then select the value.
public void verifySeletedDDValue()
{


d.get("https:/oaa.onlinesbi.com/oao/onlineaccapp.htm");
d.manage().timeouts().implicitlyWait(150, TimeUnit.SECONDS);
//clicking on apply now button
d.findElement(By.xpath("//*[@id='btnApply']/a/img")).click();
d.findElement(By.xpath("//a[text()='Start New']")).click();

//for get default text fron text field
String defaultTxt =d.findElement(By.xpath("//*[@id='firstName']")).getAttribute("value");
System.out.println("printing default text on text filed :" +defaultTxt);

//working fine
String allStates=d.findElement(By.xpath("//*[@id='cstate']")).getText();
System.out.println("all options from dropdown :" + allStates);

WebElement select=d.findElement(By.xpath("//*[@id='cstate']"));
List<WebElement> options = select.findElements(By.tagName("option"));
System.out.println("all options are :" + options);
for (WebElement option : options) {
    if("ASSAM".equals(option.getText()))
        option.click();
}

output: it will search for 'Assam'  and it selects the ''assam"

Split the string(specific) and split string with equal sign

 String expTitle=[Logged in as: admin@gmail.com , Logout?]

Scenario 1: From the above string want display only 'admin@gmail.com'

Program:
public class Split {

public static void main(String[] args) {
String title="[Logged in as: admin@gmail.com , Logout?]";
String[] one=title.split(": ");
System.out.println(one[1]);
String[] two=one[1].split(" ,");
System.out.println(two[0]);

}

}
output:
//here it will prints "admin@gmail.com"

++++++++++++++++++++++++++++++
Scenario 2: i want to print only 'cell movement'
public static void main(String[] args) {
String title="[cell movement, , ]";



String[] one=title.split("\\[");
System.out.println(one[1]);

String[] two=one[1].split(",");
System.out.println(two[0]);


}
output:
//here it will prints "cell movement"
++++++++++++
  String str = "21= A=Person"; , here i want want split with "="   sign
public class Split_String_with_Equal_Sign {
           
             public static void main(String[] args) throws InterruptedException {
           
              String str = "21= A=Person";
              String s[]=str.split("\\=");
              String s2 = "";
              for(int i=1;i<s.length;i++){
               s2=s2+"="+s[i];
              }
              System.out.println(s2.replaceFirst("=", ""));
             }
    }

Output : A=Person