Wednesday, 18 December 2013

Webdriver commands in java


driver.get("http://www.google.com");
WebElement element = driver.findElement(By.id("coolestWidgetEvah"));
List<WebElement> cheeses = driver.findElements(By.className("cheese"));
WebElement frame = driver.findElement(By.tagName("iframe"));
WebElement cheese = driver.findElement(By.name("cheese"));
WebElement cheese = driver.findElement(By.linkText("cheese"));
WebElement cheese = driver.findElement(By.partialLinkText("cheese"));
WebElement cheese = driver.findElement(By.cssSelector("#food span.dairy.aged"));
List<WebElement> inputs = driver.findElements(By.xpath("//input"));
ebElement element = (WebElement) ((JavascriptExecutor)driver).executeScript("return $('.cheese')[0]");
WebElement select = driver.findElement(By.tagName("select"));
List<WebElement> allOptions = select.findElements(By.tagName("option"));
for (WebElement option : allOptions) {
    System.out.println(String.format("Value is: %s", option.getAttribute("value")));
    option.click();
}
List<WebElement> labels = driver.findElements(By.tagName("label"));
List<WebElement> inputs = (List<WebElement>) ((JavascriptExecutor)driver).executeScript(
    "var labels = arguments[0], inputs = []; for (var i=0; i < labels.length; i++){" +
    "inputs.push(document.getElementById(labels[i].getAttribute('for'))); } return inputs;", labels);
Select select = new Select(driver.findElement(By.tagName("select")));
select.deselectAll();
select.selectByVisibleText("Edam");
driver.findElement(By.id("submit")).click();
element.submit();
driver.switchTo().window("windowName");
for (String handle : driver.getWindowHandles()) {
    driver.switchTo().window(handle);
}
driver.switchTo().frame("frameName");
driver.switchTo().frame("frameName.0.child");
Alert alert = driver.switchTo().alert();
driver.navigate().to("http://www.example.com");
driver.navigate().forward();
driver.navigate().back();
// Go to the correct domain
driver.get("http://www.example.com");

// Now set the cookie. This one's valid for the entire domain
Cookie cookie = new Cookie("key", "value");
driver.manage().addCookie(cookie);

// And now output all the available cookies for the current URL
Set<Cookie> allCookies = driver.manage().getCookies();
for (Cookie loadedCookie : allCookies) {
    System.out.println(String.format("%s -> %s", loadedCookie.getName(), loadedCookie.getValue()));
}

// You can delete cookies in 3 ways
// By name
driver.manage().deleteCookieNamed("CookieName");
// By Cookie
driver.manage().deleteCookie(loadedCookie);
// Or all of them
driver.manage().deleteAllCookies();
FirefoxProfile profile = new FirefoxProfile();
profile.addAdditionalPreference("general.useragent.override", "some UA string");
WebDriver driver = new FirefoxDriver(profile);
WebElement element = driver.findElement(By.name("source"));
WebElement target = driver.findElement(By.name("target"));
(new Actions(driver)).dragAndDrop(element, target).perform();

Drag and Drop in Webdriver in JAVA

Actions builder = new Actions(driver);

   Action dragAndDrop = builder.clickAndHold(someElement)
       .moveToElement(otherElement)
       .release(otherElement)
       .build();

   dragAndDrop.perform();

General Mouse User Interactions Using Webdriver in java

To perform sereies of actions using mouse then do like below

Actions builder = new Actions(driver);
builder.keyDown(Keys.CONTROL)
.click(someElement)
.click(someOtherElement)
.keyUp(Keys.CONTROL);
Action selectMultiple = builder.build();
selectMultiple.perform();

Steps to implement Serenity Automation Framework

coming soon....

Run test cases own ordered way other than TestNG

To run test case by own ordered way other than TestNG having depunit.

download depunit jar file from the below  link:

https://code.google.com/p/depunit/downloads/list

See the below sample code

public class DepUnitTestEX {

   
    @BeforeClass
    public void setUP(){
        System.out.println("---in before");
    }
   
   
   
    @Test(softDependencyOn={"testC"})
    public void testB(){
        System.out.println("----in testB---");       
    }
   
    @AfterClass
    public void tearDown(){
        System.out.println("---in after---");
    }
   
    @Test
    public void testC(){
        System.out.println("----in testC---");
        Assert.fail("test fail");
    }
   
    }

Customize Junit report



Does any body need to customize junit report to add columns and adding own report name is possible by customizing Jreport.

See the below image for sample


Detailed steps to implement ghost driver using phantomjs

1.To implement ghost driver need to create driver instance by passing capabilities to PhantomJsDriver class.
2.Before creating driver instance, in capabilities need to provide the path of the phantomjs driver using PhantomJSDriverService class

3.download PhantomJS

    OR, clone & build PhantomJS
      $> git clone https://github.com/ariya/phantomjs.git && cd phantomjs      
$> ./build.sh
$> ... ... go make some coffee ...
$> cd bin && ./phantomjs
$> export PATH=`pwd`:$PATH ... this is optional ...
(optional) clone GhostDriver (instead of embedded version)
$> git clone https://github.com/detro/ghostdriver.git

4.Bindings

<dependency>
<groupId>com.github.detro.ghostdriver</groupId>
<artifactId>phantomjsdriver</artifactId>
<version>LATEST_VERSION_HERE</version>
</dependency>
... or ...
dependencies {
testCompile "com.github.detro.ghostdriver.phantomjsdriver.LATEST_VERSION_HERE"
}
Java
Python
$> [sudo] easy_install selenium or $> [sudo] pip install selenium
Ruby
$> gem install selenium-webdriver
.Net
PM> Install-Package Selenium.WebDriver

5. Capabilities

DesiredCapabilities caps = new DesiredCapabilities();
// If executable not added to $PATH
caps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
"/path/to/phantomjs");
// If don't want to use embedded GhostDriver
caps.setCapability(PhantomJSDriverService.PHANTOMJS_GHOSTDRIVER_PATH_PROPERTY,
"/path/to/ghostdriver/src/main.js");
WebDriver driver = new PhantomJSDriver(caps);
Java
for Python / Ruby / .Net check documentation

6.Capabilities: Page Settings

DesiredCapabilities caps = new DesiredCapabilities();
// Change setting X to Y on every Web Page created during this WebDriver session
// NOTE: Can use PhantomJSDriverService.PHANTOMJS_PAGE_SETTINGS_PREFIX
caps.setCapability("phantomjs.page.settings.X", "Y");
...
Possible Settings (might change in the future)
page.settings => {
"XSSAuditingEnabled": false,
"javascriptCanCloseWindows": true,
"javascriptCanOpenWindows": true,
"javascriptEnabled": true,
"loadImages": true,
"localToRemoteUrlAccessEnabled": false,
"userAgent": "... AppleWebKit/534.34 ... PhantomJS/1.9.0 (development) ...",
"webSecurityEnabled": true
}

7.Then do the script as like normal driver

see the example code below:

public class GoogleGhostDriverEx {
     WebDriver driver;
        DesiredCapabilities caps;
     @Before
 public void beforeClass() {
          caps = new DesiredCapabilities();
         caps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,"D:\\Downloads-1\\phantomjs\\phantomjs-1.9.2-windows\\phantomjs.exe");                 
         driver = new PhantomJSDriver(caps);
     }
 
 @Test
 public void search() {
   
     try{
         driver.get("http://www.google.co.in");
       
         File srcFile=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
       
         FileUtils.copyFile(srcFile, new File("test.png"));
         driver.findElement(By.name("q")).sendKeys("ghostdriver");
          srcFile=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
         FileUtils.copyFile(srcFile, new File("test2.png"));
       
       
            }catch(Exception e){
                e.printStackTrace();
            }
  }

 @After
 public void afterClass(){
     driver.quit();
  }
  }

Monday, 16 December 2013

Detailed steps to implement selenium grid

1.Down load selenium standlone jar file from https://code.google.com/p/selenium/downloads/list 
 2.Then copy the jar file in any folder.ex c://SeleniumGridEx.
3.Go to that folder using command prompt.
4.Then type this command java -jar selenium-server-standalone-2.xx.xx.jar -role hub--it will act like central for all nodes
5.Any other system you want to be as a node then copy the same jar file in to other systems.
6.Then move to that folder using command prompt for node system and type below command.
 java -jar selenium-server-standalone-2.xx.xx.jar -role node  -hub http://<Ipaddress of hub system>:4444/grid/register
7.Now type this URL http://localhost:4444 in hub system able to see the grid console.

To run script on node system see the below example code.

public class GoogleEx {
     WebDriver driver;
 
    DesiredCapabilities capability;
 @Before
 public void beforeClass(){
      capability= new DesiredCapabilities();
   capability.setCapability("takesScreenshot", true);
    capability.setBrowserName("chrome");
   }
 @Test
 public void search() {
     try{   
         driver= new RemoteWebDriver(new URL("http://<Ipaddress of node  system>:5555/wd/hub"), capability);
   then go on with script.
               

            }catch(Exception e){
                e.printStackTrace();
            }            

  }

 @After
 public void afterClass(){
     driver.quit();
  }
  }